mirror of
https://github.com/storytold/texturecraft.git
synced 2026-12-01 21:47:59 +00:00
Keep live layer updates on the GPU and expose preview controls
This commit is contained in:
@@ -45,6 +45,11 @@ 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 }
|
||||
}
|
||||
|
||||
pub(crate) fn bytes(&self) -> usize {
|
||||
self.dense.get().map_or(0, |map| map.src.capacity() * size_of::<u32>())
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@ use texturecraft_paint::{
|
||||
rasterize,
|
||||
};
|
||||
|
||||
use crate::session::{ActiveStroke, CloneFrom, QUICK_MASK_STROKE_LABEL, Session, StackTarget, Tool, history_label, stroke_template};
|
||||
use crate::session::{
|
||||
ActiveStroke, CloneFrom, DisplayStrokeEnd, QUICK_MASK_STROKE_LABEL, Session, StackTarget, Tool, history_label, next_mesh_id, stroke_template,
|
||||
};
|
||||
use crate::uv_stroke_state::UvStrokeState;
|
||||
use crate::uv_symmetry::UvMirror;
|
||||
use crate::{EngineError, Result};
|
||||
@@ -323,6 +325,8 @@ impl Session {
|
||||
history_label(stroke_template(tool, on_mask), &self.stroke_layer_name())
|
||||
};
|
||||
self.stroke = Some(ActiveStroke {
|
||||
display_id: next_mesh_id(),
|
||||
display_tiles: BTreeSet::new(),
|
||||
ts,
|
||||
target,
|
||||
stroke,
|
||||
@@ -537,6 +541,7 @@ impl Session {
|
||||
PaintTarget::Mask(eid) => staging.stage_mask(pixels, eid, mask_value, &src),
|
||||
});
|
||||
st.staging = staging;
|
||||
st.display_tiles.extend(recent.iter().copied());
|
||||
self.mark_painted(ts, target, recent);
|
||||
}
|
||||
|
||||
@@ -544,6 +549,57 @@ impl Session {
|
||||
self.stroke.is_some()
|
||||
}
|
||||
|
||||
/// Identity and tiles of a supported live stroke since the display last drew it.
|
||||
pub fn pending_display_stroke(&self, ts: usize) -> Option<(u64, &BTreeSet<(u32, u32)>)> {
|
||||
let stroke = self.stroke.as_ref()?;
|
||||
(stroke.ts == ts && stroke.target.is_some() && stroke.stencil.is_none() && stroke.canvas.pickup.is_none())
|
||||
.then_some((stroke.display_id, &stroke.display_tiles))
|
||||
}
|
||||
|
||||
/// Copy-on-write material pixels for display. The staged blends are the same tiles the
|
||||
/// completed stroke will install. The live viewport does not change the document or Undo.
|
||||
pub fn display_stroke_pixels(&self, ts: usize, texel_bounds: Option<([u32; 2], [u32; 2])>) -> Option<texturecraft_compose::PixelStore> {
|
||||
self.pending_display_stroke(ts)?;
|
||||
let stroke = self.stroke.as_ref()?;
|
||||
let tiles_in_bounds;
|
||||
let touched = if let Some((min, max)) = texel_bounds {
|
||||
use texturecraft_texel::TILE;
|
||||
tiles_in_bounds = stroke
|
||||
.canvas
|
||||
.dirty
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|&(x, y)| {
|
||||
let (x, y) = (x * TILE, y * TILE);
|
||||
x >= min[0] && x < max[0] && y >= min[1] && y < max[1]
|
||||
})
|
||||
.collect();
|
||||
&tiles_in_bounds
|
||||
} else {
|
||||
&stroke.canvas.dirty
|
||||
};
|
||||
let size = (stroke.canvas.alpha.width(), stroke.canvas.alpha.height());
|
||||
let mut pixels = self.doc.pixels.clone();
|
||||
let mut staging = stroke.staging.snapshot(touched);
|
||||
with_commit_source(stroke, None, &self.mesh, touched, |source| match stroke.target {
|
||||
Some(PaintTarget::Layer(id)) => commit_layer(&mut pixels, id, size, &stroke.values, source, &mut staging),
|
||||
Some(PaintTarget::Mask(id)) => commit_mask(&mut pixels, id, size, self.tool.mask_value, source, &mut staging),
|
||||
None => {}
|
||||
});
|
||||
Some(pixels)
|
||||
}
|
||||
|
||||
pub fn clear_display_stroke_tiles(&mut self) {
|
||||
if let Some(stroke) = self.stroke.as_mut() {
|
||||
stroke.display_tiles.clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finished_display_stroke(&self, ts: usize, id: u64, previous_revision: u64) -> Option<&BTreeSet<(u32, u32)>> {
|
||||
let end = self.display_stroke_end.as_ref()?;
|
||||
(end.ts == ts && end.id == id && end.previous_revision == previous_revision && end.revision == self.revision).then_some(&end.tiles)
|
||||
}
|
||||
|
||||
/// Commit the active stroke (one undo step).
|
||||
pub fn end_stroke(&mut self) -> Result<()> {
|
||||
let brush_tile = self.tile_demand(None).brush;
|
||||
@@ -578,7 +634,9 @@ impl Session {
|
||||
}
|
||||
self.redo.clear();
|
||||
self.modified = true;
|
||||
let previous_revision = self.revision;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.display_stroke_end = Some(DisplayStrokeEnd { id: st.display_id, ts: st.ts, previous_revision, revision: self.revision, tiles: st.display_tiles });
|
||||
// The live preview already shows the committed result: the stroke's tiles recomposite
|
||||
// from the committed pixels at low priority, without holding up this frame.
|
||||
self.mark_settle(st.ts, st.target, st.canvas.dirty.iter().copied());
|
||||
@@ -596,6 +654,8 @@ impl Session {
|
||||
self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1);
|
||||
}
|
||||
self.doc = st.before;
|
||||
self.display_stroke_end =
|
||||
Some(DisplayStrokeEnd { id: st.display_id, ts: st.ts, previous_revision: self.revision, revision: self.revision, tiles: st.canvas.dirty });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -417,7 +417,18 @@ pub enum StackTarget {
|
||||
Effect(LayerId),
|
||||
}
|
||||
|
||||
/// Work left in the viewport after a stroke committed or was cancelled.
|
||||
pub(crate) struct DisplayStrokeEnd {
|
||||
pub id: u64,
|
||||
pub ts: usize,
|
||||
pub previous_revision: u64,
|
||||
pub revision: u64,
|
||||
pub tiles: BTreeSet<(u32, u32)>,
|
||||
}
|
||||
|
||||
pub(crate) struct ActiveStroke {
|
||||
pub display_id: u64,
|
||||
pub display_tiles: BTreeSet<(u32, u32)>,
|
||||
pub ts: usize,
|
||||
/// None: the stroke edits the quick mask.
|
||||
pub target: Option<PaintTarget>,
|
||||
@@ -529,6 +540,7 @@ pub struct Session {
|
||||
/// Viewport size (pixels) used by scripted strokes.
|
||||
pub viewport: Vec2,
|
||||
pub(crate) stroke: Option<ActiveStroke>,
|
||||
pub(crate) display_stroke_end: Option<DisplayStrokeEnd>,
|
||||
/// Layer clipboard: a document snapshot and the copied layer (or effect).
|
||||
pub clipboard: Option<(Document, LayerId)>,
|
||||
/// Decoded image resources (rebuilt from `doc.resources` by `Session::sync_images`).
|
||||
@@ -613,6 +625,7 @@ impl Session {
|
||||
bake_preview: None,
|
||||
viewport: Vec2::new(1280.0, 800.0),
|
||||
stroke: None,
|
||||
display_stroke_end: None,
|
||||
clipboard: None,
|
||||
images: Default::default(),
|
||||
quick_mask: Default::default(),
|
||||
@@ -1476,7 +1489,7 @@ pub(crate) fn uv_layout(t: &TextureSet) -> (usize, Vec<(u32, f32)>) {
|
||||
(t.material, t.uv_tiles.iter().map(|u| (*u, t.tile_scale(*u))).collect())
|
||||
}
|
||||
|
||||
fn next_mesh_id() -> u64 {
|
||||
pub(crate) fn next_mesh_id() -> u64 {
|
||||
static NEXT_MESH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
NEXT_MESH.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ impl BlendKey {
|
||||
}
|
||||
|
||||
/// One destination tile prepared while the stroke is drawn.
|
||||
#[derive(Debug)]
|
||||
#[derive(Clone, Debug)]
|
||||
struct StagedTile {
|
||||
/// The layer tile it was copied from (None: the layer had no tile there).
|
||||
from: Option<TileData>,
|
||||
@@ -248,6 +248,19 @@ impl Staging {
|
||||
self.images.entry(None).or_default().stage(pixels.masks.get(&effect), 2, &b, src);
|
||||
}
|
||||
|
||||
/// Copy only the destination tiles the live viewport is about to show.
|
||||
pub fn snapshot(&self, tiles: &BTreeSet<(u32, u32)>) -> Self {
|
||||
let images = self
|
||||
.images
|
||||
.iter()
|
||||
.map(|(channel, image)| {
|
||||
let tiles = tiles.iter().filter_map(|tile| image.tiles.get(tile).map(|data| (*tile, data.clone()))).collect();
|
||||
(*channel, StagedImage { key: image.key.clone(), tiles })
|
||||
})
|
||||
.collect();
|
||||
Self { images }
|
||||
}
|
||||
|
||||
fn take(&mut self, key: Option<Channel>) -> Option<StagedImage> {
|
||||
self.images.remove(&key)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
//! Compile the viewport's supported UV fills to a small GPU layer program.
|
||||
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
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::{TILE, TILE_AREA, TileImage};
|
||||
use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage};
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
const MAX_LAYERS: usize = 128;
|
||||
@@ -29,11 +32,50 @@ struct Operation {
|
||||
effects: [u32; 4],
|
||||
}
|
||||
|
||||
/// Inclusive origin and exclusive end of a material update, in document texels.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct CompositeRegion {
|
||||
pub(crate) min: [u32; 2],
|
||||
pub(crate) max: [u32; 2],
|
||||
}
|
||||
|
||||
impl CompositeRegion {
|
||||
pub fn from_tiles(tiles: impl IntoIterator<Item = (u32, u32)>) -> Option<Self> {
|
||||
let mut tiles = tiles.into_iter();
|
||||
let (x, y) = tiles.next()?;
|
||||
let mut region = Self { min: [x * TILE, y * TILE], max: [(x + 1) * TILE, (y + 1) * TILE] };
|
||||
for (x, y) in tiles {
|
||||
region.min = [region.min[0].min(x * TILE), region.min[1].min(y * TILE)];
|
||||
region.max = [region.max[0].max((x + 1) * TILE), region.max[1].max((y + 1) * TILE)];
|
||||
}
|
||||
Some(region)
|
||||
}
|
||||
|
||||
fn includes_tile(self, x: u32, y: u32) -> bool {
|
||||
let (x, y) = (x * TILE, y * TILE);
|
||||
x >= self.min[0] && x < self.max[0] && y >= self.min[1] && y < self.max[1]
|
||||
}
|
||||
|
||||
pub fn expanded(self, texels: u32) -> Self {
|
||||
Self { min: self.min.map(|x| x.saturating_sub(texels)), max: self.max.map(|x| x.saturating_add(texels)) }
|
||||
}
|
||||
|
||||
pub fn bounds(self) -> ([u32; 2], [u32; 2]) {
|
||||
(self.min, self.max)
|
||||
}
|
||||
|
||||
pub(crate) fn viewport(self, shift: u32, size: (u32, u32)) -> Self {
|
||||
Self { min: [self.min[0] >> shift, self.min[1] >> shift], max: [(self.max[0] >> shift).min(size.0), (self.max[1] >> shift).min(size.1)] }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CompositeProgram {
|
||||
operations: Vec<Operation>,
|
||||
layer_count: u32,
|
||||
paint: Vec<u32>,
|
||||
pub(crate) region: Option<CompositeRegion>,
|
||||
pub(crate) coverage: Option<Arc<DilationMap>>,
|
||||
pub(crate) writes_height: bool,
|
||||
pub(crate) writes_normal: bool,
|
||||
}
|
||||
@@ -43,9 +85,18 @@ impl CompositeProgram {
|
||||
(self.paint.len() * size_of::<u32>()) as u64
|
||||
}
|
||||
|
||||
/// 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;
|
||||
}
|
||||
|
||||
/// A flat stack of sparse paint, solid and UV procedural fills, masks and point effects.
|
||||
/// Disabled layers need no work. Stacks outside this evaluator's domain use the CPU.
|
||||
pub fn compile(project: &Project, pixels: &PixelStore, ts: usize) -> Option<Self> {
|
||||
Self::compile_region(project, pixels, ts, None)
|
||||
}
|
||||
|
||||
pub fn compile_region(project: &Project, pixels: &PixelStore, ts: usize, region: Option<CompositeRegion>) -> Option<Self> {
|
||||
use Channel::*;
|
||||
let set = project.texture_sets.get(ts)?;
|
||||
if !set.uv_tiles.is_empty() || set.has_channel(Glossiness) {
|
||||
@@ -74,7 +125,7 @@ impl CompositeProgram {
|
||||
if (image.width(), image.height()) != set.size() || image.comps() != 2 {
|
||||
return None;
|
||||
}
|
||||
Operation { ids: [0, 10, pack_paint(&mut paint, image)?, 2], ..Operation::zeroed() }
|
||||
Operation { ids: [0, 10, pack_paint(&mut paint, image, region.map(|r| r.expanded(TILE)))?, 2], ..Operation::zeroed() }
|
||||
}
|
||||
_ => point_effect(effect)?,
|
||||
};
|
||||
@@ -148,7 +199,7 @@ impl CompositeProgram {
|
||||
_ => return None,
|
||||
};
|
||||
let mut op = if let Some(image) = painted {
|
||||
Operation { ids: [slot, 10, pack_paint(&mut paint, image)?, image.comps() as u32], ..Operation::zeroed() }
|
||||
Operation { ids: [slot, 10, pack_paint(&mut paint, image, region.map(|r| r.expanded(TILE)))?, image.comps() as u32], ..Operation::zeroed() }
|
||||
} else {
|
||||
source_operation(source, &fill?.projection, default)?
|
||||
};
|
||||
@@ -175,7 +226,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, writes_height, writes_normal })
|
||||
Some(Self { operations, layer_count, paint, region, coverage: None, writes_height, writes_normal })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -288,15 +339,18 @@ fn point_effect(effect: &Effect) -> Option<Operation> {
|
||||
|
||||
/// An index for each document tile followed by the texels of allocated tiles. Two u16
|
||||
/// components fit in each word. A missing tile leaves the accumulated material untouched.
|
||||
fn pack_paint(dst: &mut Vec<u32>, image: &TileImage) -> Option<u32> {
|
||||
fn pack_paint(dst: &mut Vec<u32>, image: &TileImage, region: Option<CompositeRegion>) -> Option<u32> {
|
||||
let table = dst.len();
|
||||
let count = image.tiles_x() as usize * image.tiles_y() as usize;
|
||||
let words_per_tile = TILE_AREA * image.comps() / 2;
|
||||
if table.checked_add(count)?.checked_add(image.allocated_count().checked_mul(words_per_tile)?)? > MAX_PAINT_WORDS {
|
||||
if table.checked_add(count)? > MAX_PAINT_WORDS {
|
||||
return None;
|
||||
}
|
||||
dst.resize(table + count, 0);
|
||||
for (x, y) in image.allocated() {
|
||||
for (x, y) in image.allocated().filter(|&(x, y)| region.is_none_or(|r| r.includes_tile(x, y))) {
|
||||
if dst.len().checked_add(words_per_tile)? > MAX_PAINT_WORDS {
|
||||
return None;
|
||||
}
|
||||
let texels = image.tile(x, y)?;
|
||||
let (pairs, remainder) = texels.as_chunks::<2>();
|
||||
if pairs.len() != words_per_tile || !remainder.is_empty() {
|
||||
@@ -312,12 +366,14 @@ fn pack_paint(dst: &mut Vec<u32>, image: &TileImage) -> Option<u32> {
|
||||
pub(crate) struct GpuCompositor {
|
||||
pipeline: wgpu::ComputePipeline,
|
||||
lookup: wgpu::Buffer,
|
||||
uniform_coverage: wgpu::Buffer,
|
||||
coverage: Option<(Weak<DilationMap>, u32, wgpu::Buffer)>,
|
||||
}
|
||||
|
||||
impl GpuCompositor {
|
||||
pub(crate) fn supports(device: &wgpu::Device) -> bool {
|
||||
let limits = device.limits();
|
||||
limits.max_storage_buffers_per_shader_stage >= 4
|
||||
limits.max_storage_buffers_per_shader_stage >= 5
|
||||
&& limits.max_compute_invocations_per_workgroup >= WORKGROUP * WORKGROUP
|
||||
&& limits.max_compute_workgroup_size_x >= WORKGROUP
|
||||
&& limits.max_compute_workgroup_size_y >= WORKGROUP
|
||||
@@ -342,22 +398,77 @@ impl GpuCompositor {
|
||||
contents: bytemuck::cast_slice(&values),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
});
|
||||
Self { pipeline, lookup }
|
||||
let uniform_coverage = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("tc_composite_uniform_coverage"),
|
||||
contents: &[0; 4],
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
});
|
||||
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> {
|
||||
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
|
||||
&& 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 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))
|
||||
};
|
||||
// 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()));
|
||||
Ok(buffer)
|
||||
}
|
||||
|
||||
/// Compose bands into reusable GPU scratch space, then copy them into display textures.
|
||||
/// Indexed/SRGB and floating-point maps use the same formats as the CPU uploader.
|
||||
pub(crate) fn encode(
|
||||
&self,
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
program: &CompositeProgram,
|
||||
source_size: (u32, u32),
|
||||
shift: u32,
|
||||
textures: [&wgpu::Texture; 4],
|
||||
) {
|
||||
let width = textures[0].width();
|
||||
let height = textures[0].height();
|
||||
) -> Result<(), String> {
|
||||
let extent = (textures[0].width(), textures[0].height());
|
||||
let coverage = self.coverage_buffer(device, program.coverage.as_ref(), shift, extent)?;
|
||||
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);
|
||||
let height = region.max[1].saturating_sub(start_y);
|
||||
if width == 0 || height == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let bands = height.div_ceil(ROWS);
|
||||
let pitch = width.next_multiple_of(64);
|
||||
let area = pitch * ROWS;
|
||||
@@ -393,7 +504,7 @@ impl GpuCompositor {
|
||||
let values = [
|
||||
width,
|
||||
rows,
|
||||
top,
|
||||
top + start_y,
|
||||
area,
|
||||
source_size.0,
|
||||
source_size.1,
|
||||
@@ -402,6 +513,10 @@ impl GpuCompositor {
|
||||
program.layer_count,
|
||||
pitch,
|
||||
u32::from(program.writes_normal),
|
||||
left,
|
||||
u32::from(program.coverage.is_some()),
|
||||
extent.0,
|
||||
0,
|
||||
0,
|
||||
];
|
||||
let params = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
@@ -418,6 +533,7 @@ impl GpuCompositor {
|
||||
wgpu::BindGroupEntry { binding: 2, resource: self.lookup.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 3, resource: scratch.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 4, resource: paint.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 5, resource: coverage.as_entire_binding() },
|
||||
],
|
||||
});
|
||||
{
|
||||
@@ -436,10 +552,11 @@ impl GpuCompositor {
|
||||
buffer: &scratch,
|
||||
layout: wgpu::TexelCopyBufferLayout { offset: stride * offset, bytes_per_row: Some(pitch * bytes_per_texel), rows_per_image: None },
|
||||
},
|
||||
wgpu::TexelCopyTextureInfo { origin: wgpu::Origin3d { x: 0, y: top, z: 0 }, ..texture.as_image_copy() },
|
||||
wgpu::TexelCopyTextureInfo { origin: wgpu::Origin3d { x: left, y: start_y + top, z: 0 }, ..texture.as_image_copy() },
|
||||
wgpu::Extent3d { width, height: rows, depth_or_array_layers: 1 },
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1537,7 +1537,7 @@ impl Renderer {
|
||||
}
|
||||
|
||||
let (compositor, textures) = crate::gpu_trace::scoped(device, "viewport GPU composite", || {
|
||||
let compositor = self.compositor.take().unwrap_or_else(|| GpuCompositor::new(device));
|
||||
let mut compositor = self.compositor.take().unwrap_or_else(|| GpuCompositor::new(device));
|
||||
let mut maps: Vec<_> = DisplayKind::ALL
|
||||
.iter()
|
||||
.zip(&self.default_texels)
|
||||
@@ -1549,26 +1549,37 @@ impl Renderer {
|
||||
let extent = if composed { size } else { (1, 1) };
|
||||
if extent == (old.texture.width(), old.texture.height()) {
|
||||
old.clone()
|
||||
} else if composed {
|
||||
} else if composed && program.region.is_none() {
|
||||
Tex::new(device, "tc_composite", extent.0, extent.1, display_format(kind), mip_count(extent.0.max(extent.1)))
|
||||
} else {
|
||||
neutral_tex(device, queue, extent, display_format(kind), 1, neutral)
|
||||
neutral_tex(device, queue, extent, display_format(kind), mip_count(extent.0.max(extent.1)), neutral)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_composite") });
|
||||
if let (Some(base), Some(orm), Some(height), Some(normal)) = (maps.first(), maps.get(1), maps.get(3), maps.get(2)) {
|
||||
compositor.encode(device, &mut encoder, program, set.size, set.shift, [&base.texture, &orm.texture, &height.texture, &normal.texture]);
|
||||
compositor.encode(device, &mut encoder, program, set.size, set.shift, [&base.texture, &orm.texture, &height.texture, &normal.texture])?;
|
||||
}
|
||||
queue.submit([encoder.finish()]);
|
||||
maps.extend(set.tex.last().cloned());
|
||||
(compositor, maps)
|
||||
})?;
|
||||
Ok::<_, String>((compositor, maps))
|
||||
})??;
|
||||
self.compositor = Some(compositor);
|
||||
if let Some(set) = self.sets.get_mut(ts) {
|
||||
let region = program.region.map(|r| r.viewport(set.shift, size));
|
||||
for ((mips, old), new) in set.mips_dirty.iter_mut().zip(&set.tex).zip(&textures).take(DisplayKind::ALL.len()) {
|
||||
if let Some(region) = region
|
||||
&& old.texture == new.texture
|
||||
{
|
||||
if new.mips > 1 {
|
||||
mips.add(region.min[0], region.min[1], region.max[0], region.max[1]);
|
||||
}
|
||||
} else {
|
||||
*mips = MipsDirty::All;
|
||||
}
|
||||
}
|
||||
set.tex = textures;
|
||||
set.pending.iter_mut().take(DisplayKind::ALL.len()).for_each(|slot| *slot = None);
|
||||
set.mips_dirty.iter_mut().take(DisplayKind::ALL.len()).for_each(|mips| *mips = MipsDirty::All);
|
||||
set.bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &set.tex);
|
||||
self.content_rev += 1;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ struct Params {
|
||||
// Source width, source height, display sampling step, height map enabled.
|
||||
source: vec4<u32>,
|
||||
program: vec4<u32>,
|
||||
coverage: vec4<u32>,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var<uniform> params: Params;
|
||||
@@ -22,6 +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>;
|
||||
|
||||
fn pcg3d(cell: vec3<u32>) -> vec3<u32> {
|
||||
var v = cell * 1664525u + 1013904223u;
|
||||
@@ -389,12 +391,23 @@ fn compose(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
if id.x >= params.band.x || id.y >= params.band.y {
|
||||
return;
|
||||
}
|
||||
let pixel = vec2(id.x, id.y + params.band.z) * params.source.z;
|
||||
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);
|
||||
}
|
||||
}
|
||||
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);
|
||||
var scalars = array<f32, 6>(1.0, 1.0, 0.5, 0.0, 0.5, 0.0);
|
||||
for (var i = 0u; i < params.program.x; i++) {
|
||||
for (var i = 0u; covered && i < params.program.x; i++) {
|
||||
let layer = layers[i];
|
||||
var source: vec3<f32>;
|
||||
let mode = u32(layer.balance.z);
|
||||
|
||||
@@ -95,6 +95,7 @@ fn refresh_draft_preferences(draft: &mut Prefs, previous: &Prefs, current: &Pref
|
||||
language,
|
||||
viewport_texture,
|
||||
gpu_compositing,
|
||||
material_start_preview,
|
||||
brightness,
|
||||
accent,
|
||||
system_title_bar,
|
||||
|
||||
+178
-19
@@ -11,10 +11,11 @@ use texturecraft_engine::Session;
|
||||
use texturecraft_engine::compose::{DisplayKind, ImageRes, display_tile_bytes, kinds_for};
|
||||
use texturecraft_engine::core::{BakedMap, Channel};
|
||||
use texturecraft_engine::geom::{Mesh, glam::Vec2};
|
||||
use texturecraft_render::gpu_composite::CompositeProgram;
|
||||
use texturecraft_render::gpu_composite::{CompositeProgram, CompositeRegion};
|
||||
use texturecraft_render::{BakeVisualization, CageGeometry, Frame, Renderer, wgpu};
|
||||
|
||||
use crate::bake_scene::{BakeSceneLink, CageUpload};
|
||||
use crate::i18n::n_;
|
||||
|
||||
/// Content shown through the aux texture.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -54,6 +55,7 @@ pub struct SceneSync {
|
||||
/// Reduction applied when preparing each display tile.
|
||||
pub tile_shift: u32,
|
||||
pub overview: Option<(usize, texturecraft_engine::MaterialOverview)>,
|
||||
cleared_overviews: Vec<usize>,
|
||||
composite: Option<(CompositeProgram, Arc<AtomicBool>)>,
|
||||
pub tiles: Vec<(usize, DisplayKind, u32, u32, Vec<u8>)>,
|
||||
pub aux: Vec<(usize, u32, Vec<u8>)>,
|
||||
@@ -78,6 +80,10 @@ impl SceneSync {
|
||||
renderer.set_display_shift(*shift);
|
||||
reset = renderer.set_texture_sets(device, queue, sets, *material_count);
|
||||
}
|
||||
for &ts in &self.cleared_overviews {
|
||||
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)
|
||||
{
|
||||
@@ -146,9 +152,13 @@ pub struct GpuLink {
|
||||
/// Next set to serve when the last frame exhausted the shared upload budget.
|
||||
upload_cursor: Option<usize>,
|
||||
pending_overviews: BTreeSet<usize>,
|
||||
active_overviews: BTreeSet<usize>,
|
||||
gpu_composite_enabled: bool,
|
||||
pub(crate) prefer_gpu_layers: bool,
|
||||
pub(crate) material_start_preview: bool,
|
||||
cpu_reason: &'static str,
|
||||
gpu_composite_current: Option<CompositeKey>,
|
||||
gpu_display_stroke: Option<u64>,
|
||||
gpu_composite_rejected: Option<CompositeKey>,
|
||||
gpu_composite_failed: Arc<AtomicBool>,
|
||||
bake_scene: BakeSceneLink,
|
||||
@@ -205,12 +215,16 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink {
|
||||
composite_total: 0,
|
||||
upload_cursor: None,
|
||||
pending_overviews: BTreeSet::new(),
|
||||
active_overviews: BTreeSet::new(),
|
||||
gpu_composite_enabled: !cfg!(target_arch = "wasm32")
|
||||
&& info.device_type != wgpu::DeviceType::Cpu
|
||||
&& info.backend != wgpu::Backend::Gl
|
||||
&& std::env::var("TEXTURECRAFT_GPU_COMPOSITE").as_deref() != Ok("0"),
|
||||
prefer_gpu_layers: true,
|
||||
material_start_preview: true,
|
||||
cpu_reason: n_("Waiting for the first material update"),
|
||||
gpu_composite_current: None,
|
||||
gpu_display_stroke: None,
|
||||
gpu_composite_rejected: None,
|
||||
gpu_composite_failed: Arc::default(),
|
||||
bake_scene: BakeSceneLink::default(),
|
||||
@@ -239,37 +253,93 @@ impl GpuLink {
|
||||
s.pending_tiles() > 0 || s.caches.iter().any(|cache| !cache.upload.is_empty())
|
||||
}
|
||||
|
||||
fn plan_gpu_composite(&mut self, session: &Session, shift: u32, interactive: bool, out: &mut SceneSync) -> bool {
|
||||
if !self.gpu_composite_enabled
|
||||
|| !self.prefer_gpu_layers
|
||||
|| interactive
|
||||
|| session.solo.is_some()
|
||||
|| session.caches.len() != 1
|
||||
|| session.doc.baked.get(&0).is_some_and(|maps| !maps.maps.is_empty())
|
||||
|| self.gpu_composite_failed.load(Ordering::Acquire)
|
||||
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."));
|
||||
}
|
||||
if self.gpu_composite_current.is_some() {
|
||||
(n_("Layers: GPU"), n_("The graphics card composes this material."))
|
||||
} else {
|
||||
(n_("Layers: CPU"), self.cpu_reason)
|
||||
}
|
||||
}
|
||||
|
||||
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.")
|
||||
} else if !self.gpu_composite_enabled {
|
||||
n_("GPU compositing is unavailable on this device.")
|
||||
} else if interactive || session.solo.is_some() {
|
||||
n_("The active view uses CPU compositing.")
|
||||
} else if session.stroke_active() && session.pending_display_stroke(0).is_none() {
|
||||
n_("This painting tool uses CPU compositing.")
|
||||
} else if session.caches.len() != 1 {
|
||||
n_("GPU compositing currently supports a single texture set.")
|
||||
} else if session.doc.baked.get(&0).is_some_and(|maps| maps.maps.contains_key(&BakedMap::AmbientOcclusion) || maps.maps.contains_key(&BakedMap::Normal))
|
||||
{
|
||||
n_("This material uses baked normal or ambient occlusion maps.")
|
||||
} else {
|
||||
""
|
||||
};
|
||||
if !self.cpu_reason.is_empty() || self.gpu_composite_failed.load(Ordering::Acquire) {
|
||||
return false;
|
||||
}
|
||||
let Some(cache) = session.caches.first() else { return false };
|
||||
if !cache.dilation.fully_covered() {
|
||||
let padding = cache.dilation.existing_sources();
|
||||
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 };
|
||||
if self.gpu_composite_current == Some(key) {
|
||||
let stroke = session.pending_display_stroke(0);
|
||||
let stroke_id = stroke.map(|(id, _)| id);
|
||||
let current = self.gpu_composite_current == Some(key);
|
||||
let unchanged_stroke = self.gpu_display_stroke == stroke_id;
|
||||
if current && unchanged_stroke && stroke.is_none_or(|(_, tiles)| tiles.is_empty()) {
|
||||
return true;
|
||||
}
|
||||
if self.gpu_composite_rejected == Some(key) {
|
||||
if stroke.is_none() && self.gpu_composite_rejected == Some(key) {
|
||||
return false;
|
||||
}
|
||||
if let Some(program) = CompositeProgram::compile(&session.doc.project, &session.doc.pixels, 0) {
|
||||
let changed_tiles = if current
|
||||
&& (unchanged_stroke || self.gpu_display_stroke.is_none())
|
||||
&& let Some((_, tiles)) = stroke
|
||||
{
|
||||
Some(tiles)
|
||||
} else if stroke.is_none()
|
||||
&& let Some(previous_id) = self.gpu_display_stroke
|
||||
&& let Some(previous) = self.gpu_composite_current.filter(|old| old.mesh == key.mesh && old.size == key.size && old.shift == key.shift)
|
||||
{
|
||||
session.finished_display_stroke(0, previous_id, previous.revision)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let region = changed_tiles
|
||||
.and_then(|tiles| CompositeRegion::from_tiles(tiles.iter().copied()))
|
||||
.map(|r| if padding.is_some() { r.expanded(texturecraft_engine::texel::TILE) } else { r });
|
||||
if changed_tiles.is_some() && region.is_none() {
|
||||
self.gpu_composite_current = Some(key);
|
||||
self.gpu_display_stroke = stroke_id;
|
||||
return true;
|
||||
}
|
||||
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 {
|
||||
self.gpu_composite_rejected = Some(key);
|
||||
if stroke_id.is_none() {
|
||||
self.gpu_composite_rejected = Some(key);
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -320,6 +390,8 @@ impl GpuLink {
|
||||
let resend = self.reset.swap(false, Ordering::AcqRel);
|
||||
if resend || sets != self.sets || shift != self.shift || out.mesh.is_some() {
|
||||
self.gpu_composite_current = None;
|
||||
self.gpu_display_stroke = None;
|
||||
self.gpu_composite_failed = Arc::default();
|
||||
self.pending_overviews.retain(|&ts| ts < sets.len());
|
||||
for (ts, layout) in sets.iter().enumerate() {
|
||||
if resend || out.mesh.is_some() || self.shift != shift || self.sets.get(ts) != Some(layout) {
|
||||
@@ -328,7 +400,7 @@ impl GpuLink {
|
||||
// upload queue after composition; sending them now sends blank pixels.
|
||||
cache.queue_ready_uploads();
|
||||
self.pending_overviews.remove(&ts);
|
||||
if cache.dirty.len() >= UPLOAD_CHUNK {
|
||||
if self.material_start_preview && cache.dirty.len() >= UPLOAD_CHUNK {
|
||||
self.pending_overviews.insert(ts);
|
||||
}
|
||||
}
|
||||
@@ -357,10 +429,21 @@ impl GpuLink {
|
||||
}
|
||||
}
|
||||
|
||||
let interactive = session.stroke_active() || demand.has_brush() || aux_map.is_some() || bake.is_some();
|
||||
if !self.material_start_preview {
|
||||
self.pending_overviews.clear();
|
||||
for ts in std::mem::take(&mut self.active_overviews) {
|
||||
if let Some(cache) = session.caches.get_mut(ts) {
|
||||
out.cleared_overviews.push(ts);
|
||||
cache.queue_ready_uploads();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let interactive = aux_map.is_some() || bake.is_some();
|
||||
if self.plan_gpu_composite(session, shift, interactive, &mut out) {
|
||||
return out;
|
||||
}
|
||||
self.gpu_display_stroke = None;
|
||||
if self.gpu_composite_current.take().is_some()
|
||||
&& let Some(cache) = session.caches.first_mut()
|
||||
{
|
||||
@@ -377,6 +460,7 @@ impl GpuLink {
|
||||
&& let Some(overview) = session.material_overview(ts, 128)
|
||||
{
|
||||
self.sent.entry(ts).or_default().extend(overview.maps.iter().map(|(kind, _)| *kind));
|
||||
self.active_overviews.insert(ts);
|
||||
out.overview = Some((ts, overview));
|
||||
}
|
||||
if out.overview.is_none() || demand.has_brush() {
|
||||
@@ -423,6 +507,8 @@ 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.aux_image.as_ref().is_some_and(|image| image.strong_count() == 0) {
|
||||
self.aux_image = None;
|
||||
self.aux.retain(|_, (view, _)| view != "image");
|
||||
@@ -694,9 +780,13 @@ pub(crate) mod tests {
|
||||
composite_total: 0,
|
||||
upload_cursor: None,
|
||||
pending_overviews: BTreeSet::new(),
|
||||
active_overviews: BTreeSet::new(),
|
||||
gpu_composite_enabled: false,
|
||||
prefer_gpu_layers: true,
|
||||
material_start_preview: true,
|
||||
cpu_reason: n_("Waiting for the first material update"),
|
||||
gpu_composite_current: None,
|
||||
gpu_display_stroke: None,
|
||||
gpu_composite_rejected: None,
|
||||
gpu_composite_failed: Arc::default(),
|
||||
bake_scene: BakeSceneLink::default(),
|
||||
@@ -931,6 +1021,27 @@ pub(crate) mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabling_the_material_overview_keeps_ordinary_tile_uploads() {
|
||||
let mut session = Session::new_project("preview switch", primitives::plane(1.0, 1), "builtin:plane", None, 1024).unwrap();
|
||||
let mut link = link();
|
||||
link.material_start_preview = false;
|
||||
let update = link.sync(&mut session, None, None, 0, FRAME_BUDGET_MS);
|
||||
assert!(update.overview.is_none());
|
||||
assert!(!update.tiles.is_empty());
|
||||
assert!(session.pending_tiles() > 0);
|
||||
|
||||
link.material_start_preview = true;
|
||||
execute(&mut session, "textureSet.resolution", &json!({"resolution":2048})).unwrap();
|
||||
let update = link.sync(&mut session, None, None, 0, FRAME_BUDGET_MS);
|
||||
assert!(update.overview.is_some());
|
||||
link.material_start_preview = false;
|
||||
let update = link.sync(&mut session, None, None, 0, FRAME_BUDGET_MS);
|
||||
assert_eq!(update.cleared_overviews, [0]);
|
||||
assert!(update.overview.is_none());
|
||||
assert!(!update.tiles.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn opening_and_resizing_show_the_whole_material_before_detail_arrives() {
|
||||
@@ -1006,6 +1117,39 @@ pub(crate) mod tests {
|
||||
session
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn gpu_layers_cover_uv_islands_and_their_padding() {
|
||||
use texturecraft_render::{headless::Headless, readback::Readback};
|
||||
let Ok(mut headless) = Headless::new() else { return };
|
||||
let mut mesh = primitives::plane(1.0, 1);
|
||||
for uv in &mut mesh.uvs {
|
||||
*uv = *uv * 0.5 + Vec2::splat(0.25);
|
||||
}
|
||||
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();
|
||||
let mut link = link();
|
||||
link.gpu_composite_enabled = true;
|
||||
let scene = link.sync(&mut session, None, None, 0, 0.0);
|
||||
assert!(scene.composite.is_some());
|
||||
scene.apply_display(&mut headless.renderer, &headless.device, &headless.queue);
|
||||
assert!(!link.gpu_composite_failed.load(Ordering::Acquire));
|
||||
assert_eq!(link.compositor_status().0, "Layers: GPU");
|
||||
let (width, _, image) = Readback::blocking(&headless.device, &headless.queue, headless.renderer.display_textures()[0][0]).unwrap();
|
||||
let samples = |x: u32, y: u32| {
|
||||
let i = (y * width + x) as usize * 4;
|
||||
&image[i..i + 4]
|
||||
};
|
||||
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]);
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn gpu_layers_keep_sparse_paint_and_return_to_cpu_when_requested() {
|
||||
@@ -1047,10 +1191,25 @@ pub(crate) mod tests {
|
||||
assert!(!image[pixel + 4..pixel + 8].starts_with(&[255, 0, 0]), "a one-texel stroke does not spill into the next texel");
|
||||
assert_eq!(textures[0][3].width(), 1024, "height has a full-size texture too");
|
||||
|
||||
s.begin_stroke_uv(Vec2::splat(0.95), 1.0).unwrap();
|
||||
let dab = Vec2::splat(0.95);
|
||||
let dab_pixel = ((972 * width + 972) * 4) as usize;
|
||||
let before_dab = image[dab_pixel..dab_pixel + 4].to_vec();
|
||||
s.begin_stroke_uv(dab, 1.0).unwrap();
|
||||
let scene = link.sync(&mut s, None, None, 0, FRAME_BUDGET_MS);
|
||||
assert!(scene.composite.is_none());
|
||||
assert!(scene.tiles.iter().any(|t| (t.2, t.3) == (15, 15)), "live paint reaches the first CPU upload");
|
||||
assert!(scene.composite.is_some());
|
||||
assert!(scene.tiles.is_empty(), "live layer compositing stays on the GPU");
|
||||
scene.apply_display(&mut gpu.renderer, &gpu.device, &gpu.queue);
|
||||
assert!(!link.gpu_composite_failed.load(Ordering::Acquire));
|
||||
let (_, _, live) = Readback::blocking(&gpu.device, &gpu.queue, gpu.renderer.display_textures()[0][0]).unwrap();
|
||||
assert_ne!(&live[dab_pixel..dab_pixel + 4], before_dab);
|
||||
assert_eq!(&live[pixel..pixel + 4], &[255, 0, 0, 255], "the regional dispatch leaves distant texels alone");
|
||||
assert!(link.sync(&mut s, None, None, 0, FRAME_BUDGET_MS).composite.is_none(), "an unchanged stroke does not redispatch");
|
||||
s.cancel_stroke();
|
||||
let restored = link.sync(&mut s, None, None, 0, FRAME_BUDGET_MS);
|
||||
restored.apply_display(&mut gpu.renderer, &gpu.device, &gpu.queue);
|
||||
let (_, _, cancelled) = Readback::blocking(&gpu.device, &gpu.queue, gpu.renderer.display_textures()[0][0]).unwrap();
|
||||
assert_eq!(&cancelled[dab_pixel..dab_pixel + 4], before_dab);
|
||||
s.begin_stroke_uv(dab, 1.0).unwrap();
|
||||
s.end_stroke().unwrap();
|
||||
let mut resumed = false;
|
||||
for _ in 0..8 {
|
||||
|
||||
@@ -368,6 +368,12 @@ fn general(
|
||||
.on_hover_text(tr("GPU uses the CPU on unsupported devices or layer stacks. CPU forces software composition."));
|
||||
});
|
||||
|
||||
row(ui, tr("Low-resolution material preview"), |ui, label| {
|
||||
ui.checkbox(&mut p.material_start_preview, "")
|
||||
.labelled_by(label)
|
||||
.on_hover_text(tr("Show a quick preview when opening or resizing a texture set. Turn off to see the finished tiles as they arrive."));
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(12.0);
|
||||
ui.add_enabled_ui(false, |ui| {
|
||||
|
||||
@@ -153,6 +153,8 @@ pub struct Prefs {
|
||||
pub viewport_texture: u8,
|
||||
/// Prefer GPU layer compositing in the material viewport where available.
|
||||
pub gpu_compositing: bool,
|
||||
/// Show a coarse view of the whole material before its detailed CPU tiles arrive.
|
||||
pub material_start_preview: bool,
|
||||
/// Interface brightness (the views keep their own background).
|
||||
pub brightness: crate::theme::Brightness,
|
||||
/// The colour of what is on, chosen or focused.
|
||||
@@ -202,6 +204,7 @@ impl Default for Prefs {
|
||||
language: "en".into(),
|
||||
viewport_texture: 0,
|
||||
gpu_compositing: true,
|
||||
material_start_preview: true,
|
||||
brightness: crate::theme::Brightness::default(),
|
||||
accent: crate::theme::Accent::default(),
|
||||
system_title_bar: false,
|
||||
|
||||
@@ -551,6 +551,11 @@ pub fn status_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
|
||||
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)]))
|
||||
|
||||
@@ -453,6 +453,7 @@ impl PendingSync {
|
||||
.zip(app.session.caches.get(app.session.ts()))
|
||||
.map(|(size, cache)| visible_uv_bounds(size, cache.size, app.ui.uv_zoom, app.ui.uv_pan, app.ui.uv_rotation));
|
||||
gpu.prefer_gpu_layers = app.ui.prefs.gpu_compositing;
|
||||
gpu.material_start_preview = app.ui.prefs.material_start_preview;
|
||||
let scene = gpu.sync_view(
|
||||
&mut app.session,
|
||||
aux,
|
||||
|
||||
Reference in New Issue
Block a user