mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-30 10:04:10 +01:00
Merge pull request #88 from storytold/m3/gpu-direct-masks
feat(gpu): GPU stage without readback; masks, groups and blend modes on the GPU (M3)
This commit is contained in:
20 files changed
+1769
-339
No files matched your search
+1
-1
@@ -72,7 +72,7 @@ OR Apache-2.0) is noted in the table.
|
||||
| Tile binning with per-row backdrops; per-pixel exact area coverage on the GPU | `crates/gpu/src/binning.rs`, `crates/gpu/src/fine.wgsl` | Raph Levien et al., *Vello* (<https://github.com/linebender/vello>, Apache-2.0 OR MIT) and its design notes; the *sparse strips* rendering work from the same group (2025); the coverage integral is our oracle's (font-rs row above) | Written from the public descriptions; no Vello code or shaders copied (ADR 0019). |
|
||||
| Adaptive Bézier flattening (Wang's formula) | `crates/geom/src/path.rs` | G.-J. Wang (1984); public mathematical result | |
|
||||
| Porter–Duff "source over" compositing, premultiplied alpha | `crates/render/src/lib.rs` | Porter & Duff, *Compositing Digital Images*, SIGGRAPH 1984 | Public; standard in every graphics stack. |
|
||||
| Blend modes (separable modes, premultiplied) | `crates/render/src/lib.rs` | W3C Compositing and Blending Level 1 | W3C Royalty-Free Patent Policy. |
|
||||
| Blend modes (separable modes, premultiplied) | `crates/render/src/lib.rs`, `crates/gpu/src/fine.wgsl` | W3C Compositing and Blending Level 1 | W3C Royalty-Free Patent Policy. |
|
||||
| Adjust Color filter (brightness, contrast, saturation and hue as colour matrices) | `crates/render/src/filters.rs` | Paul Haeberli, *Matrix Operations for Image Processing* (Silicon Graphics, 1993) | Public description; standard matrix operations. |
|
||||
| Blur, drop shadow and glow by repeated box blurs | `crates/render/src/filters.rs` | Standard image processing (repeated box filters approach a Gaussian, central limit theorem) | Public; no specific implementation followed. |
|
||||
| Bevel and Gradient Bevel by offset differences of the blurred opacity; Gradient Glow and Gradient Bevel through a colour ramp | `crates/render/src/filters.rs` | Standard image processing: embossing as the difference of an image offset along the light direction (a directional derivative; e.g. R. C. Gonzalez & R. E. Woods, *Digital Image Processing*); parameters and behaviour from Adobe's public Animate user guide and ActionScript 3.0 reference (`BevelFilter`, `GradientGlowFilter`, `GradientBevelFilter`) | Public descriptions only; no Adobe code or assets (ADR 0025). |
|
||||
|
||||
@@ -2,6 +2,17 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
* **GPU stage, second slice** (ADR 0029; builds with `--features gpu-stage`, Preferences ›
|
||||
Stage › Renderer › GPU (preview)). The graphics card now draws each stage tile straight into
|
||||
the picture the window shows, with no copy back to the CPU: a 4K stage with 1,000 shapes
|
||||
takes about 2 ms, and 10,000 shapes about 10 ms (the CPU needs 16–28 ms). **Mask layers**
|
||||
(nested, several shapes per mask), **symbols that fade as one** and **all 14 blend modes**
|
||||
are drawn on the GPU too, so ordinary documents no longer fall back to the CPU; masked scenes
|
||||
draw up to 7× faster than on the CPU. The picture is the CPU's within one 8-bit step.
|
||||
Filters and bitmaps still draw on the CPU (the status bar says so). When the window runs on
|
||||
OpenGL, the GPU stage uses a device of its own and copies tiles back, as before; Preferences
|
||||
says which.
|
||||
|
||||
* **HTML canvas export** (ADR 0028). File › Export › Export HTML Canvas… writes the movie as
|
||||
one web page that plays in any modern browser: open it from your disk, put it on a server or
|
||||
send it as one file. Everything moves exactly as on the stage, because every frame of every
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
//!
|
||||
//! The CPU oracle draws by default. A [`Rasterizer`] (the GPU stage, ADR 0019) can take over;
|
||||
//! whatever it hands back (content it doesn't draw yet, or a failed device) the oracle draws, so
|
||||
//! the picture is always complete. Keys include which rasterizer drew them.
|
||||
//! the picture is always complete. Keys include which rasterizer drew them. A rasterizer may
|
||||
//! keep its pictures on the GPU ([`Raster::Native`], ADR 0029): the cache then holds them, under
|
||||
//! a budget of their own, and only the shell knows what they are.
|
||||
|
||||
use crate::history::StateId;
|
||||
use anicraft_doc::{ColorEffect, DisplayList, Document, Rgba, evaluate_scene, evaluate_scene_camera};
|
||||
@@ -56,13 +58,17 @@ impl FrameJob {
|
||||
}
|
||||
}
|
||||
|
||||
/// A finished image: premultiplied RGBA8, ready for a texture upload.
|
||||
/// A finished image: premultiplied RGBA8, ready for a texture upload, or (`native`) an image
|
||||
/// already on the GPU.
|
||||
pub struct FrameImage {
|
||||
pub key: u64,
|
||||
pub frame: u32,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Empty when the picture is [`FrameImage::native`].
|
||||
pub rgba_premul: Vec<u8>,
|
||||
/// The rasterizer's own GPU image (ADR 0029), shown as it is; `None` for bytes.
|
||||
pub native: Option<NativeImage>,
|
||||
pub ms: f32,
|
||||
pub stats: RenderStats,
|
||||
pub error: Option<String>,
|
||||
@@ -72,9 +78,21 @@ pub struct FrameImage {
|
||||
pub fallback: Option<String>,
|
||||
}
|
||||
|
||||
/// Draws a display list as premultiplied RGBA8 in place of the CPU oracle, or says why it
|
||||
/// can't (then the oracle draws it).
|
||||
pub type Rasterizer = Arc<dyn Fn(&DisplayList, &View) -> Result<(Vec<u8>, RenderStats), String> + Send + Sync>;
|
||||
/// A picture a rasterizer keeps on the GPU. The engine stays GPU-free: only the shell, which
|
||||
/// set the rasterizer, knows the concrete type (and how to show it).
|
||||
pub type NativeImage = Arc<dyn std::any::Any + Send + Sync>;
|
||||
|
||||
/// What a [`Rasterizer`] drew.
|
||||
pub enum Raster {
|
||||
/// Premultiplied RGBA8 bytes, `width × height × 4` of them.
|
||||
Premul8(Vec<u8>),
|
||||
/// A `width × height` picture on the GPU (no bytes on the CPU).
|
||||
Native { image: NativeImage, width: u32, height: u32 },
|
||||
}
|
||||
|
||||
/// Draws a display list in place of the CPU oracle, or says why it can't (then the oracle
|
||||
/// draws it).
|
||||
pub type Rasterizer = Arc<dyn Fn(&DisplayList, &View) -> Result<(Raster, RenderStats), String> + Send + Sync>;
|
||||
|
||||
/// Identity of an evaluated scene: the display list depends on these and nothing else.
|
||||
pub fn scene_key(state: StateId, frame: u32, onion: bool) -> u64 {
|
||||
@@ -158,11 +176,14 @@ fn render_job_by(job: &FrameJob, dl: &DisplayList, raster: Option<&Rasterizer>)
|
||||
let mut fallback = None;
|
||||
if let Some(r) = raster {
|
||||
// Last-resort guard: a renderer bug must not take the editor down with it.
|
||||
let (w, h) = (job.view.width, job.view.height);
|
||||
let done = |rgba_premul: Vec<u8>, native: Option<NativeImage>, stats: RenderStats| {
|
||||
let ms = t0.elapsed().as_secs_f32() * 1000.0;
|
||||
FrameImage { key: job.key, frame: job.frame, width: w, height: h, rgba_premul, native, ms, stats, error: None, gpu: true, fallback: None }
|
||||
};
|
||||
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| r(dl, &job.view))) {
|
||||
Ok(Ok((rgba, stats))) if rgba.len() == job.view.width as usize * job.view.height as usize * 4 => {
|
||||
let ms = t0.elapsed().as_secs_f32() * 1000.0;
|
||||
return FrameImage { key: job.key, frame: job.frame, width: job.view.width, height: job.view.height, rgba_premul: rgba, ms, stats, error: None, gpu: true, fallback: None };
|
||||
}
|
||||
Ok(Ok((Raster::Premul8(rgba), stats))) if rgba.len() == w as usize * h as usize * 4 => return done(rgba, None, stats),
|
||||
Ok(Ok((Raster::Native { image, width, height }, stats))) if (width, height) == (w, h) => return done(Vec::new(), Some(image), stats),
|
||||
Ok(Ok(_)) => fallback = Some("the GPU returned a wrong-sized image".to_string()),
|
||||
Ok(Err(why)) => fallback = Some(why),
|
||||
Err(_) => fallback = Some("the GPU renderer failed".to_string()),
|
||||
@@ -175,7 +196,7 @@ fn render_job_by(job: &FrameJob, dl: &DisplayList, raster: Option<&Rasterizer>)
|
||||
Err(_) => (Vec::new(), RenderStats::default(), Some("the renderer failed on this frame".into())),
|
||||
};
|
||||
let (width, height) = if error.is_none() { (job.view.width, job.view.height) } else { (0, 0) };
|
||||
FrameImage { key: job.key, frame: job.frame, width, height, rgba_premul: rgba, ms: t0.elapsed().as_secs_f32() * 1000.0, stats, error, gpu: false, fallback }
|
||||
FrameImage { key: job.key, frame: job.frame, width, height, rgba_premul: rgba, native: None, ms: t0.elapsed().as_secs_f32() * 1000.0, stats, error, gpu: false, fallback }
|
||||
}
|
||||
|
||||
/// Renders a job synchronously, evaluating its scene.
|
||||
@@ -213,19 +234,28 @@ struct RasterSlot {
|
||||
raster: Option<Rasterizer>,
|
||||
}
|
||||
|
||||
/// LRU cache of finished images, bounded by bytes.
|
||||
/// LRU cache of finished images, bounded by bytes: those in memory, and (apart) those a
|
||||
/// rasterizer keeps on the GPU, counted at 4 bytes a pixel.
|
||||
pub struct FrameCache {
|
||||
map: HashMap<u64, (Arc<FrameImage>, u64)>,
|
||||
tick: u64,
|
||||
bytes: usize,
|
||||
native_bytes: usize,
|
||||
pub budget_bytes: usize,
|
||||
pub native_budget_bytes: usize,
|
||||
pub hits: u64,
|
||||
pub misses: u64,
|
||||
}
|
||||
|
||||
/// `(bytes in memory, bytes on the GPU)` an image holds.
|
||||
fn cost(img: &FrameImage) -> (usize, usize) {
|
||||
let gpu = if img.native.is_some() { img.width as usize * img.height as usize * 4 } else { 0 };
|
||||
(img.rgba_premul.len() + std::mem::size_of::<FrameImage>(), gpu)
|
||||
}
|
||||
|
||||
impl FrameCache {
|
||||
pub fn new(budget_bytes: usize) -> Self {
|
||||
FrameCache { map: HashMap::new(), tick: 0, bytes: 0, budget_bytes, hits: 0, misses: 0 }
|
||||
FrameCache { map: HashMap::new(), tick: 0, bytes: 0, native_bytes: 0, budget_bytes, native_budget_bytes: DEFAULT_NATIVE_CACHE_BYTES, hits: 0, misses: 0 }
|
||||
}
|
||||
pub fn get(&mut self, key: u64) -> Option<Arc<FrameImage>> {
|
||||
self.tick += 1;
|
||||
@@ -247,18 +277,31 @@ impl FrameCache {
|
||||
}
|
||||
pub fn insert(&mut self, img: Arc<FrameImage>) {
|
||||
self.tick += 1;
|
||||
let size = img.rgba_premul.len() + std::mem::size_of::<FrameImage>();
|
||||
let (cpu, gpu) = cost(&img);
|
||||
if let Some((old, _)) = self.map.insert(img.key, (img, self.tick)) {
|
||||
self.bytes = self.bytes.saturating_sub(old.rgba_premul.len() + std::mem::size_of::<FrameImage>());
|
||||
self.forget(&old);
|
||||
}
|
||||
self.bytes += size;
|
||||
while self.bytes > self.budget_bytes && self.map.len() > 1 {
|
||||
let Some((&victim, _)) = self.map.iter().min_by_key(|(_, (_, t))| *t) else { break };
|
||||
self.bytes += cpu;
|
||||
self.native_bytes += gpu;
|
||||
loop {
|
||||
// Evict the least recently used image of the kind that is over its budget.
|
||||
let over_gpu = self.native_bytes > self.native_budget_bytes;
|
||||
if !(over_gpu || self.bytes > self.budget_bytes) || self.map.len() <= 1 {
|
||||
break;
|
||||
}
|
||||
let victim = self.map.iter().filter(|(_, (i, _))| !over_gpu || i.native.is_some()).min_by_key(|(_, (_, t))| *t).map(|(&k, _)| k);
|
||||
let Some(victim) = victim else { break };
|
||||
if let Some((old, _)) = self.map.remove(&victim) {
|
||||
self.bytes = self.bytes.saturating_sub(old.rgba_premul.len() + std::mem::size_of::<FrameImage>());
|
||||
self.forget(&old);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn forget(&mut self, img: &FrameImage) {
|
||||
let (cpu, gpu) = cost(img);
|
||||
self.bytes = self.bytes.saturating_sub(cpu);
|
||||
self.native_bytes = self.native_bytes.saturating_sub(gpu);
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
@@ -268,6 +311,10 @@ impl FrameCache {
|
||||
pub fn bytes(&self) -> usize {
|
||||
self.bytes
|
||||
}
|
||||
/// Bytes of the images kept on the GPU.
|
||||
pub fn native_bytes(&self) -> usize {
|
||||
self.native_bytes
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -290,6 +337,8 @@ struct Shared {
|
||||
|
||||
/// Default image-cache budget.
|
||||
pub const DEFAULT_CACHE_BYTES: usize = 768 * 1024 * 1024;
|
||||
/// Default budget for pictures a rasterizer keeps on the GPU (graphics memory is scarcer).
|
||||
pub const DEFAULT_NATIVE_CACHE_BYTES: usize = 384 * 1024 * 1024;
|
||||
/// Most jobs the worker renders in one parallel pass.
|
||||
const BATCH: usize = 32;
|
||||
|
||||
@@ -430,7 +479,7 @@ impl RenderService {
|
||||
let key = job.key;
|
||||
let frame = job.frame;
|
||||
self.render_now_batch(vec![job]).into_iter().next().unwrap_or_else(|| {
|
||||
Arc::new(FrameImage { key, frame, width: 0, height: 0, rgba_premul: Vec::new(), ms: 0.0, stats: RenderStats::default(), error: Some("render failed".into()), gpu: false, fallback: None })
|
||||
Arc::new(FrameImage { key, frame, width: 0, height: 0, rgba_premul: Vec::new(), native: None, ms: 0.0, stats: RenderStats::default(), error: Some("render failed".into()), gpu: false, fallback: None })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -657,7 +706,7 @@ mod tests {
|
||||
if dl.items.len() > plain {
|
||||
return Err("too much".into());
|
||||
}
|
||||
Ok(([10u8, 20, 30, 255].repeat(v.width as usize * v.height as usize), RenderStats::default()))
|
||||
Ok((Raster::Premul8([10u8, 20, 30, 255].repeat(v.width as usize * v.height as usize)), RenderStats::default()))
|
||||
});
|
||||
svc.set_rasterizer(Some(flat));
|
||||
assert!(svc.has_rasterizer());
|
||||
@@ -684,12 +733,55 @@ mod tests {
|
||||
fn cache_respects_budget_lru() {
|
||||
let mut c = FrameCache::new(3 * 1000);
|
||||
for k in 0..10u64 {
|
||||
c.insert(Arc::new(FrameImage { key: k, frame: 0, width: 0, height: 0, rgba_premul: vec![0; 800], ms: 0.0, stats: RenderStats::default(), error: None, gpu: false, fallback: None }));
|
||||
c.insert(Arc::new(FrameImage { key: k, frame: 0, width: 0, height: 0, rgba_premul: vec![0; 800], native: None, ms: 0.0, stats: RenderStats::default(), error: None, gpu: false, fallback: None }));
|
||||
}
|
||||
assert!(c.bytes() <= 3000);
|
||||
assert!(c.contains(9) && !c.contains(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_pictures_have_a_budget_of_their_own() {
|
||||
// 10 × 10 pictures on the GPU (400 bytes each) under a 1,000-byte GPU budget: the
|
||||
// oldest GPU pictures go, the ones in memory stay.
|
||||
let mut c = FrameCache::new(1 << 20);
|
||||
c.native_budget_bytes = 1000;
|
||||
let img = |k: u64, native: bool| {
|
||||
let n: Option<NativeImage> = native.then(|| Arc::new(k) as NativeImage);
|
||||
Arc::new(FrameImage { key: k, frame: 0, width: 10, height: 10, rgba_premul: if native { Vec::new() } else { vec![0; 400] }, native: n, ms: 0.0, stats: RenderStats::default(), error: None, gpu: native, fallback: None })
|
||||
};
|
||||
c.insert(img(100, false));
|
||||
for k in 0..5 {
|
||||
c.insert(img(k, true));
|
||||
}
|
||||
assert!(c.native_bytes() <= 1000 && c.contains(4) && c.contains(3) && !c.contains(0));
|
||||
assert!(c.contains(100), "pictures in memory are not evicted for GPU memory");
|
||||
// Replacing a picture does not count it twice.
|
||||
c.insert(img(4, true));
|
||||
assert_eq!(c.native_bytes(), 800);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rasterizer_may_keep_its_pictures_on_the_gpu() {
|
||||
let doc = sample::demo();
|
||||
let svc = RenderService::new(64 << 20, None);
|
||||
let view = View { transform: Affine::scale(0.25, 0.25), width: 320, height: 180, background: Some(doc.stage.background) };
|
||||
// A stand-in that keeps its picture as a number, and gets the size wrong once.
|
||||
let wrong = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let w2 = wrong.clone();
|
||||
let native: Rasterizer = Arc::new(move |_: &DisplayList, v: &View| {
|
||||
let bad = w2.load(std::sync::atomic::Ordering::Relaxed);
|
||||
Ok((Raster::Native { image: Arc::new(7u32), width: v.width + u32::from(bad), height: v.height }, RenderStats::default()))
|
||||
});
|
||||
svc.set_rasterizer(Some(native));
|
||||
let img = svc.render_now(svc.job(1, &doc, 3, view, false));
|
||||
assert!(img.gpu && img.rgba_premul.is_empty());
|
||||
assert_eq!(img.native.as_ref().and_then(|n| n.downcast_ref::<u32>()), Some(&7));
|
||||
wrong.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
let img = svc.render_now(svc.job(1, &doc, 4, view, false));
|
||||
assert!(!img.gpu && img.native.is_none() && img.fallback.as_deref() == Some("the GPU returned a wrong-sized image"));
|
||||
assert_eq!(img.rgba_premul.len(), 320 * 180 * 4, "the oracle drew it instead");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_distinguish_state_frame_and_view() {
|
||||
let doc = sample::demo();
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
//! GPU stage timings and parity against the CPU oracle (ADR 0019; numbers in
|
||||
//! GPU stage timings and parity against the CPU oracle (ADR 0019, ADR 0029; numbers in
|
||||
//! docs/performance.md).
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run --release -p anicraft-gpu --example gpu_bench
|
||||
//! cargo run --release -p anicraft-gpu --example gpu_bench -- --layers 50 --shapes 200
|
||||
//! ```
|
||||
//! Prints the adapter, then for each scene and size: CPU ms, GPU ms (prepare + bin + GPU),
|
||||
//! the work the fine pass did, and how far the two pictures are apart.
|
||||
//! Prints the adapter, then for each scene and size: CPU ms; the first slice's read-back path
|
||||
//! (prepare + bin + upload, compute, copy back); the direct path the window uses (into a
|
||||
//! texture, no readback): what the calling thread spends, and until the GPU has finished; the
|
||||
//! stage's way (512 px tiles drawn in parallel, as the render service does, until finished);
|
||||
//! the work the fine pass did; and how far the GPU's picture is from the oracle's.
|
||||
|
||||
use anicraft_doc::{Document, evaluate, sample};
|
||||
use anicraft_doc::{Document, LayerKind, evaluate, sample};
|
||||
use anicraft_gpu::{GpuRenderer, Output, compare_premul8};
|
||||
use anicraft_geom::Affine;
|
||||
use anicraft_render::{View, render};
|
||||
use rayon::prelude::*;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
fn arg(name: &str, default: u32) -> u32 {
|
||||
@@ -18,6 +24,45 @@ fn arg(name: &str, default: u32) -> u32 {
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).and_then(|v| v.parse().ok()).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// The stress document with every other layer a mask over the layer below it (half the shapes
|
||||
/// are mask artwork, half are drawn inside a mask), and every shape at 80 % in a group.
|
||||
fn masked(mut doc: Document) -> Document {
|
||||
let tl = doc.timeline_mut(0);
|
||||
let ids: Vec<_> = tl.layers.iter().map(|l| l.id).collect();
|
||||
for (i, layer) in tl.layers.iter_mut().enumerate() {
|
||||
let l = Arc::make_mut(layer);
|
||||
if i % 2 == 0 {
|
||||
l.kind = LayerKind::Mask;
|
||||
} else {
|
||||
l.parent = ids.get(i - 1).copied();
|
||||
}
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
/// The demo with the ball and star symbols faded (groups) and the hills a mask over the sky.
|
||||
fn composited() -> Document {
|
||||
let mut doc = sample::demo();
|
||||
let tl = doc.timeline_mut(0);
|
||||
let hills = tl.layers.get(3).map(|l| l.id);
|
||||
for (i, layer) in tl.layers.iter_mut().enumerate() {
|
||||
let l = Arc::make_mut(layer);
|
||||
match i {
|
||||
0 | 1 => {
|
||||
for k in &mut l.keyframes {
|
||||
for e in &mut Arc::make_mut(k).elements {
|
||||
Arc::make_mut(e).color.alpha = 0.6;
|
||||
}
|
||||
}
|
||||
}
|
||||
3 => l.kind = LayerKind::Mask,
|
||||
4 => l.parent = hills,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let gpu = match GpuRenderer::new() {
|
||||
Ok(g) => g,
|
||||
@@ -32,9 +77,14 @@ fn main() {
|
||||
let scenes: Vec<(String, Document)> = vec![
|
||||
(format!("stress {layers}×{shapes}"), sample::stress(layers, shapes, 240)),
|
||||
("1,000 shapes".into(), sample::stress(5, 200, 240)),
|
||||
(format!("masked {layers}×{shapes}"), masked(sample::stress(layers, shapes, 240))),
|
||||
("sample".into(), sample::demo()),
|
||||
("composited sample".into(), composited()),
|
||||
];
|
||||
println!("{:<18} {:>10} {:>9} {:>9} {:>30} {:>9} {:>9} parity (mean / max / differing px)", "scene", "size", "CPU ms", "GPU ms", "prepare + bin + gpu", "entries", "pieces");
|
||||
println!(
|
||||
"{:<20} {:>10} {:>8} {:>9} {:>9} {:>9} {:>7} {:>22} {:>8} {:>8} parity (mean / max / differing px)",
|
||||
"scene", "size", "CPU ms", "readback", "direct", "direct+", "tiled", "prepare + bin + submit", "entries", "pieces"
|
||||
);
|
||||
for (name, doc) in &scenes {
|
||||
for scale in [1.0f32, 2.0] {
|
||||
let v = View::stage(doc, scale * 1920.0 / doc.stage.width as f32);
|
||||
@@ -42,37 +92,71 @@ fn main() {
|
||||
let dl0 = evaluate(doc, 0);
|
||||
// Warm-up (pipeline caches, allocations).
|
||||
let _ = gpu.render(&dl0, &v, Output::Premul8);
|
||||
let _ = gpu.render_texture(&dl0, &v);
|
||||
let _ = gpu.wait_idle();
|
||||
let _ = render(&dl0, &v);
|
||||
let lists: Vec<_> = (0..runs).map(|i| evaluate(doc, (i * 20) % frames)).collect();
|
||||
let per = |t: Instant| t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
|
||||
let t = Instant::now();
|
||||
for dl in &lists {
|
||||
let _ = render(dl, &v);
|
||||
}
|
||||
let cpu_ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
|
||||
let cpu_ms = per(t);
|
||||
let t = Instant::now();
|
||||
for dl in &lists {
|
||||
let _ = gpu.render(dl, &v, Output::Premul8);
|
||||
}
|
||||
let readback_ms = per(t);
|
||||
// Direct: what the calling thread spends (the stage's cost per tile), then each frame
|
||||
// waited for to the end (the latency until the window can show it).
|
||||
let mut sum = [0.0f32; 3];
|
||||
let mut work = (0, 0);
|
||||
let t = Instant::now();
|
||||
let mut keep = Vec::with_capacity(lists.len());
|
||||
for dl in &lists {
|
||||
if let Ok(f) = gpu.render(dl, &v, Output::Premul8) {
|
||||
if let Ok(f) = gpu.render_texture(dl, &v) {
|
||||
sum[0] += f.timings.prepare;
|
||||
sum[1] += f.timings.bin;
|
||||
sum[2] += f.timings.gpu;
|
||||
work = (f.entries, f.pieces);
|
||||
keep.push(f);
|
||||
}
|
||||
}
|
||||
let gpu_ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
|
||||
let direct_ms = per(t);
|
||||
let _ = gpu.wait_idle();
|
||||
drop(keep);
|
||||
let t = Instant::now();
|
||||
for dl in &lists {
|
||||
let _ = gpu.render_texture(dl, &v);
|
||||
let _ = gpu.wait_idle();
|
||||
}
|
||||
let done_ms = per(t);
|
||||
// The stage: 512 px tiles of the same frame, in parallel, then waited for.
|
||||
let tiles: Vec<View> = (0..v.height.div_ceil(512))
|
||||
.flat_map(|ty| (0..v.width.div_ceil(512)).map(move |tx| (tx, ty)))
|
||||
.map(|(tx, ty)| View { transform: Affine::translate(-((tx * 512) as f32), -((ty * 512) as f32)).mul(&v.transform), width: 512.min(v.width - tx * 512), height: 512.min(v.height - ty * 512), background: v.background })
|
||||
.collect();
|
||||
let t = Instant::now();
|
||||
for dl in &lists {
|
||||
let _: Vec<_> = tiles.par_iter().map(|tv| gpu.render_texture(dl, tv).ok()).collect();
|
||||
let _ = gpu.wait_idle();
|
||||
}
|
||||
let tiled_ms = per(t);
|
||||
let n = runs as f32;
|
||||
let parity = match (gpu.render(&dl0, &v, Output::Premul8), render(&dl0, &v)) {
|
||||
(Ok(g), Ok((c, _))) => compare_premul8(&g.premul8, &c.to_premul_rgba8()).map_or("size mismatch".into(), |d| format!("{:.4} / {} / {}", d.mean, d.max, d.differing)),
|
||||
let parity = match (gpu.render_texture(&dl0, &v).and_then(|t| gpu.read_texture(&t)), render(&dl0, &v)) {
|
||||
(Ok(g), Ok((c, _))) => compare_premul8(&g, &c.to_premul_rgba8()).map_or("size mismatch".into(), |d| format!("{:.4} / {} / {}", d.mean, d.max, d.differing)),
|
||||
(Err(e), _) => format!("GPU: {e}"),
|
||||
(_, Err(e)) => format!("CPU: {e}"),
|
||||
};
|
||||
println!(
|
||||
"{:<18} {:>10} {:>9.2} {:>9.2} {:>30} {:>9} {:>9} {parity}",
|
||||
"{:<20} {:>10} {:>8.2} {:>9.2} {:>9.2} {:>9.2} {:>7.2} {:>22} {:>8} {:>8} {parity}",
|
||||
name,
|
||||
format!("{}×{}", v.width, v.height),
|
||||
cpu_ms,
|
||||
gpu_ms,
|
||||
readback_ms,
|
||||
direct_ms,
|
||||
done_ms,
|
||||
tiled_ms,
|
||||
format!("{:.2} + {:.2} + {:.2}", sum[0] / n, sum[1] / n, sum[2] / n),
|
||||
work.0,
|
||||
work.1
|
||||
|
||||
+255
-54
@@ -1,4 +1,4 @@
|
||||
//! Tile binning: the CPU half of the GPU stage (ADR 0019).
|
||||
//! Tile binning: the CPU half of the GPU stage (ADR 0019, ADR 0029).
|
||||
//!
|
||||
//! The surface is cut into 16 × 16 pixel tiles. Every fill's edges are split at tile rows and
|
||||
//! columns; each piece lands in the one tile it crosses. What a piece contributes to the tiles
|
||||
@@ -10,11 +10,17 @@
|
||||
//! with neither (outside the fill) get no entry; interior tiles get a backdrop and no pieces.
|
||||
//!
|
||||
//! Each tile then lists its entries in drawing order, so the shader composites every pixel in
|
||||
//! one pass, front to back in the display list's order.
|
||||
//! one pass, front to back in the display list's order. Masks and groups (ADR 0029) are more
|
||||
//! entries in the same list: before a clipped fill, the clip's coverage is computed from its
|
||||
//! artwork's entries in this tile (one level per clip in its chain, the levels multiplied); and
|
||||
//! a group opens before its first fill in the tile and closes (blending into what is below at
|
||||
//! its alpha and in its blend mode) when its run ends, as the oracle's band compositor does per
|
||||
//! band.
|
||||
|
||||
use anicraft_doc::BlendMode;
|
||||
use anicraft_geom::{FillRule, Vec2};
|
||||
use anicraft_render::Fill;
|
||||
use anicraft_render::paint::Shader;
|
||||
use anicraft_render::{Fill, NeedsFull, Scene};
|
||||
use rayon::prelude::*;
|
||||
|
||||
/// A `vec4<f32>` as the shader sees it.
|
||||
@@ -23,27 +29,72 @@ type Vec4 = [f32; 4];
|
||||
/// Tile side in pixels (the shader's workgroup is one tile, one invocation per pixel).
|
||||
pub const TILE: u32 = 16;
|
||||
const T: f32 = TILE as f32;
|
||||
/// "No backdrop" in an entry.
|
||||
/// "No backdrop" in an entry; "no clip" or "no group" in the tables.
|
||||
pub const NONE: u32 = u32::MAX;
|
||||
/// `vec4`s of paint data per fill.
|
||||
pub const PAINT_VEC4S: usize = 4;
|
||||
/// Gradient table entries (the oracle's LUT size).
|
||||
pub const RAMP: usize = 256;
|
||||
/// Deepest nesting of groups the shader's per-pixel stack holds (`fine.wgsl`).
|
||||
pub const MAX_GROUP_DEPTH: usize = 8;
|
||||
/// Longest chain of nested clips the binning expands (each level is one more pass over its
|
||||
/// artwork per clip switch).
|
||||
pub const MAX_CLIP_DEPTH: usize = 16;
|
||||
|
||||
/// Paint kinds in an op header.
|
||||
const SOLID: u32 = 0;
|
||||
const LINEAR: u32 = 1;
|
||||
const RADIAL: u32 = 2;
|
||||
|
||||
/// Op header flag: the fill is drawn inside the current clip.
|
||||
pub const CLIPPED: u32 = 1;
|
||||
/// Op header flag: the op is clip artwork (its coverage joins the current level's union).
|
||||
pub const ART: u32 = 2;
|
||||
|
||||
/// An entry whose first word has this bit is a control entry, not a fill.
|
||||
pub const CTRL: u32 = 0x8000_0000;
|
||||
/// `[OPEN, group, 0, 0]`: push the colour so far and continue on transparent.
|
||||
pub const OPEN: u32 = CTRL | 1;
|
||||
/// `[CLOSE, alpha bits, blend mode, 0]`: blend the group into the colour below it.
|
||||
pub const CLOSE: u32 = CTRL | 2;
|
||||
/// The clip coverage starts at 1 (a new clip's chain follows).
|
||||
pub const MASK_RESET: u32 = CTRL | 3;
|
||||
/// One level of the clip chain starts: its union of artwork coverage starts at 0.
|
||||
pub const LEVEL_BEGIN: u32 = CTRL | 4;
|
||||
/// The level ends: the clip coverage is multiplied by its union.
|
||||
pub const LEVEL_END: u32 = CTRL | 5;
|
||||
|
||||
/// Blend modes as the shader numbers them (`fine.wgsl` › `blend`).
|
||||
pub fn blend_code(m: BlendMode) -> u32 {
|
||||
match m {
|
||||
BlendMode::Normal | BlendMode::Layer => 0,
|
||||
BlendMode::Multiply => 1,
|
||||
BlendMode::Screen => 2,
|
||||
BlendMode::Darken => 3,
|
||||
BlendMode::Lighten => 4,
|
||||
BlendMode::Difference => 5,
|
||||
BlendMode::Add => 6,
|
||||
BlendMode::Subtract => 7,
|
||||
BlendMode::Invert => 8,
|
||||
BlendMode::HardLight => 9,
|
||||
BlendMode::Overlay => 10,
|
||||
BlendMode::Alpha => 11,
|
||||
BlendMode::Erase => 12,
|
||||
}
|
||||
}
|
||||
|
||||
/// A scene ready for the fine shader.
|
||||
///
|
||||
/// * `index` (u32): `[start, count]` per tile into the entry list; then each entry as
|
||||
/// `[op, first piece, pieces, backdrop]` (the backdrop's first `vec4` in `geo`, or [`NONE`]);
|
||||
/// then each op's header `[kind, fill rule, ramp start in paints, 0]`.
|
||||
/// `[op, first piece, pieces, backdrop]` (the backdrop's first `vec4` in `geo`, or [`NONE`]),
|
||||
/// or a control entry ([`CTRL`] set); then each op's header `[kind, fill rule, ramp start in
|
||||
/// paints, flags]`.
|
||||
/// * `geo` (`vec4<f32>`): pieces `(x0, y0, x1, y1)` relative to their tile's top-left, in the
|
||||
/// edge's direction; then backdrops, four `vec4`s (16 rows) each.
|
||||
/// * `paints` (`vec4<f32>`): per op its colour, then the inverse paint transform and gradient
|
||||
/// parameters; then the gradient tables (256 premultiplied colours each).
|
||||
///
|
||||
/// Ops are the scene's fills in drawing order, then every clip's artwork, clip by clip.
|
||||
pub struct Binned {
|
||||
pub tiles_x: u32,
|
||||
pub tiles_y: u32,
|
||||
@@ -52,8 +103,12 @@ pub struct Binned {
|
||||
pub ops_at: u32,
|
||||
pub geo: Vec<[f32; 4]>,
|
||||
pub paints: Vec<[f32; 4]>,
|
||||
/// Entries (fills, artwork and control) and edge pieces in all tiles.
|
||||
pub entries: usize,
|
||||
pub pieces: usize,
|
||||
/// Pieces plus entries the fine pass walks, summed over tiles (each for 256 pixels): what
|
||||
/// bounds how long the dispatch runs.
|
||||
pub work: u64,
|
||||
}
|
||||
|
||||
/// A chunk of fills' share of the scene (binned in parallel; chunking keeps allocations few).
|
||||
@@ -78,14 +133,63 @@ struct Piece {
|
||||
/// Fills binned per parallel task.
|
||||
const CHUNK: usize = 16;
|
||||
|
||||
/// Bins `fills` for a `width × height` surface.
|
||||
pub fn bin(fills: &[Fill], width: u32, height: u32) -> Binned {
|
||||
/// What the per-tile streams need to know about the ops, clips and groups.
|
||||
struct Tables<'a> {
|
||||
/// Fills come first in the op list; artwork after.
|
||||
fills: u32,
|
||||
/// Per fill: its clip and its group (or [`NONE`]).
|
||||
op_clip: Vec<u32>,
|
||||
op_group: Vec<u32>,
|
||||
/// Per clip: its chain, outermost first, and its artwork's op range.
|
||||
clip_chain: Vec<Vec<u32>>,
|
||||
art_ops: Vec<(u32, u32)>,
|
||||
scene: &'a Scene,
|
||||
}
|
||||
|
||||
/// One tile row's entries, built in parallel and then copied into place.
|
||||
struct RowOut {
|
||||
stream: Vec<[u32; 4]>,
|
||||
/// `[start, count]` per tile, `start` local to the row.
|
||||
heads: Vec<[u32; 2]>,
|
||||
work: u64,
|
||||
}
|
||||
|
||||
/// Bins `scene` for a `width × height` surface. `Err` when its nesting is deeper than the
|
||||
/// shader holds ([`MAX_GROUP_DEPTH`], [`MAX_CLIP_DEPTH`]); the caller draws it on the CPU.
|
||||
pub fn bin(scene: &Scene, width: u32, height: u32) -> Result<Binned, NeedsFull> {
|
||||
if scene.groups.iter().any(|g| g.chain.len() > MAX_GROUP_DEPTH) {
|
||||
return Err(NeedsFull::Groups);
|
||||
}
|
||||
let mut clip_chain: Vec<Vec<u32>> = Vec::with_capacity(scene.clips.len());
|
||||
for (i, c) in scene.clips.iter().enumerate() {
|
||||
let mut chain = c.parent.filter(|&p| (p as usize) < i).and_then(|p| clip_chain.get(p as usize)).cloned().unwrap_or_default();
|
||||
chain.push(i as u32);
|
||||
if chain.len() > MAX_CLIP_DEPTH {
|
||||
return Err(NeedsFull::Clips);
|
||||
}
|
||||
clip_chain.push(chain);
|
||||
}
|
||||
let mut ops: Vec<&Fill> = scene.fills.iter().collect();
|
||||
let mut art_ops = Vec::with_capacity(scene.clips.len());
|
||||
for c in &scene.clips {
|
||||
let a0 = ops.len() as u32;
|
||||
ops.extend(c.art.iter());
|
||||
art_ops.push((a0, ops.len() as u32));
|
||||
}
|
||||
if ops.len() >= CTRL as usize {
|
||||
return Err(NeedsFull::Groups);
|
||||
}
|
||||
let nf = scene.fills.len();
|
||||
let op_clip: Vec<u32> = scene.fills.iter().map(|f| f.clip.filter(|&c| (c as usize) < scene.clips.len()).unwrap_or(NONE)).collect();
|
||||
let op_group: Vec<u32> = scene.fills.iter().map(|f| f.group.filter(|&g| (g as usize) < scene.groups.len()).unwrap_or(NONE)).collect();
|
||||
let tables = Tables { fills: nf as u32, op_clip, op_group, clip_chain, art_ops, scene };
|
||||
|
||||
let tiles_x = width.div_ceil(TILE);
|
||||
let tiles_y = height.div_ceil(TILE);
|
||||
let (tx, ty) = (tiles_x as usize, tiles_y as usize);
|
||||
// Phase 1, parallel over chunks of fills: pieces, backdrops and entries; each chunk's
|
||||
// Phase 1, parallel over chunks of ops: pieces, backdrops and entries; each chunk's
|
||||
// entries then sorted (stably, so drawing order holds) by tile row, with row offsets.
|
||||
let locals: Vec<(Local, Vec<u32>)> = fills
|
||||
let locals: Vec<(Local, Vec<u32>)> = ops
|
||||
.par_chunks(CHUNK)
|
||||
.enumerate()
|
||||
.map(|(c, chunk)| {
|
||||
@@ -108,7 +212,7 @@ pub fn bin(fills: &[Fill], width: u32, height: u32) -> Binned {
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Where each chunk's pieces and backdrops go in `geo`, and each tile row's entries.
|
||||
// Where each chunk's pieces and backdrops go in `geo`.
|
||||
let pieces: usize = locals.iter().map(|(l, _)| l.pieces.len()).sum();
|
||||
let mut piece_at = Vec::with_capacity(locals.len());
|
||||
let mut bd_at = Vec::with_capacity(locals.len());
|
||||
@@ -119,17 +223,19 @@ pub fn bin(fills: &[Fill], width: u32, height: u32) -> Binned {
|
||||
p += l.pieces.len();
|
||||
b += l.backdrops.len();
|
||||
}
|
||||
|
||||
// Phase 2, parallel over tile rows: each tile's stream of entries.
|
||||
let rows: Vec<RowOut> = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, &bd_at, &tables)).collect();
|
||||
let mut row_at = vec![0usize; ty + 1];
|
||||
for r in 0..ty {
|
||||
let n: usize = locals.iter().map(|(_, rows)| (rows[r + 1] - rows[r]) as usize).sum();
|
||||
row_at[r + 1] = row_at[r] + n;
|
||||
for (r, out) in rows.iter().enumerate() {
|
||||
row_at[r + 1] = row_at[r] + out.stream.len();
|
||||
}
|
||||
let total = row_at[ty];
|
||||
let work = rows.iter().map(|r| r.work).sum();
|
||||
let entries_at = 2 * tx * ty;
|
||||
let ops_at = entries_at + 4 * total;
|
||||
let mut index = vec![0u32; ops_at + 4 * fills.len()];
|
||||
|
||||
// Phase 2, parallel over tile rows: each row owns its tiles' headers and its entries.
|
||||
let mut index = vec![0u32; ops_at + 4 * ops.len()];
|
||||
// Phase 3, parallel over tile rows: headers and streams copied into place.
|
||||
{
|
||||
let (headers, rest) = index.split_at_mut(entries_at);
|
||||
let (mut entries, _) = rest.split_at_mut(4 * total);
|
||||
@@ -139,40 +245,15 @@ pub fn bin(fills: &[Fill], width: u32, height: u32) -> Binned {
|
||||
row_entries.push(mine);
|
||||
entries = after;
|
||||
}
|
||||
headers.par_chunks_mut(2 * tx.max(1)).zip(row_entries).enumerate().for_each(|(r, (head, out))| {
|
||||
let first_tile = (r * tx) as u32;
|
||||
let mut count = vec![0u32; tx];
|
||||
let slices = || locals.iter().enumerate().map(|(c, (l, rows))| (c, l.entries.get(rows[r] as usize..rows[r + 1] as usize).unwrap_or(&[])));
|
||||
for (_, es) in slices() {
|
||||
for e in es {
|
||||
if let Some(n) = count.get_mut((e[1] - first_tile) as usize) {
|
||||
*n += 1;
|
||||
}
|
||||
}
|
||||
headers.par_chunks_mut(2 * tx.max(1)).zip(row_entries).zip(&rows).enumerate().for_each(|(r, ((head, out), row))| {
|
||||
for (h, &[s, n]) in head.as_chunks_mut::<2>().0.iter_mut().zip(&row.heads) {
|
||||
*h = [row_at[r] as u32 + s, n];
|
||||
}
|
||||
let mut cursor = vec![0u32; tx];
|
||||
let mut run = 0u32;
|
||||
for (t, &n) in count.iter().enumerate() {
|
||||
if let Some(h) = head.get_mut(2 * t..2 * t + 2) {
|
||||
h.copy_from_slice(&[row_at[r] as u32 + run, n]);
|
||||
}
|
||||
cursor[t] = run;
|
||||
run += n;
|
||||
}
|
||||
for (c, es) in slices() {
|
||||
for &[op, tile, s0, n, bd] in es {
|
||||
let Some(cur) = cursor.get_mut((tile - first_tile) as usize) else { continue };
|
||||
let at = 4 * *cur as usize;
|
||||
*cur += 1;
|
||||
let bd = if bd == NONE { NONE } else { bd_at[c] + bd };
|
||||
if let Some(slot) = out.get_mut(at..at + 4) {
|
||||
slot.copy_from_slice(&[op, piece_at[c] + s0, n, bd]);
|
||||
}
|
||||
}
|
||||
for (d, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(&row.stream) {
|
||||
*d = *s;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Pieces, then backdrops, copied in parallel into their places.
|
||||
let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; b];
|
||||
{
|
||||
@@ -189,13 +270,13 @@ pub fn bin(fills: &[Fill], width: u32, height: u32) -> Binned {
|
||||
jobs.into_par_iter().for_each(|(d, s)| d.copy_from_slice(s));
|
||||
}
|
||||
// Tens of thousands of small buffers: free them on the pool, off the frame's path.
|
||||
rayon::spawn(move || drop(locals));
|
||||
rayon::spawn(move || drop((locals, rows)));
|
||||
|
||||
// Paints: a fixed record per op, then the gradient tables.
|
||||
let mut paints: Vec<[f32; 4]> = Vec::with_capacity(PAINT_VEC4S * fills.len());
|
||||
let mut paints: Vec<[f32; 4]> = Vec::with_capacity(PAINT_VEC4S * ops.len());
|
||||
let mut ramps: Vec<[f32; 4]> = Vec::new();
|
||||
let ramps_at = (PAINT_VEC4S * fills.len()) as u32;
|
||||
for (op, f) in fills.iter().enumerate() {
|
||||
let ramps_at = (PAINT_VEC4S * ops.len()) as u32;
|
||||
for (op, f) in ops.iter().enumerate() {
|
||||
let rule = match f.rule {
|
||||
FillRule::NonZero => 0,
|
||||
FillRule::EvenOdd => 1,
|
||||
@@ -213,18 +294,138 @@ pub fn bin(fills: &[Fill], width: u32, height: u32) -> Binned {
|
||||
let m = inv.m;
|
||||
(RADIAL, [[0.0; 4], [m[0], m[1], m[2], m[3]], [m[4], m[5], center.x, center.y], [0.0, 0.0, *inv_radius, 0.0]])
|
||||
}
|
||||
// `plain_fills` never hands these over; draw nothing rather than guess.
|
||||
// `prepare_scene` never hands these over; draw nothing rather than guess.
|
||||
Shader::Bitmap { .. } | Shader::Image { .. } => (SOLID, [[0.0; 4]; 4]),
|
||||
};
|
||||
paints.extend_from_slice(&rec);
|
||||
let flags = if op >= nf {
|
||||
ART
|
||||
} else if tables.op_clip.get(op).is_some_and(|&c| c != NONE) {
|
||||
CLIPPED
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let at = ops_at + 4 * op;
|
||||
if let Some(slot) = index.get_mut(at..at + 4) {
|
||||
slot.copy_from_slice(&[kind, rule, ramp, 0]);
|
||||
slot.copy_from_slice(&[kind, rule, ramp, flags]);
|
||||
}
|
||||
}
|
||||
paints.extend_from_slice(&ramps);
|
||||
|
||||
Binned { tiles_x, tiles_y, index, entries_at: entries_at as u32, ops_at: ops_at as u32, geo, paints, entries: total, pieces }
|
||||
Ok(Binned { tiles_x, tiles_y, index, entries_at: entries_at as u32, ops_at: ops_at as u32, geo, paints, entries: total, pieces, work })
|
||||
}
|
||||
|
||||
/// Tile row `r`'s streams: per tile, its fills in drawing order with the clip and group
|
||||
/// entries they need.
|
||||
fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec<u32>)], piece_at: &[u32], bd_at: &[u32], t: &Tables) -> RowOut {
|
||||
let first_tile = (r * tx) as u32;
|
||||
let slices = || {
|
||||
locals.iter().enumerate().map(move |(c, (l, rows))| {
|
||||
let (a, b) = (rows.get(r).copied().unwrap_or(0) as usize, rows.get(r + 1).copied().unwrap_or(0) as usize);
|
||||
(c, l.entries.get(a..b).unwrap_or(&[]))
|
||||
})
|
||||
};
|
||||
// Counting sort by tile, fills and artwork apart, keeping drawing order within a tile.
|
||||
let mut count = vec![[0u32; 2]; tx + 1];
|
||||
for (_, es) in slices() {
|
||||
for e in es {
|
||||
if let Some(n) = count.get_mut(e[1].wrapping_sub(first_tile) as usize + 1) {
|
||||
n[usize::from(e[0] >= t.fills)] += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
for i in 1..count.len() {
|
||||
let prev = count[i - 1];
|
||||
count[i][0] += prev[0];
|
||||
count[i][1] += prev[1];
|
||||
}
|
||||
let (nfill, nart) = (count[tx][0] as usize, count[tx][1] as usize);
|
||||
let mut fe = vec![[0u32; 4]; nfill];
|
||||
let mut ae = vec![[0u32; 4]; nart];
|
||||
let mut cursor: Vec<[u32; 2]> = count[..tx].to_vec();
|
||||
for (c, es) in slices() {
|
||||
let (p0, b0) = (piece_at.get(c).copied().unwrap_or(0), bd_at.get(c).copied().unwrap_or(0));
|
||||
for &[op, tile, s0, n, bd] in es {
|
||||
let Some(cur) = cursor.get_mut(tile.wrapping_sub(first_tile) as usize) else { continue };
|
||||
let art = usize::from(op >= t.fills);
|
||||
let at = cur[art] as usize;
|
||||
cur[art] += 1;
|
||||
let bd = if bd == NONE { NONE } else { b0 + bd };
|
||||
let slot = if art == 1 { ae.get_mut(at) } else { fe.get_mut(at) };
|
||||
if let Some(slot) = slot {
|
||||
*slot = [op, p0 + s0, n, bd];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut out = RowOut { stream: Vec::with_capacity(nfill), heads: Vec::with_capacity(tx), work: 0 };
|
||||
let plain = t.scene.clips.is_empty() && t.scene.groups.is_empty();
|
||||
for tile in 0..tx {
|
||||
let start = out.stream.len();
|
||||
let fills = fe.get(count[tile][0] as usize..count[tile + 1][0] as usize).unwrap_or(&[]);
|
||||
if plain {
|
||||
out.stream.extend_from_slice(fills);
|
||||
} else {
|
||||
let arts = ae.get(count[tile][1] as usize..count[tile + 1][1] as usize).unwrap_or(&[]);
|
||||
tile_stream(fills, arts, t, &mut out.stream);
|
||||
}
|
||||
let mine = out.stream.get(start..).unwrap_or(&[]);
|
||||
out.work += mine.iter().map(|e| if e[0] & CTRL == 0 { u64::from(e[2]) + 1 } else { 1 }).sum::<u64>();
|
||||
out.heads.push([start as u32, mine.len() as u32]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One tile's stream: its fills, each preceded by the clip coverage it needs (when that clip
|
||||
/// isn't the one computed last) and the group opens and closes its group chain needs.
|
||||
fn tile_stream(fills: &[[u32; 4]], arts: &[[u32; 4]], t: &Tables, out: &mut Vec<[u32; 4]>) {
|
||||
// The artwork of clip `l` in this tile (artwork entries are in op order, clip by clip).
|
||||
let level = |l: u32| -> &[[u32; 4]] {
|
||||
let Some(&(a0, a1)) = t.art_ops.get(l as usize) else { return &[] };
|
||||
let lo = arts.partition_point(|e| e[0] < a0);
|
||||
let hi = arts.partition_point(|e| e[0] < a1);
|
||||
arts.get(lo..hi).unwrap_or(&[])
|
||||
};
|
||||
let close = |g: u32, out: &mut Vec<[u32; 4]>| {
|
||||
let (alpha, mode) = t.scene.groups.get(g as usize).map_or((1.0f32, 0), |x| (x.alpha, blend_code(x.blend)));
|
||||
out.push([CLOSE, alpha.to_bits(), mode, 0]);
|
||||
};
|
||||
let mut open: Vec<u32> = Vec::new();
|
||||
let mut clip = NONE;
|
||||
for e in fills {
|
||||
let op = e[0] as usize;
|
||||
let c = t.op_clip.get(op).copied().unwrap_or(NONE);
|
||||
if c != NONE && c != clip {
|
||||
let chain = t.clip_chain.get(c as usize).map_or(&[][..], Vec::as_slice);
|
||||
// A level with no artwork here hides the fill in the whole tile.
|
||||
if chain.is_empty() || chain.iter().any(|&l| level(l).is_empty()) {
|
||||
continue;
|
||||
}
|
||||
out.push([MASK_RESET, 0, 0, 0]);
|
||||
for &l in chain {
|
||||
out.push([LEVEL_BEGIN, 0, 0, 0]);
|
||||
out.extend_from_slice(level(l));
|
||||
out.push([LEVEL_END, 0, 0, 0]);
|
||||
}
|
||||
clip = c;
|
||||
}
|
||||
let g = t.op_group.get(op).copied().unwrap_or(NONE);
|
||||
let want = if g == NONE { &[][..] } else { t.scene.groups.get(g as usize).map_or(&[][..], |x| x.chain.as_slice()) };
|
||||
let keep = open.iter().zip(want).take_while(|(a, b)| a == b).count();
|
||||
while open.len() > keep {
|
||||
if let Some(g) = open.pop() {
|
||||
close(g, out);
|
||||
}
|
||||
}
|
||||
for &g in want.iter().skip(keep) {
|
||||
out.push([OPEN, g, 0, 0]);
|
||||
open.push(g);
|
||||
}
|
||||
out.push(*e);
|
||||
}
|
||||
while let Some(g) = open.pop() {
|
||||
close(g, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits one fill's edges into tile pieces and walks each tile row for backdrops.
|
||||
|
||||
+158
-9
@@ -1,4 +1,4 @@
|
||||
// AniCraft GPU stage: fine rasterization (ADR 0019).
|
||||
// AniCraft GPU stage: fine rasterization (ADR 0019, ADR 0029).
|
||||
//
|
||||
// One workgroup per 16 × 16 tile, one invocation per pixel. Each pixel walks its tile's entries
|
||||
// in drawing order. An entry's coverage is its backdrop (winding from edges left of the tile,
|
||||
@@ -6,6 +6,15 @@
|
||||
// same integral as the CPU oracle's accumulation buffer (crates/render/src/raster.rs). Then the
|
||||
// fill rule, the paint (solid, or the oracle's own 256-entry gradient table) and src-over on
|
||||
// premultiplied colour, all in f32, as the oracle does.
|
||||
//
|
||||
// Masks and groups (ADR 0029) are control entries in the same list, mirroring the oracle's band
|
||||
// compositor (crates/render/src/lib.rs): clip artwork unites into a level's coverage, levels
|
||||
// multiply into the clip coverage that clipped fills are scaled by; a group pushes the colour
|
||||
// so far and continues on transparent, and its close blends it into the colour below at the
|
||||
// group's alpha, in its blend mode (the W3C separable formulas, as the oracle's `blend`).
|
||||
//
|
||||
// Two entry points: `main` writes a storage buffer (premultiplied RGBA8 or f32, for readback),
|
||||
// `main_texture` writes premultiplied RGBA8 into a texture the window shows directly.
|
||||
|
||||
struct Params {
|
||||
// width, height, tiles across, output format (0: premultiplied RGBA8, 1: f32 RGBA)
|
||||
@@ -21,9 +30,20 @@ struct Params {
|
||||
@group(0) @binding(2) var<storage, read> geo: array<vec4<f32>>;
|
||||
@group(0) @binding(3) var<storage, read> paints: array<vec4<f32>>;
|
||||
@group(0) @binding(4) var<storage, read_write> out: array<u32>;
|
||||
@group(0) @binding(5) var out_texture: texture_storage_2d<rgba8unorm, write>;
|
||||
|
||||
const NONE: u32 = 0xffffffffu;
|
||||
const PAINT_VEC4S: u32 = 4u;
|
||||
// Must match binning.rs.
|
||||
const CTRL: u32 = 0x80000000u;
|
||||
const OPEN: u32 = 0x80000001u;
|
||||
const CLOSE: u32 = 0x80000002u;
|
||||
const MASK_RESET: u32 = 0x80000003u;
|
||||
const LEVEL_BEGIN: u32 = 0x80000004u;
|
||||
const LEVEL_END: u32 = 0x80000005u;
|
||||
const CLIPPED: u32 = 1u;
|
||||
const ART: u32 = 2u;
|
||||
const MAX_GROUP_DEPTH: u32 = 8u;
|
||||
|
||||
// Mean of clamp(u, 0, 1) for u running linearly from u0 to u1.
|
||||
fn avg_clamp(u0: f32, u1: f32) -> f32 {
|
||||
@@ -89,10 +109,80 @@ fn shade(op: u32, kind: u32, ramp: u32, p: vec2<f32>) -> vec4<f32> {
|
||||
return paints[ramp + i];
|
||||
}
|
||||
|
||||
@compute @workgroup_size(16, 16)
|
||||
fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
|
||||
let width = params.size.x;
|
||||
let height = params.size.y;
|
||||
fn unpremul(c: f32, a: f32) -> f32 {
|
||||
if a > 1e-6 {
|
||||
return clamp(c / a, 0.0, 1.0);
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
fn hard(cb: f32, cs: f32) -> f32 {
|
||||
if cs <= 0.5 {
|
||||
return cb * 2.0 * cs;
|
||||
}
|
||||
let t = 2.0 * cs - 1.0;
|
||||
return cb + t - cb * t;
|
||||
}
|
||||
|
||||
// The separable blend function B(cb, cs) for mode `m` (binning.rs › blend_code).
|
||||
fn blend_channel(m: u32, cb: f32, cs: f32) -> f32 {
|
||||
switch m {
|
||||
case 1u: { return cb * cs; }
|
||||
case 2u: { return cb + cs - cb * cs; }
|
||||
case 3u: { return min(cb, cs); }
|
||||
case 4u: { return max(cb, cs); }
|
||||
case 5u: { return abs(cb - cs); }
|
||||
case 6u: { return min(cb + cs, 1.0); }
|
||||
case 7u: { return max(cb - cs, 0.0); }
|
||||
case 8u: { return 1.0 - cb; }
|
||||
case 9u: { return hard(cb, cs); }
|
||||
case 10u: { return hard(cs, cb); }
|
||||
default: { return cs; }
|
||||
}
|
||||
}
|
||||
|
||||
// Source s over backdrop b (premultiplied) in mode m, as the oracle's `blend`.
|
||||
fn blend(m: u32, s: vec4<f32>, b: vec4<f32>) -> vec4<f32> {
|
||||
let sa = clamp(s.a, 0.0, 1.0);
|
||||
let ba = clamp(b.a, 0.0, 1.0);
|
||||
if m == 11u {
|
||||
return vec4<f32>(b.rgb * sa, ba * sa);
|
||||
}
|
||||
if m == 12u {
|
||||
let k = 1.0 - sa;
|
||||
return vec4<f32>(b.rgb * k, ba * k);
|
||||
}
|
||||
var o = vec4<f32>(0.0, 0.0, 0.0, sa + ba - sa * ba);
|
||||
for (var i = 0u; i < 3u; i++) {
|
||||
let cs = unpremul(s[i], sa);
|
||||
let cb = unpremul(b[i], ba);
|
||||
o[i] = (1.0 - ba) * s[i] + (1.0 - sa) * b[i] + sa * ba * blend_channel(m, cb, cs);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
// A group's colour `s` composited into `below` at `alpha`, in mode `m` (the oracle's
|
||||
// `close_group`, per pixel).
|
||||
fn close_group(s: vec4<f32>, below: vec4<f32>, alpha: f32, m: u32) -> vec4<f32> {
|
||||
if alpha <= 0.0 {
|
||||
return below;
|
||||
}
|
||||
if m != 0u {
|
||||
if s.a > 0.0 {
|
||||
return blend(m, s * alpha, below);
|
||||
}
|
||||
return below;
|
||||
}
|
||||
let sa = s.a * alpha;
|
||||
if sa <= 0.0 {
|
||||
return below;
|
||||
}
|
||||
let inv = 1.0 - sa;
|
||||
return vec4<f32>(s.rgb * alpha + below.rgb * inv, sa + below.a * inv);
|
||||
}
|
||||
|
||||
// The finished colour of pixel `lid` in tile `wg`.
|
||||
fn pixel(wg: vec3<u32>, lid: vec3<u32>) -> vec4<f32> {
|
||||
let tile = wg.y * params.size.z + wg.x;
|
||||
let x = wg.x * 16u + lid.x;
|
||||
let y = wg.y * 16u + lid.y;
|
||||
@@ -101,11 +191,37 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid:
|
||||
let centre = vec2<f32>(f32(x) + 0.5, f32(y) + 0.5);
|
||||
|
||||
var c = params.bg;
|
||||
var stack: array<vec4<f32>, MAX_GROUP_DEPTH>;
|
||||
var depth = 0u;
|
||||
var mask = 1.0;
|
||||
var level = 0.0;
|
||||
let start = index[tile * 2u];
|
||||
let count = index[tile * 2u + 1u];
|
||||
for (var i = 0u; i < count; i++) {
|
||||
let e = params.at.x + (start + i) * 4u;
|
||||
let op = index[e];
|
||||
if (op & CTRL) != 0u {
|
||||
switch op {
|
||||
case OPEN: {
|
||||
if depth < MAX_GROUP_DEPTH {
|
||||
stack[depth] = c;
|
||||
depth += 1u;
|
||||
}
|
||||
c = vec4<f32>(0.0);
|
||||
}
|
||||
case CLOSE: {
|
||||
if depth > 0u {
|
||||
depth -= 1u;
|
||||
c = close_group(c, stack[depth], bitcast<f32>(index[e + 1u]), index[e + 2u]);
|
||||
}
|
||||
}
|
||||
case MASK_RESET: { mask = 1.0; }
|
||||
case LEVEL_BEGIN: { level = 0.0; }
|
||||
case LEVEL_END: { mask *= level; }
|
||||
default: {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let first = index[e + 1u];
|
||||
let pieces = index[e + 2u];
|
||||
let bd = index[e + 3u];
|
||||
@@ -117,20 +233,41 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid:
|
||||
w += piece_cover(geo[first + k], px, py);
|
||||
}
|
||||
let h = params.at.y + op * 4u;
|
||||
let cov = fold(w, index[h + 1u]);
|
||||
var cov = fold(w, index[h + 1u]);
|
||||
let flags = index[h + 3u];
|
||||
if (flags & ART) != 0u {
|
||||
let k = clamp(cov, 0.0, 1.0);
|
||||
level = level + k - level * k;
|
||||
continue;
|
||||
}
|
||||
if (flags & CLIPPED) != 0u {
|
||||
cov *= mask;
|
||||
}
|
||||
if cov <= 1e-4 {
|
||||
continue;
|
||||
}
|
||||
let s = shade(op, index[h], index[h + 2u], centre);
|
||||
c = s * cov + c * (1.0 - s.a * cov);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
if x >= width || y >= height {
|
||||
// Premultiplied RGBA8 steps, rounded as the oracle's `Pixmap::to_premul_rgba8`.
|
||||
fn quantize(c: vec4<f32>) -> vec4<u32> {
|
||||
return vec4<u32>(clamp(c, vec4<f32>(0.0), vec4<f32>(1.0)) * 255.0 + 0.5);
|
||||
}
|
||||
|
||||
@compute @workgroup_size(16, 16)
|
||||
fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
|
||||
let c = pixel(wg, lid);
|
||||
let x = wg.x * 16u + lid.x;
|
||||
let y = wg.y * 16u + lid.y;
|
||||
if x >= params.size.x || y >= params.size.y {
|
||||
return;
|
||||
}
|
||||
let at = y * width + x;
|
||||
let at = y * params.size.x + x;
|
||||
if params.size.w == 0u {
|
||||
let q = vec4<u32>(clamp(c, vec4<f32>(0.0), vec4<f32>(1.0)) * 255.0 + 0.5);
|
||||
let q = quantize(c);
|
||||
out[at] = q.x | (q.y << 8u) | (q.z << 16u) | (q.w << 24u);
|
||||
} else {
|
||||
out[at * 4u] = bitcast<u32>(c.x);
|
||||
@@ -139,3 +276,15 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid:
|
||||
out[at * 4u + 3u] = bitcast<u32>(c.w);
|
||||
}
|
||||
}
|
||||
|
||||
@compute @workgroup_size(16, 16)
|
||||
fn main_texture(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
|
||||
let c = pixel(wg, lid);
|
||||
let x = wg.x * 16u + lid.x;
|
||||
let y = wg.y * 16u + lid.y;
|
||||
if x >= params.size.x || y >= params.size.y {
|
||||
return;
|
||||
}
|
||||
// Exactly k / 255, so the texture's unorm conversion lands on the oracle's byte k.
|
||||
textureStore(out_texture, vec2<u32>(x, y), vec4<f32>(quantize(c)) / 255.0);
|
||||
}
|
||||
+335
-131
@@ -1,22 +1,26 @@
|
||||
//! AniCraft GPU stage renderer (layer L3, beside the engine; ADR 0019).
|
||||
//! AniCraft GPU stage renderer (layer L3, beside the engine; ADR 0019, ADR 0029).
|
||||
//!
|
||||
//! Draws the same fills as the CPU oracle (`anicraft-render`) with wgpu compute: the oracle
|
||||
//! prepares the fills ([`anicraft_render::plain_fills`]: flattening, strokes, paints and their
|
||||
//! gradient tables), [`binning`] sorts their edges into 16 × 16 tiles on the CPU, and one
|
||||
//! compute pass computes every pixel's exact area coverage and composites the fills in order.
|
||||
//! The output is the oracle's within float rounding (the parity tests check mean and maximum
|
||||
//! error against it).
|
||||
//! Draws the same scene as the CPU oracle (`anicraft-render`) with wgpu compute: the oracle
|
||||
//! prepares it ([`anicraft_render::prepare_scene`]: flattening, strokes, paints and their
|
||||
//! gradient tables, clips and groups), [`binning`] sorts the edges into 16 × 16 tiles on the
|
||||
//! CPU, and one compute pass computes every pixel's exact area coverage and composites the
|
||||
//! fills in order, inside their masks and groups (alpha and blend modes) as the oracle's band
|
||||
//! compositor does. The output is the oracle's within float rounding (the parity tests check
|
||||
//! mean and maximum error against it).
|
||||
//!
|
||||
//! What the plain path doesn't cover yet (masks, group opacity, blend modes, filters,
|
||||
//! bitmaps) is reported as [`GpuError::NeedsFull`], and the caller renders that frame on the
|
||||
//! CPU. The renderer owns a headless device, so it works without a window, in tests and on
|
||||
//! machines where the window itself runs on OpenGL.
|
||||
//! What it doesn't draw yet (filters, bitmaps, nesting deeper than the shader holds) is
|
||||
//! reported as [`GpuError::NeedsFull`], and the caller renders that picture on the CPU.
|
||||
//!
|
||||
//! Two ways to run: on a **headless device of its own** ([`GpuRenderer::new`]: tests, tools,
|
||||
//! and windows that run on OpenGL), reading frames back; or on the **window's device**
|
||||
//! ([`GpuRenderer::shared`]), drawing into a texture ([`GpuRenderer::render_texture`]) that
|
||||
//! the window shows as it is, with no readback.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod binning;
|
||||
|
||||
use anicraft_doc::DisplayList;
|
||||
use anicraft_render::{MAX_PIXELS, NeedsFull, Pixmap, RenderStats, View, paint::premultiply, plain_fills};
|
||||
use anicraft_render::{MAX_PIXELS, NeedsFull, Pixmap, RenderStats, View, paint::premultiply, prepare_scene};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Instant;
|
||||
use wgpu::util::DeviceExt;
|
||||
@@ -45,7 +49,7 @@ pub enum Output {
|
||||
Float,
|
||||
}
|
||||
|
||||
/// A rendered frame.
|
||||
/// A rendered frame, read back.
|
||||
pub struct GpuFrame {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
@@ -60,14 +64,29 @@ pub struct GpuFrame {
|
||||
pub pieces: usize,
|
||||
}
|
||||
|
||||
/// Where a frame's time went (milliseconds).
|
||||
/// A frame rendered into a texture on the renderer's device: premultiplied RGBA8
|
||||
/// (`Rgba8Unorm`, the bytes [`Pixmap::to_premul_rgba8`] gives), sampleable, ready for the window
|
||||
/// to show (egui's `register_native_texture`). The work is submitted, not waited for: anything
|
||||
/// later on the same queue (the window's own drawing) sees it finished.
|
||||
pub struct GpuTexture {
|
||||
pub texture: wgpu::Texture,
|
||||
pub view: wgpu::TextureView,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub stats: RenderStats,
|
||||
pub timings: Timings,
|
||||
pub entries: usize,
|
||||
pub pieces: usize,
|
||||
}
|
||||
|
||||
/// Where a frame's time went (milliseconds, on the calling thread).
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Timings {
|
||||
/// Cull, flatten, stroke and paint set-up (shared with the oracle, parallel).
|
||||
pub prepare: f32,
|
||||
/// Tile binning (parallel per fill) and buffer packing.
|
||||
/// Tile binning (parallel per fill and per tile row) and buffer packing.
|
||||
pub bin: f32,
|
||||
/// Upload, compute pass, readback.
|
||||
/// Upload and submit; for read-back frames also the wait for the GPU and the copy back.
|
||||
pub gpu: f32,
|
||||
}
|
||||
|
||||
@@ -77,48 +96,97 @@ impl Timings {
|
||||
}
|
||||
}
|
||||
|
||||
/// The renderer: a headless device and the fine pipeline.
|
||||
/// Most work one dispatch may carry (edge pieces plus entries, summed over tiles, each walked
|
||||
/// by 256 pixels). Far above real scenes (the 10k-shape 4K stress frame is about 1M), it
|
||||
/// keeps a pathological frame from running long enough for the driver to reset the GPU, which
|
||||
/// on a shared device would take the window with it. Such a frame is drawn on the CPU.
|
||||
pub const MAX_WORK: u64 = 1 << 25;
|
||||
|
||||
/// Where the fine pass writes.
|
||||
enum Target<'a> {
|
||||
Buffer(&'a wgpu::Buffer),
|
||||
Texture(&'a wgpu::TextureView),
|
||||
}
|
||||
|
||||
/// The renderer: a device (its own, or the window's) and the fine pipelines.
|
||||
pub struct GpuRenderer {
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
pipeline: wgpu::ComputePipeline,
|
||||
layout: wgpu::BindGroupLayout,
|
||||
texture_pipeline: wgpu::ComputePipeline,
|
||||
texture_layout: wgpu::BindGroupLayout,
|
||||
limits: wgpu::Limits,
|
||||
/// Adapter name and backend, for the status bar and reports.
|
||||
pub adapter: String,
|
||||
/// First error the device reported outside our error scopes (or its loss). Once set, the
|
||||
/// renderer refuses to draw and callers fall back to the CPU.
|
||||
/// Whether the device is the window's (frames go to textures the window shows).
|
||||
pub shared: bool,
|
||||
/// First device failure (an error in a render, an uncaptured error or the device's loss).
|
||||
/// Once set, the renderer refuses to draw and callers fall back to the CPU.
|
||||
broken: Arc<Mutex<Option<String>>>,
|
||||
}
|
||||
|
||||
/// Checks an adapter and device can run the stage; the device's own limits are what count
|
||||
/// (a window's device may have asked for less than its adapter has).
|
||||
fn check(adapter: &wgpu::Adapter, limits: &wgpu::Limits, name: &str) -> Result<(), GpuError> {
|
||||
if !adapter.get_downlevel_capabilities().flags.contains(wgpu::DownlevelFlags::COMPUTE_SHADERS) {
|
||||
return Err(GpuError::Unavailable(format!("{name} has no compute shaders")));
|
||||
}
|
||||
if limits.max_storage_buffers_per_shader_stage < 4
|
||||
|| limits.max_storage_textures_per_shader_stage < 1
|
||||
|| limits.max_compute_invocations_per_workgroup < 256
|
||||
|| limits.max_compute_workgroup_size_x < 16
|
||||
|| limits.max_compute_workgroup_size_y < 16
|
||||
{
|
||||
return Err(GpuError::Unavailable(format!("{name} is below the compute limits the stage needs")));
|
||||
}
|
||||
if !adapter.get_texture_format_features(wgpu::TextureFormat::Rgba8Unorm).allowed_usages.contains(wgpu::TextureUsages::STORAGE_BINDING) {
|
||||
return Err(GpuError::Unavailable(format!("{name} can't write RGBA8 textures from compute")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl GpuRenderer {
|
||||
/// Opens a headless device on the best adapter (high-performance first), builds the
|
||||
/// pipeline and checks it with a small known render. `Err` means "use the CPU".
|
||||
/// pipelines and checks them with a small known render. `Err` means "use the CPU".
|
||||
pub fn new() -> Result<GpuRenderer, GpuError> {
|
||||
// A renderer bug must never take the caller down: wgpu reports misuse by panicking.
|
||||
std::panic::catch_unwind(Self::open).unwrap_or_else(|_| Err(GpuError::Unavailable("the GPU driver failed while starting".into())))
|
||||
}
|
||||
|
||||
/// Runs on the window's device and queue (eframe's `egui_wgpu::RenderState`), so frames
|
||||
/// can go straight into textures the window shows. Nothing is installed on the device:
|
||||
/// every call the renderer makes runs inside its own (thread-local) error scopes, the
|
||||
/// window's error handling stays as it was. `Err` means "use a device of our own, or the
|
||||
/// CPU".
|
||||
pub fn shared(adapter: &wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Result<GpuRenderer, GpuError> {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
let info = adapter.get_info();
|
||||
let name = format!("{} ({:?})", info.name, info.backend);
|
||||
let limits = device.limits();
|
||||
check(adapter, &limits, &name)?;
|
||||
Self::build(device, queue, limits, name, true, Arc::new(Mutex::new(None)))
|
||||
}))
|
||||
.unwrap_or_else(|_| Err(GpuError::Unavailable("the GPU driver failed while starting".into())))
|
||||
}
|
||||
|
||||
fn open() -> Result<GpuRenderer, GpuError> {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
|
||||
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }))
|
||||
.map_err(|e| GpuError::Unavailable(e.to_string()))?;
|
||||
let info = adapter.get_info();
|
||||
let name = format!("{} ({:?})", info.name, info.backend);
|
||||
if !adapter.get_downlevel_capabilities().flags.contains(wgpu::DownlevelFlags::COMPUTE_SHADERS) {
|
||||
return Err(GpuError::Unavailable(format!("{name} has no compute shaders")));
|
||||
}
|
||||
let have = adapter.limits();
|
||||
let want = wgpu::Limits {
|
||||
max_storage_buffer_binding_size: have.max_storage_buffer_binding_size,
|
||||
max_buffer_size: have.max_buffer_size,
|
||||
max_texture_dimension_2d: have.max_texture_dimension_2d,
|
||||
..wgpu::Limits::downlevel_defaults()
|
||||
};
|
||||
if have.max_storage_buffers_per_shader_stage < 4 || have.max_compute_invocations_per_workgroup < 256 || have.max_compute_workgroup_size_x < 16 || have.max_compute_workgroup_size_y < 16 {
|
||||
return Err(GpuError::Unavailable(format!("{name} is below the compute limits the stage needs")));
|
||||
}
|
||||
check(&adapter, &have, &name)?;
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("anicraft-gpu"), required_limits: want.clone(), ..Default::default() }))
|
||||
.map_err(|e| GpuError::Unavailable(format!("{name}: {e}")))?;
|
||||
// Our own device: its uncaptured errors and its loss are ours to catch.
|
||||
let broken: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
|
||||
{
|
||||
let b = broken.clone();
|
||||
@@ -132,48 +200,44 @@ impl GpuRenderer {
|
||||
g.get_or_insert_with(|| format!("device lost: {msg}"));
|
||||
});
|
||||
}
|
||||
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
Self::build(device, queue, want, name, false, broken)
|
||||
}
|
||||
|
||||
fn build(device: wgpu::Device, queue: wgpu::Queue, limits: wgpu::Limits, name: String, shared: bool, broken: Arc<Mutex<Option<String>>>) -> Result<GpuRenderer, GpuError> {
|
||||
let scopes = Scopes::push(&device);
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("anicraft-fine"), source: wgpu::ShaderSource::Wgsl(include_str!("fine.wgsl").into()) });
|
||||
let storage = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only }, has_dynamic_offset: false, min_binding_size: None },
|
||||
count: None,
|
||||
let entry = |binding: u32, ty: wgpu::BindingType| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None };
|
||||
let buffer = |ty| wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None };
|
||||
let read = || buffer(wgpu::BufferBindingType::Storage { read_only: true });
|
||||
let common = [entry(0, buffer(wgpu::BufferBindingType::Uniform)), entry(1, read()), entry(2, read()), entry(3, read())];
|
||||
let make = |label: &str, out: wgpu::BindGroupLayoutEntry, entry_point: &str| {
|
||||
let mut entries = common.to_vec();
|
||||
entries.push(out);
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries: &entries });
|
||||
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: &[Some(&layout)], immediate_size: 0 });
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some(label),
|
||||
layout: Some(&pl),
|
||||
module: &module,
|
||||
entry_point: Some(entry_point),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
(pipeline, layout)
|
||||
};
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("anicraft-fine"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
|
||||
count: None,
|
||||
},
|
||||
storage(1, true),
|
||||
storage(2, true),
|
||||
storage(3, true),
|
||||
storage(4, false),
|
||||
],
|
||||
});
|
||||
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("anicraft-fine"), bind_group_layouts: &[Some(&layout)], immediate_size: 0 });
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("anicraft-fine"),
|
||||
layout: Some(&pl),
|
||||
module: &module,
|
||||
entry_point: Some("main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
if let Some(e) = pollster::block_on(scope.pop()) {
|
||||
let (pipeline, layout) = make("anicraft-fine", entry(4, buffer(wgpu::BufferBindingType::Storage { read_only: false })), "main");
|
||||
let storage_texture = wgpu::BindingType::StorageTexture { access: wgpu::StorageTextureAccess::WriteOnly, format: wgpu::TextureFormat::Rgba8Unorm, view_dimension: wgpu::TextureViewDimension::D2 };
|
||||
let (texture_pipeline, texture_layout) = make("anicraft-fine-texture", entry(5, storage_texture), "main_texture");
|
||||
if let Some(e) = scopes.pop() {
|
||||
return Err(GpuError::Unavailable(format!("{name}: the stage shader did not build: {e}")));
|
||||
}
|
||||
let r = GpuRenderer { device, queue, pipeline, layout, limits: want, adapter: name, broken };
|
||||
let r = GpuRenderer { device, queue, pipeline, layout, texture_pipeline, texture_layout, limits, adapter: name, shared, broken };
|
||||
r.self_test()?;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// A 24 × 20 render of two known rectangles must come back exactly: catches drivers that
|
||||
/// build the pipeline but compute garbage.
|
||||
/// A 24 × 20 render of two known rectangles must come back exactly, read back and through a
|
||||
/// texture: catches drivers that build the pipelines but compute garbage.
|
||||
fn self_test(&self) -> Result<(), GpuError> {
|
||||
use anicraft_doc::{ColorEffect, DisplayItem, ElementId, LayerId, Paint, Rgba};
|
||||
use anicraft_geom::{Affine, FillRule, Path};
|
||||
@@ -195,69 +259,145 @@ impl GpuRenderer {
|
||||
};
|
||||
let dl = DisplayList { items: vec![item(2.0, Rgba::new(1.0, 0.0, 0.0, 1.0)), item(14.0, Rgba::new(0.0, 0.0, 1.0, 0.5))], ..Default::default() };
|
||||
let view = View { transform: Affine::IDENTITY, width: 24, height: 20, background: Some(Rgba::WHITE) };
|
||||
let ok = |bytes: &[u8]| {
|
||||
let px = |x: usize, y: usize| bytes.get((y * 24 + x) * 4..(y * 24 + x) * 4 + 4).map(<[u8]>::to_vec);
|
||||
px(5, 10) == Some(vec![255, 0, 0, 255]) && px(18, 10) == Some(vec![128, 128, 255, 255]) && px(12, 1) == Some(vec![255; 4])
|
||||
};
|
||||
let f = self.render(&dl, &view, Output::Premul8)?;
|
||||
let px = |x: usize, y: usize| f.premul8.get((y * 24 + x) * 4..(y * 24 + x) * 4 + 4).map(<[u8]>::to_vec);
|
||||
let ok = px(5, 10) == Some(vec![255, 0, 0, 255]) && px(18, 10) == Some(vec![128, 128, 255, 255]) && px(12, 1) == Some(vec![255; 4]);
|
||||
if !ok {
|
||||
let t = self.render_texture(&dl, &view)?;
|
||||
if !ok(&f.premul8) || !ok(&self.read_texture(&t)?) {
|
||||
return Err(GpuError::Unavailable(format!("{}: the self-test render came back wrong", self.adapter)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the device has failed (lost, or an error outside a render); then use the CPU.
|
||||
/// Whether the device has failed (lost, or an error in or outside a render); then use the
|
||||
/// CPU.
|
||||
pub fn broken(&self) -> Option<String> {
|
||||
self.broken.lock().unwrap_or_else(PoisonError::into_inner).clone()
|
||||
}
|
||||
|
||||
/// Renders a display list. [`GpuError::NeedsFull`] means "draw this one on the CPU".
|
||||
pub fn render(&self, dl: &DisplayList, view: &View, output: Output) -> Result<GpuFrame, GpuError> {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.render_inner(dl, view, output))).unwrap_or_else(|_| Err(GpuError::Device("the GPU renderer failed on this frame".into())))
|
||||
fn mark_broken(&self, why: &str) {
|
||||
self.broken.lock().unwrap_or_else(PoisonError::into_inner).get_or_insert_with(|| why.to_string());
|
||||
}
|
||||
|
||||
fn render_inner(&self, dl: &DisplayList, view: &View, output: Output) -> Result<GpuFrame, GpuError> {
|
||||
/// Renders a display list and reads it back. [`GpuError::NeedsFull`] means "draw this one
|
||||
/// on the CPU".
|
||||
pub fn render(&self, dl: &DisplayList, view: &View, output: Output) -> Result<GpuFrame, GpuError> {
|
||||
self.guard(|| {
|
||||
let (b, stats, mut timings) = self.prepare(dl, view)?;
|
||||
let t = Instant::now();
|
||||
let (premul8, pixmap) = self.run_readback(&b, view, output)?;
|
||||
timings.gpu = ms(t);
|
||||
Ok(GpuFrame { width: view.width, height: view.height, premul8, pixmap, stats, timings, entries: b.entries, pieces: b.pieces })
|
||||
})
|
||||
}
|
||||
|
||||
/// Renders a display list into a new texture on this renderer's device (no readback).
|
||||
pub fn render_texture(&self, dl: &DisplayList, view: &View) -> Result<GpuTexture, GpuError> {
|
||||
self.guard(|| {
|
||||
let (b, stats, mut timings) = self.prepare(dl, view)?;
|
||||
let t = Instant::now();
|
||||
let (w, h) = (view.width, view.height);
|
||||
let max = self.limits.max_texture_dimension_2d;
|
||||
if w > max || h > max {
|
||||
return Err(GpuError::TooLarge(format!("image {w}×{h} is larger than this GPU's textures ({max} px)")));
|
||||
}
|
||||
let scopes = Scopes::push(&self.device);
|
||||
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("anicraft-stage"),
|
||||
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
});
|
||||
let tex_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let enc = self.encode(&b, view, Output::Premul8, Target::Texture(&tex_view))?;
|
||||
self.queue.submit([enc]);
|
||||
self.pop(scopes)?;
|
||||
timings.gpu = ms(t);
|
||||
Ok(GpuTexture { texture, view: tex_view, width: w, height: h, stats, timings, entries: b.entries, pieces: b.pieces })
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads a texture from [`GpuRenderer::render_texture`] back (tests, benchmarks and the
|
||||
/// self-test; the stage never does).
|
||||
pub fn read_texture(&self, t: &GpuTexture) -> Result<Vec<u8>, GpuError> {
|
||||
self.guard(|| {
|
||||
let row = (t.width * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
|
||||
let scopes = Scopes::push(&self.device);
|
||||
let read = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: u64::from(row) * u64::from(t.height), usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
|
||||
let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("anicraft-readback") });
|
||||
enc.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
wgpu::TexelCopyBufferInfo { buffer: &read, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: Some(t.height) } },
|
||||
wgpu::Extent3d { width: t.width, height: t.height, depth_or_array_layers: 1 },
|
||||
);
|
||||
self.queue.submit([enc.finish()]);
|
||||
let bytes = self.map(&read, scopes)?;
|
||||
let mut out = Vec::with_capacity(t.width as usize * t.height as usize * 4);
|
||||
for r in bytes.chunks(row as usize) {
|
||||
out.extend_from_slice(r.get(..t.width as usize * 4).unwrap_or(&[]));
|
||||
}
|
||||
Ok(out)
|
||||
})
|
||||
}
|
||||
|
||||
/// Blocks until everything submitted so far has run (benchmarks).
|
||||
pub fn wait_idle(&self) -> Result<(), GpuError> {
|
||||
self.device.poll(wgpu::PollType::wait_indefinitely()).map(|_| ()).map_err(|e| GpuError::Device(e.to_string()))
|
||||
}
|
||||
|
||||
/// Every call runs inside `catch_unwind` (wgpu reports misuse by panicking), refuses once the
|
||||
/// device is broken, and marks it broken on a device error.
|
||||
fn guard<R>(&self, f: impl FnOnce() -> Result<R, GpuError>) -> Result<R, GpuError> {
|
||||
if let Some(e) = self.broken() {
|
||||
return Err(GpuError::Device(e));
|
||||
}
|
||||
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| Err(GpuError::Device("the GPU renderer failed on this frame".into())));
|
||||
if let Err(GpuError::Device(e)) = &r {
|
||||
self.mark_broken(e);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// The oracle's preparation, then the binning; checked against the device's limits.
|
||||
fn prepare(&self, dl: &DisplayList, view: &View) -> Result<(binning::Binned, RenderStats, Timings), GpuError> {
|
||||
let (w, h) = (view.width, view.height);
|
||||
if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS {
|
||||
return Err(GpuError::TooLarge(format!("image {w}×{h} is outside the GPU stage's range")));
|
||||
}
|
||||
let t0 = Instant::now();
|
||||
let (fills, stats) = plain_fills(dl, view).map_err(GpuError::NeedsFull)?;
|
||||
let (scene, stats) = prepare_scene(dl, view).map_err(GpuError::NeedsFull)?;
|
||||
let t1 = Instant::now();
|
||||
let b = binning::bin(&fills, w, h);
|
||||
let b = binning::bin(&scene, w, h).map_err(GpuError::NeedsFull)?;
|
||||
// Free the prepared polygons on the pool, off this frame's path (as the oracle does).
|
||||
rayon::spawn(move || drop(fills));
|
||||
let t2 = Instant::now();
|
||||
let (premul8, pixmap) = self.run(&b, view, output)?;
|
||||
let t3 = Instant::now();
|
||||
let ms = |a: Instant, b: Instant| (b - a).as_secs_f32() * 1000.0;
|
||||
Ok(GpuFrame { width: w, height: h, premul8, pixmap, stats, timings: Timings { prepare: ms(t0, t1), bin: ms(t1, t2), gpu: ms(t2, t3) }, entries: b.entries, pieces: b.pieces })
|
||||
}
|
||||
|
||||
fn run(&self, b: &binning::Binned, view: &View, output: Output) -> Result<(Vec<u8>, Option<Pixmap>), GpuError> {
|
||||
let (w, h) = (view.width, view.height);
|
||||
let px = u64::from(w) * u64::from(h);
|
||||
let out_bytes = px * if output == Output::Float { 16 } else { 4 };
|
||||
let index: &[u8] = bytemuck::cast_slice(&b.index);
|
||||
let geo: &[u8] = bytemuck::cast_slice(&b.geo);
|
||||
let paints: &[u8] = bytemuck::cast_slice(&b.paints);
|
||||
rayon::spawn(move || drop(scene));
|
||||
if b.work > MAX_WORK {
|
||||
return Err(GpuError::TooLarge(format!("this frame is too much work for one GPU pass ({} M)", b.work >> 20)));
|
||||
}
|
||||
let cap = self.limits.max_storage_buffer_binding_size.min(self.limits.max_buffer_size);
|
||||
for (what, n) in [("tile lists", index.len() as u64), ("edges", geo.len() as u64), ("paints", paints.len() as u64), ("the image", out_bytes)] {
|
||||
if n > cap {
|
||||
let sizes = [("tile lists", b.index.len() * 4), ("edges", b.geo.len() * 16), ("paints", b.paints.len() * 16)];
|
||||
for (what, n) in sizes {
|
||||
if n as u64 > cap {
|
||||
return Err(GpuError::TooLarge(format!("{what} need {} MB, more than this GPU binds ({} MB)", n >> 20, cap >> 20)));
|
||||
}
|
||||
}
|
||||
Ok((b, stats, Timings { prepare: (t1 - t0).as_secs_f32() * 1000.0, bin: ms(t1), gpu: 0.0 }))
|
||||
}
|
||||
|
||||
/// Uploads the binned scene and records the fine pass into `target`.
|
||||
fn encode(&self, b: &binning::Binned, view: &View, output: Output, target: Target) -> Result<wgpu::CommandBuffer, GpuError> {
|
||||
let bg = view.background.map_or([0.0; 4], premultiply);
|
||||
let mut uniform = [0u32; 12];
|
||||
uniform[..4].copy_from_slice(&[w, h, b.tiles_x, u32::from(output == Output::Float)]);
|
||||
uniform[..4].copy_from_slice(&[view.width, view.height, b.tiles_x, u32::from(output == Output::Float)]);
|
||||
uniform[4..6].copy_from_slice(&[b.entries_at, b.ops_at]);
|
||||
for (u, f) in uniform[8..].iter_mut().zip(bg) {
|
||||
*u = f.to_bits();
|
||||
}
|
||||
|
||||
let oom = self.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let valid = self.device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let storage = |label: &str, bytes: &[u8]| {
|
||||
// Bindings can't be empty: pad to one vec4.
|
||||
let pad = [0u8; 16];
|
||||
@@ -265,66 +405,130 @@ impl GpuRenderer {
|
||||
self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents, usage: wgpu::BufferUsages::STORAGE })
|
||||
};
|
||||
let ubuf = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("params"), contents: bytemuck::cast_slice(&uniform), usage: wgpu::BufferUsages::UNIFORM });
|
||||
let ibuf = storage("index", index);
|
||||
let gbuf = storage("geo", geo);
|
||||
let pbuf = storage("paints", paints);
|
||||
let obuf = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("out"), size: out_bytes, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });
|
||||
let read = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: out_bytes, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
|
||||
let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("anicraft-fine"),
|
||||
layout: &self.layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 1, resource: ibuf.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 2, resource: gbuf.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 3, resource: pbuf.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 4, resource: obuf.as_entire_binding() },
|
||||
],
|
||||
});
|
||||
let ibuf = storage("index", bytemuck::cast_slice(&b.index));
|
||||
let gbuf = storage("geo", bytemuck::cast_slice(&b.geo));
|
||||
let pbuf = storage("paints", bytemuck::cast_slice(&b.paints));
|
||||
let mut entries = vec![
|
||||
wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 1, resource: ibuf.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 2, resource: gbuf.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 3, resource: pbuf.as_entire_binding() },
|
||||
];
|
||||
let (pipeline, layout) = match target {
|
||||
Target::Buffer(out) => {
|
||||
entries.push(wgpu::BindGroupEntry { binding: 4, resource: out.as_entire_binding() });
|
||||
(&self.pipeline, &self.layout)
|
||||
}
|
||||
Target::Texture(view) => {
|
||||
entries.push(wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(view) });
|
||||
(&self.texture_pipeline, &self.texture_layout)
|
||||
}
|
||||
};
|
||||
let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("anicraft-fine"), layout, entries: &entries });
|
||||
let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("anicraft-fine") });
|
||||
{
|
||||
let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("anicraft-fine"), timestamp_writes: None });
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.set_bind_group(0, &bind, &[]);
|
||||
pass.dispatch_workgroups(b.tiles_x, b.tiles_y, 1);
|
||||
}
|
||||
Ok(enc.finish())
|
||||
}
|
||||
|
||||
fn run_readback(&self, b: &binning::Binned, view: &View, output: Output) -> Result<(Vec<u8>, Option<Pixmap>), GpuError> {
|
||||
let (w, h) = (view.width, view.height);
|
||||
let out_bytes = u64::from(w) * u64::from(h) * if output == Output::Float { 16 } else { 4 };
|
||||
let cap = self.limits.max_storage_buffer_binding_size.min(self.limits.max_buffer_size);
|
||||
if out_bytes > cap {
|
||||
return Err(GpuError::TooLarge(format!("the image needs {} MB, more than this GPU binds ({} MB)", out_bytes >> 20, cap >> 20)));
|
||||
}
|
||||
let scopes = Scopes::push(&self.device);
|
||||
let obuf = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("out"), size: out_bytes, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });
|
||||
let read = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: out_bytes, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
|
||||
let fine = self.encode(b, view, output, Target::Buffer(&obuf))?;
|
||||
let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("anicraft-readback") });
|
||||
enc.copy_buffer_to_buffer(&obuf, 0, &read, 0, out_bytes);
|
||||
self.queue.submit([enc.finish()]);
|
||||
self.queue.submit([fine, enc.finish()]);
|
||||
let bytes = self.map(&read, scopes)?;
|
||||
Ok(match output {
|
||||
Output::Premul8 => (bytes, None),
|
||||
Output::Float => {
|
||||
let mut pm = Pixmap::new(w, h).map_err(|e| GpuError::TooLarge(e.to_string()))?;
|
||||
for (p, q) in pm.data.iter_mut().zip(bytes.as_chunks::<16>().0) {
|
||||
for (c, v) in p.iter_mut().zip(q.as_chunks::<4>().0) {
|
||||
*c = f32::from_le_bytes(*v);
|
||||
}
|
||||
}
|
||||
(Vec::new(), Some(pm))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Waits for `read`'s copy, pops the error scopes and returns its bytes.
|
||||
fn map(&self, read: &wgpu::Buffer, scopes: Scopes) -> Result<Vec<u8>, GpuError> {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
read.slice(..).map_async(wgpu::MapMode::Read, move |r| {
|
||||
let _ = tx.send(r);
|
||||
});
|
||||
let polled = self.device.poll(wgpu::PollType::wait_indefinitely());
|
||||
let invalid = pollster::block_on(valid.pop());
|
||||
let no_memory = pollster::block_on(oom.pop());
|
||||
if let Some(e) = invalid.or(no_memory) {
|
||||
return Err(GpuError::Device(e.to_string()));
|
||||
}
|
||||
self.pop(scopes)?;
|
||||
polled.map_err(|e| GpuError::Device(e.to_string()))?;
|
||||
match rx.recv() {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(e)) => return Err(GpuError::Device(e.to_string())),
|
||||
Err(_) => return Err(GpuError::Device("the readback never completed".into())),
|
||||
}
|
||||
let result = {
|
||||
let view = read.slice(..).get_mapped_range().map_err(|e| GpuError::Device(e.to_string()))?;
|
||||
let bytes: &[u8] = &view;
|
||||
match output {
|
||||
Output::Premul8 => (bytes.to_vec(), None),
|
||||
Output::Float => {
|
||||
let mut pm = Pixmap::new(w, h).map_err(|e| GpuError::TooLarge(e.to_string()))?;
|
||||
for (p, q) in pm.data.iter_mut().zip(bytes.as_chunks::<16>().0) {
|
||||
for (c, v) in p.iter_mut().zip(q.as_chunks::<4>().0) {
|
||||
*c = f32::from_le_bytes(*v);
|
||||
}
|
||||
}
|
||||
(Vec::new(), Some(pm))
|
||||
}
|
||||
}
|
||||
};
|
||||
let bytes = read.slice(..).get_mapped_range().map_err(|e| GpuError::Device(e.to_string()))?.to_vec();
|
||||
read.unmap();
|
||||
Ok(result)
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Pops a render's scopes: out of memory fails just this frame (the CPU draws it); any
|
||||
/// other error is a device error and stops the GPU stage.
|
||||
fn pop(&self, scopes: Scopes) -> Result<(), GpuError> {
|
||||
let (oom, other) = scopes.pop_split();
|
||||
if let Some(e) = other {
|
||||
return Err(GpuError::Device(e.to_string()));
|
||||
}
|
||||
if let Some(e) = oom {
|
||||
return Err(GpuError::TooLarge(format!("the GPU ran out of memory: {e}")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The error scopes around one render on this thread: nothing the renderer does can reach the
|
||||
/// device's uncaptured-error handler (on the window's device that would be the window's).
|
||||
struct Scopes {
|
||||
internal: wgpu::ErrorScopeGuard,
|
||||
oom: wgpu::ErrorScopeGuard,
|
||||
valid: wgpu::ErrorScopeGuard,
|
||||
}
|
||||
|
||||
impl Scopes {
|
||||
fn push(device: &wgpu::Device) -> Scopes {
|
||||
let internal = device.push_error_scope(wgpu::ErrorFilter::Internal);
|
||||
let oom = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let valid = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
Scopes { internal, oom, valid }
|
||||
}
|
||||
|
||||
/// `(out of memory, any other error)`, popped innermost first.
|
||||
fn pop_split(self) -> (Option<wgpu::Error>, Option<wgpu::Error>) {
|
||||
let valid = pollster::block_on(self.valid.pop());
|
||||
let oom = pollster::block_on(self.oom.pop());
|
||||
let internal = pollster::block_on(self.internal.pop());
|
||||
(oom, valid.or(internal))
|
||||
}
|
||||
|
||||
fn pop(self) -> Option<wgpu::Error> {
|
||||
let (oom, other) = self.pop_split();
|
||||
other.or(oom)
|
||||
}
|
||||
}
|
||||
|
||||
fn ms(t: Instant) -> f32 {
|
||||
t.elapsed().as_secs_f32() * 1000.0
|
||||
}
|
||||
|
||||
/// Mean and maximum per-channel difference of two premultiplied RGBA8 images, in 1/255 steps,
|
||||
|
||||
+362
-40
@@ -6,8 +6,8 @@
|
||||
//! tests print why and pass, so CI machines without a GPU stay green.
|
||||
|
||||
use super::*;
|
||||
use crate::binning::{Binned, PAINT_VEC4S, TILE, piece_cover, solid_of};
|
||||
use anicraft_doc::{ColorEffect, DisplayItem, ElementId, GradientStop, LayerId, Paint, Rgba, Stroke, sample};
|
||||
use crate::binning::{self as bn, Binned, PAINT_VEC4S, TILE, piece_cover, solid_of};
|
||||
use anicraft_doc::{BlendMode, ColorEffect, DisplayItem, ElementId, ElementKind, GradientStop, Group, LayerId, LayerKind, Paint, Rgba, Stroke, sample};
|
||||
use anicraft_geom::{Affine, FillRule, Path, Vec2};
|
||||
use anicraft_render::{paint::Premul, render};
|
||||
use std::sync::OnceLock;
|
||||
@@ -46,6 +46,26 @@ fn stops(colors: &[(f32, Rgba)]) -> Vec<GradientStop> {
|
||||
colors.iter().map(|&(offset, color)| GradientStop { offset, color }).collect()
|
||||
}
|
||||
|
||||
fn group(parent: Option<u32>, alpha: f32, blend: BlendMode) -> Group {
|
||||
Group { parent, alpha, blend, filters: Default::default(), clip: None }
|
||||
}
|
||||
|
||||
fn clipped(mut i: DisplayItem, clip: u32) -> DisplayItem {
|
||||
i.clip = Some(clip);
|
||||
i
|
||||
}
|
||||
|
||||
fn mask(path: Path, clip: u32) -> DisplayItem {
|
||||
let mut m = item(path, Paint::Solid(Rgba::new(1.0, 0.0, 1.0, 0.3)));
|
||||
m.masks = Some(clip);
|
||||
m
|
||||
}
|
||||
|
||||
fn in_group(mut i: DisplayItem, g: u32) -> DisplayItem {
|
||||
i.group = Some(g);
|
||||
i
|
||||
}
|
||||
|
||||
/// Analytic scenes: each stresses one part of the coverage or paint model.
|
||||
fn scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
let red = Rgba::new(0.9, 0.1, 0.1, 1.0);
|
||||
@@ -90,6 +110,99 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
let mut huge = item(Path::ellipse(50.0, 40.0, 300.0, 200.0), Paint::Solid(red));
|
||||
huge.color = ColorEffect { alpha: 0.5, tint: Rgba::hex(0x4cd07d), tint_amount: 0.7 };
|
||||
out.push(("off-surface", list(vec![huge]), view(100, 80, Some(Rgba::WHITE))));
|
||||
out.extend(composited_scenes());
|
||||
out
|
||||
}
|
||||
|
||||
/// Masks and groups (ADR 0029): each stresses one part of the oracle's band compositor.
|
||||
fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
let red = Rgba::new(0.9, 0.1, 0.1, 1.0);
|
||||
let blue = Rgba::new(0.1, 0.2, 0.9, 0.6);
|
||||
let green = Rgba::new(0.2, 0.7, 0.3, 0.8);
|
||||
let grad = || Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(120.0, 40.0), stops: stops(&[(0.0, red), (0.5, Rgba::new(1.0, 0.9, 0.3, 1.0)), (1.0, blue)]) };
|
||||
let mut out = Vec::new();
|
||||
// A mask: a gradient seen through a circle, an unclipped shape over it, and one under it.
|
||||
let dl = DisplayList {
|
||||
items: vec![item(Path::rect(70.0, 0.0, 50.0, 100.0), Paint::Solid(green)), clipped(item(Path::rect(0.0, 0.0, 120.0, 100.0), grad()), 0), mask(Path::ellipse(50.0, 50.0, 37.3, 33.1), 0), item(Path::rect(10.0, 60.0, 30.0, 30.0), Paint::Solid(blue))],
|
||||
clip_parents: vec![None],
|
||||
groups: Vec::new(),
|
||||
};
|
||||
out.push(("mask", dl, view(120, 100, Some(Rgba::WHITE))));
|
||||
// Mask artwork that overlaps unites (no cancelled overlap), even-odd artwork keeps its hole,
|
||||
// and a nested mask is inside its parent's; shapes switch between the clips.
|
||||
let mut ring = Path::rect(20.0, 20.0, 80.0, 70.0);
|
||||
ring.cmds.extend(Path::rect(45.0, 40.0, 30.0, 25.0).cmds);
|
||||
let mut eo = mask(ring, 0);
|
||||
eo.fill_rule = FillRule::EvenOdd;
|
||||
let mut star = mask(Path::star(60.0, 55.0, 50.0, 20.0, 6), 1);
|
||||
star.transform = Affine::rotate(0.1);
|
||||
let mut stripes = Vec::new();
|
||||
for k in 0..6 {
|
||||
let c = if k % 2 == 0 { red } else { blue };
|
||||
stripes.push(clipped(item(Path::rect(0.0, 7.0 + 17.3 * k as f32, 130.0, 9.0), Paint::Solid(c)), 1));
|
||||
stripes.push(clipped(item(Path::rect(3.0 + 21.1 * k as f32, 0.0, 6.5, 110.0), Paint::Solid(green)), if k % 3 == 0 { 0 } else { 1 }));
|
||||
}
|
||||
let mut items = stripes;
|
||||
items.extend([eo, mask(Path::ellipse(95.0, 20.0, 30.0, 18.0), 0), star]);
|
||||
out.push(("nested masks", DisplayList { items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0)))));
|
||||
// Group alpha: overlapping shapes fade as one; nested groups multiply; a group spans tiles
|
||||
// and the render bands; a top-level shape between two groups.
|
||||
let dl = DisplayList {
|
||||
items: vec![
|
||||
in_group(item(Path::rect(5.0, 5.0, 60.0, 50.0), Paint::Solid(red)), 0),
|
||||
in_group(item(Path::ellipse(55.0, 40.0, 35.0, 30.0), grad()), 0),
|
||||
in_group(item(Path::rect(30.0, 20.0, 70.0, 20.0), Paint::Solid(blue)), 1),
|
||||
in_group(item(Path::star(80.0, 70.0, 30.0, 12.0, 5), Paint::Solid(green)), 2),
|
||||
in_group(item(Path::rect(70.0, 50.0, 40.0, 40.0), Paint::Solid(Rgba::BLACK)), 1),
|
||||
item(Path::rect(0.0, 75.0, 140.0, 8.0), Paint::Solid(Rgba::new(1.0, 1.0, 0.0, 0.7))),
|
||||
in_group(item(Path::ellipse(30.0, 85.0, 25.0, 20.0), Paint::Solid(red)), 3),
|
||||
],
|
||||
clip_parents: Vec::new(),
|
||||
groups: vec![group(None, 0.5, BlendMode::Normal), group(Some(0), 0.7, BlendMode::Layer), group(Some(1), 0.4, BlendMode::Normal), group(None, 0.35, BlendMode::Normal)],
|
||||
};
|
||||
out.push(("group alpha", dl, view(140, 110, Some(Rgba::WHITE))));
|
||||
// Every blend mode, over a striped, partly transparent backdrop, at full and part alpha.
|
||||
let mut items = Vec::new();
|
||||
let mut groups = Vec::new();
|
||||
for k in 0..4 {
|
||||
items.push(item(Path::rect(0.0, k as f32 * 24.0, 14.0 * 24.0, 12.0), Paint::Solid(Rgba::new(0.2 + 0.2 * k as f32, 0.8 - 0.15 * k as f32, 0.4, 0.5 + 0.15 * k as f32))));
|
||||
}
|
||||
for (i, &m) in BlendMode::ALL.iter().enumerate() {
|
||||
let g = groups.len() as u32;
|
||||
groups.push(group(None, if i % 2 == 0 { 1.0 } else { 0.6 }, m));
|
||||
let x = i as f32 * 24.0;
|
||||
items.push(in_group(item(Path::ellipse(x + 12.0, 30.0, 11.0, 28.0), grad()), g));
|
||||
items.push(in_group(item(Path::rect(x + 2.0, 60.0, 20.0, 30.0), Paint::Solid(Rgba::new(0.9, 0.5, 0.2, 0.7))), g));
|
||||
}
|
||||
out.push(("blend modes", DisplayList { items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8)))));
|
||||
// Masks inside groups and groups inside masks, with a blend mode, on transparent.
|
||||
let dl = DisplayList {
|
||||
items: vec![
|
||||
in_group(clipped(item(Path::rect(0.0, 0.0, 100.0, 60.0), grad()), 0), 0),
|
||||
in_group(item(Path::ellipse(70.0, 40.0, 30.0, 30.0), Paint::Solid(blue)), 0),
|
||||
mask(Path::ellipse(40.0, 30.0, 32.0, 26.0), 0),
|
||||
in_group(clipped(item(Path::rect(20.0, 20.0, 80.0, 60.0), Paint::Solid(red)), 1), 1),
|
||||
in_group(clipped(item(Path::star(60.0, 50.0, 30.0, 12.0, 7), Paint::Solid(green)), 1), 2),
|
||||
mask(Path::rect(30.0, 10.0, 50.0, 70.0), 1),
|
||||
],
|
||||
clip_parents: vec![None, Some(0)],
|
||||
groups: vec![group(None, 0.8, BlendMode::Normal), group(None, 0.9, BlendMode::Multiply), group(Some(1), 0.5, BlendMode::Screen)],
|
||||
};
|
||||
out.push(("masks and groups", dl, view(110, 90, None)));
|
||||
// Malformed links, as the oracle treats them: a clip whose parent is later (empty, hides
|
||||
// what it clips), a group whose parent is later (top-level), a clip index past the list.
|
||||
let dl = DisplayList {
|
||||
items: vec![
|
||||
clipped(item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(red)), 0),
|
||||
mask(Path::rect(0.0, 0.0, 30.0, 30.0), 0),
|
||||
clipped(item(Path::rect(10.0, 10.0, 40.0, 40.0), Paint::Solid(blue)), 9),
|
||||
in_group(item(Path::rect(5.0, 20.0, 40.0, 10.0), Paint::Solid(green)), 1),
|
||||
in_group(item(Path::rect(20.0, 5.0, 10.0, 40.0), Paint::Solid(Rgba::BLACK)), 7),
|
||||
],
|
||||
clip_parents: vec![Some(1), None],
|
||||
groups: vec![group(Some(1), 0.5, BlendMode::Normal), group(Some(1), 0.5, BlendMode::Difference)],
|
||||
};
|
||||
out.push(("malformed links", dl, view(50, 50, Some(Rgba::WHITE))));
|
||||
out
|
||||
}
|
||||
|
||||
@@ -104,16 +217,53 @@ fn emulate(b: &Binned, v: &View) -> Vec<Premul> {
|
||||
let (lx, ly) = (x % TILE as usize, y % TILE as usize);
|
||||
let (start, count) = (b.index[2 * tile] as usize, b.index[2 * tile + 1] as usize);
|
||||
let mut c = bg;
|
||||
let mut stack: Vec<Premul> = Vec::new();
|
||||
let (mut mask, mut level) = (1.0f32, 0.0f32);
|
||||
for i in 0..count {
|
||||
let e = b.entries_at as usize + (start + i) * 4;
|
||||
let (op, first, n, bd) = (b.index[e] as usize, b.index[e + 1] as usize, b.index[e + 2] as usize, b.index[e + 3]);
|
||||
match b.index[e] {
|
||||
bn::OPEN => {
|
||||
assert!(stack.len() < bn::MAX_GROUP_DEPTH);
|
||||
stack.push(c);
|
||||
c = [0.0; 4];
|
||||
continue;
|
||||
}
|
||||
bn::CLOSE => {
|
||||
let below = stack.pop().unwrap();
|
||||
c = close_group(c, below, f32::from_bits(b.index[e + 1]), b.index[e + 2]);
|
||||
continue;
|
||||
}
|
||||
bn::MASK_RESET => {
|
||||
mask = 1.0;
|
||||
continue;
|
||||
}
|
||||
bn::LEVEL_BEGIN => {
|
||||
level = 0.0;
|
||||
continue;
|
||||
}
|
||||
bn::LEVEL_END => {
|
||||
mask *= level;
|
||||
continue;
|
||||
}
|
||||
k => assert_eq!(k & bn::CTRL, 0, "unknown control entry {k:x}"),
|
||||
}
|
||||
let mut wnd = if bd == binning::NONE { 0.0 } else { b.geo[bd as usize + ly / 4][ly % 4] };
|
||||
for k in 0..n {
|
||||
let s = b.geo[first + k];
|
||||
wnd += piece_cover(s, lx as f32, ly as f32);
|
||||
}
|
||||
let hd = b.ops_at as usize + op * 4;
|
||||
let cov = if b.index[hd + 1] == 0 { wnd.abs().min(1.0) } else { let t = wnd.abs() % 2.0; if t > 1.0 { 2.0 - t } else { t } };
|
||||
let mut cov = if b.index[hd + 1] == 0 { wnd.abs().min(1.0) } else { let t = wnd.abs() % 2.0; if t > 1.0 { 2.0 - t } else { t } };
|
||||
let flags = b.index[hd + 3];
|
||||
if flags & bn::ART != 0 {
|
||||
let k = cov.clamp(0.0, 1.0);
|
||||
level = level + k - level * k;
|
||||
continue;
|
||||
}
|
||||
if flags & bn::CLIPPED != 0 {
|
||||
cov *= mask;
|
||||
}
|
||||
if cov <= 1e-4 {
|
||||
continue;
|
||||
}
|
||||
@@ -135,12 +285,62 @@ fn emulate(b: &Binned, v: &View) -> Vec<Premul> {
|
||||
c[k] = s[k] * cov + c[k] * (1.0 - sa);
|
||||
}
|
||||
}
|
||||
assert!(stack.is_empty(), "every group closes");
|
||||
out[y * w + x] = c;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `fine.wgsl` › `close_group` and `blend`, on the CPU (the oracle's formulas, written again
|
||||
/// from the shader's numbering).
|
||||
fn close_group(s: Premul, below: Premul, alpha: f32, m: u32) -> Premul {
|
||||
if alpha <= 0.0 {
|
||||
return below;
|
||||
}
|
||||
if m != 0 {
|
||||
if s[3] <= 0.0 {
|
||||
return below;
|
||||
}
|
||||
let s = [s[0] * alpha, s[1] * alpha, s[2] * alpha, s[3] * alpha];
|
||||
let (sa, ba) = (s[3].clamp(0.0, 1.0), below[3].clamp(0.0, 1.0));
|
||||
if m == 11 {
|
||||
return [below[0] * sa, below[1] * sa, below[2] * sa, ba * sa];
|
||||
}
|
||||
if m == 12 {
|
||||
let k = 1.0 - sa;
|
||||
return [below[0] * k, below[1] * k, below[2] * k, ba * k];
|
||||
}
|
||||
let un = |c: f32, a: f32| if a > 1e-6 { (c / a).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let hard = |cb: f32, cs: f32| if cs <= 0.5 { cb * 2.0 * cs } else { let t = 2.0 * cs - 1.0; cb + t - cb * t };
|
||||
let f = |cb: f32, cs: f32| match m {
|
||||
1 => cb * cs,
|
||||
2 => cb + cs - cb * cs,
|
||||
3 => cb.min(cs),
|
||||
4 => cb.max(cs),
|
||||
5 => (cb - cs).abs(),
|
||||
6 => (cb + cs).min(1.0),
|
||||
7 => (cb - cs).max(0.0),
|
||||
8 => 1.0 - cb,
|
||||
9 => hard(cb, cs),
|
||||
10 => hard(cs, cb),
|
||||
_ => cs,
|
||||
};
|
||||
let mut o = [0.0; 4];
|
||||
for i in 0..3 {
|
||||
o[i] = (1.0 - ba) * s[i] + (1.0 - sa) * below[i] + sa * ba * f(un(below[i], ba), un(s[i], sa));
|
||||
}
|
||||
o[3] = sa + ba - sa * ba;
|
||||
return o;
|
||||
}
|
||||
let sa = s[3] * alpha;
|
||||
if sa <= 0.0 {
|
||||
return below;
|
||||
}
|
||||
let inv = 1.0 - sa;
|
||||
[s[0] * alpha + below[0] * inv, s[1] * alpha + below[1] * inv, s[2] * alpha + below[2] * inv, sa + below[3] * inv]
|
||||
}
|
||||
|
||||
fn f32_diff(a: &[Premul], b: &[Premul]) -> (f64, f32) {
|
||||
let mut sum = 0.0f64;
|
||||
let mut max = 0.0f32;
|
||||
@@ -172,6 +372,37 @@ fn camera_sample() -> anicraft_doc::Document {
|
||||
doc
|
||||
}
|
||||
|
||||
/// The sample with what ADR 0029 draws on the GPU, built the way artists build it: the Sun
|
||||
/// layer is a mask the Hills show through, the ball symbol multiplies at 60 % and the star
|
||||
/// symbol (itself a nested symbol) fades to half.
|
||||
fn composited_sample() -> anicraft_doc::Document {
|
||||
let mut doc = sample::demo();
|
||||
let tl = doc.timeline_mut(0);
|
||||
let sun = tl.layers.get(2).map(|l| l.id);
|
||||
for (i, layer) in tl.layers.iter_mut().enumerate() {
|
||||
let l = Arc::make_mut(layer);
|
||||
match i {
|
||||
0 | 1 => {
|
||||
for k in &mut l.keyframes {
|
||||
for e in &mut Arc::make_mut(k).elements {
|
||||
let e = Arc::make_mut(e);
|
||||
e.color.alpha = if i == 0 { 0.6 } else { 0.5 };
|
||||
if let ElementKind::Symbol { blend, .. } = &mut e.kind
|
||||
&& i == 0
|
||||
{
|
||||
*blend = BlendMode::Multiply;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
2 => l.kind = LayerKind::Mask,
|
||||
3 => l.parent = sun,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binned_coverage_matches_the_oracle_on_the_cpu() {
|
||||
let mut all = scenes();
|
||||
@@ -183,45 +414,113 @@ fn binned_coverage_matches_the_oracle_on_the_cpu() {
|
||||
for (f, s) in [(0u32, 0.5f32), (20, 0.8)] {
|
||||
all.push(("camera", anicraft_doc::evaluate(&cam, f), View::stage(&cam, s)));
|
||||
}
|
||||
let comp = composited_sample();
|
||||
for (f, s) in [(0u32, 0.4f32), (30, 0.6)] {
|
||||
all.push(("composited sample", anicraft_doc::evaluate(&comp, f), View::stage(&comp, s)));
|
||||
}
|
||||
for (name, dl, v) in all {
|
||||
let (fills, _) = plain_fills(&dl, &v).unwrap();
|
||||
let b = binning::bin(&fills, v.width, v.height);
|
||||
let (scene, _) = prepare_scene(&dl, &v).unwrap();
|
||||
let b = binning::bin(&scene, v.width, v.height).unwrap();
|
||||
let (oracle, _) = render(&dl, &v).unwrap();
|
||||
let (mean, max) = f32_diff(&emulate(&b, &v), &oracle.data);
|
||||
assert!(mean < 1e-4 && max < 2e-3, "{name}: mean {mean:e}, max {max:e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_composited_sample_really_has_masks_and_groups() {
|
||||
let comp = composited_sample();
|
||||
let dl = anicraft_doc::evaluate(&comp, 10);
|
||||
assert!(dl.items.iter().any(|i| i.masks.is_some()) && dl.items.iter().any(|i| i.clip.is_some()));
|
||||
assert!(dl.groups.iter().any(|g| g.blend == BlendMode::Multiply) && dl.groups.iter().any(|g| (g.alpha - 0.5).abs() < 1e-6));
|
||||
// ...and that they show: it differs from the plain sample.
|
||||
let v = View::stage(&comp, 0.25);
|
||||
let (a, _) = render(&dl, &v).unwrap();
|
||||
let (b, _) = render(&anicraft_doc::evaluate(&sample::demo(), 10), &v).unwrap();
|
||||
assert!(f32_diff(&a.data, &b.data).0 > 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binning_shapes_the_scene_into_tiles() {
|
||||
// One rectangle exactly covering tiles 1..3 × 1..2 of a 64 × 48 surface: its edges sit on
|
||||
// tile boundaries, so the interior tiles carry a backdrop and no pieces.
|
||||
let dl = list(vec![item(Path::rect(16.0, 16.0, 32.0, 16.0), Paint::Solid(Rgba::BLACK))]);
|
||||
let v = view(64, 48, None);
|
||||
let (fills, _) = plain_fills(&dl, &v).unwrap();
|
||||
let b = binning::bin(&fills, 64, 48);
|
||||
let bin = |dl: &DisplayList, v: &View| binning::bin(&prepare_scene(dl, v).unwrap().0, v.width, v.height).unwrap();
|
||||
let b = bin(&dl, &v);
|
||||
assert_eq!((b.tiles_x, b.tiles_y), (4, 3));
|
||||
let count = |tx: usize, ty: usize| b.index[2 * (ty * 4 + tx) + 1];
|
||||
assert_eq!((count(0, 1), count(1, 1), count(2, 1), count(3, 1)), (0, 1, 1, 0));
|
||||
assert_eq!(count(1, 0) + count(1, 2), 0, "nothing above or below");
|
||||
let count = |b: &Binned, tx: usize, ty: usize| b.index[2 * (ty * b.tiles_x as usize + tx) + 1];
|
||||
assert_eq!((count(&b, 0, 1), count(&b, 1, 1), count(&b, 2, 1), count(&b, 3, 1)), (0, 1, 1, 0));
|
||||
assert_eq!(count(&b, 1, 0) + count(&b, 1, 2), 0, "nothing above or below");
|
||||
// Odd sizes: partial tiles at the right and bottom still bin.
|
||||
let dl = list(vec![item(Path::ellipse(20.0, 10.0, 30.0, 30.0), Paint::Solid(Rgba::BLACK))]);
|
||||
let v = view(37, 21, None);
|
||||
let (fills, _) = plain_fills(&dl, &v).unwrap();
|
||||
let b = binning::bin(&fills, 37, 21);
|
||||
let b = bin(&dl, &v);
|
||||
assert_eq!((b.tiles_x, b.tiles_y), (3, 2));
|
||||
let (oracle, _) = render(&dl, &v).unwrap();
|
||||
assert!(f32_diff(&emulate(&b, &v), &oracle.data).1 < 2e-3);
|
||||
// Nothing to draw: an empty scene bins to empty tile lists.
|
||||
let b = binning::bin(&[], 40, 40);
|
||||
assert_eq!((b.entries, b.pieces), (0, 0));
|
||||
let b = bin(&list(vec![]), &view(40, 40, None));
|
||||
assert_eq!((b.entries, b.pieces, b.work), (0, 0, 0));
|
||||
assert!(b.index.iter().all(|&v| v == 0));
|
||||
// A group in one tile: open, the fill, close; a clipped fill: the clip's level first. In
|
||||
// the middle tile the mask has no artwork, so the clipped fill is left out there.
|
||||
let dl = DisplayList {
|
||||
items: vec![
|
||||
in_group(item(Path::rect(1.0, 1.0, 4.0, 4.0), Paint::Solid(Rgba::BLACK)), 0),
|
||||
clipped(item(Path::rect(0.0, 0.0, 40.0, 16.0), Paint::Solid(Rgba::BLACK)), 0),
|
||||
mask(Path::rect(2.0, 2.0, 5.0, 5.0), 0),
|
||||
mask(Path::rect(34.0, 2.0, 4.0, 4.0), 0),
|
||||
],
|
||||
clip_parents: vec![None],
|
||||
groups: vec![group(None, 0.5, BlendMode::Screen)],
|
||||
};
|
||||
let b = bin(&dl, &view(40, 16, None));
|
||||
let stream = |b: &Binned, t: usize| -> Vec<u32> {
|
||||
let (s, n) = (b.index[2 * t] as usize, b.index[2 * t + 1] as usize);
|
||||
(s..s + n).map(|i| b.index[b.entries_at as usize + 4 * i]).collect()
|
||||
};
|
||||
// (The clip coverage is per pixel, apart from the group stack: it may be computed first.)
|
||||
assert_eq!(stream(&b, 0), vec![bn::OPEN, 0, bn::MASK_RESET, bn::LEVEL_BEGIN, 2, bn::LEVEL_END, bn::CLOSE, 1]);
|
||||
assert_eq!(stream(&b, 1), Vec::<u32>::new(), "no mask artwork in the middle tile");
|
||||
assert_eq!(stream(&b, 2), vec![bn::MASK_RESET, bn::LEVEL_BEGIN, 3, bn::LEVEL_END, 1]);
|
||||
let (oracle, _) = render(&dl, &view(40, 16, None)).unwrap();
|
||||
assert!(f32_diff(&emulate(&b, &view(40, 16, None)), &oracle.data).1 < 2e-3);
|
||||
let close = (0..b.entries).map(|i| b.entries_at as usize + 4 * i).find(|&e| b.index[e] == bn::CLOSE).unwrap();
|
||||
assert_eq!((f32::from_bits(b.index[close + 1]), b.index[close + 2]), (0.5, bn::blend_code(BlendMode::Screen)));
|
||||
assert!(b.work >= b.entries as u64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() {
|
||||
let deep = |n: usize| DisplayList {
|
||||
items: vec![in_group(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1)],
|
||||
clip_parents: Vec::new(),
|
||||
groups: (0..n).map(|i| group(i.checked_sub(1).map(|p| p as u32), 0.9, BlendMode::Normal)).collect(),
|
||||
};
|
||||
let v = view(8, 8, None);
|
||||
let bin = |dl: &DisplayList| binning::bin(&prepare_scene(dl, &v).unwrap().0, 8, 8).map(|_| ());
|
||||
assert!(bin(&deep(bn::MAX_GROUP_DEPTH)).is_ok());
|
||||
assert_eq!(bin(&deep(bn::MAX_GROUP_DEPTH + 1)).err(), Some(NeedsFull::Groups));
|
||||
let masks = |n: usize| {
|
||||
let mut items: Vec<DisplayItem> = (0..n).map(|c| mask(Path::rect(0.0, 0.0, 8.0, 8.0), c as u32)).collect();
|
||||
items.push(clipped(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1));
|
||||
DisplayList { items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() }
|
||||
};
|
||||
assert!(bin(&masks(bn::MAX_CLIP_DEPTH)).is_ok());
|
||||
assert_eq!(bin(&masks(bn::MAX_CLIP_DEPTH + 1)).err(), Some(NeedsFull::Clips));
|
||||
// At the limit, still the oracle's picture.
|
||||
for dl in [deep(bn::MAX_GROUP_DEPTH), masks(bn::MAX_CLIP_DEPTH)] {
|
||||
let b = binning::bin(&prepare_scene(&dl, &v).unwrap().0, 8, 8).unwrap();
|
||||
assert!(f32_diff(&emulate(&b, &v), &render(&dl, &v).unwrap().0.data).1 < 2e-3);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degenerate_geometry_bins_without_trouble() {
|
||||
// NaN and infinite points, zero-area polygons, edges far outside the surface.
|
||||
let fills = vec![anicraft_render::Fill {
|
||||
// NaN and infinite points, zero-area polygons, edges far outside the surface; clip and
|
||||
// group indices past their tables.
|
||||
let fill = |clip, group| anicraft_render::Fill {
|
||||
polys: vec![
|
||||
vec![Vec2::new(f32::NAN, 0.0), Vec2::new(5.0, 5.0), Vec2::new(1.0, f32::INFINITY)],
|
||||
vec![Vec2::new(3.0, 3.0), Vec2::new(3.0, 3.0), Vec2::new(3.0, 3.0)],
|
||||
@@ -231,8 +530,11 @@ fn degenerate_geometry_bins_without_trouble() {
|
||||
rule: FillRule::NonZero,
|
||||
shader: anicraft_render::paint::Shader::Solid([1.0; 4]),
|
||||
bounds: anicraft_render::raster::IRect { x0: 0, y0: 0, x1: 32, y1: 32 },
|
||||
}];
|
||||
let b = binning::bin(&fills, 32, 32);
|
||||
clip,
|
||||
group,
|
||||
};
|
||||
let scene = anicraft_render::Scene { fills: vec![fill(None, None), fill(Some(7), Some(9))], clips: Vec::new(), groups: Vec::new() };
|
||||
let b = binning::bin(&scene, 32, 32).unwrap();
|
||||
assert!(b.geo.iter().flatten().all(|v| v.is_finite()));
|
||||
}
|
||||
|
||||
@@ -255,21 +557,47 @@ fn gpu() -> Option<&'static GpuRenderer> {
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// The GPU's picture against the oracle's, read back and through a texture (byte for byte
|
||||
/// the same as each other).
|
||||
fn assert_parity(g: &GpuRenderer, name: &str, dl: &DisplayList, v: &View) -> Diff {
|
||||
let f = g.render(dl, v, Output::Premul8).unwrap();
|
||||
let (oracle, st) = render(dl, v).unwrap();
|
||||
let d = compare_premul8(&f.premul8, &oracle.to_premul_rgba8()).unwrap();
|
||||
assert!(d.mean <= MEAN_TARGET / 16.0 && d.max <= 2, "{name}: {d:?}");
|
||||
assert_eq!((f.stats.drawn, f.stats.culled), (st.drawn, st.culled), "{name}");
|
||||
let t = g.render_texture(dl, v).unwrap();
|
||||
assert_eq!((t.width, t.height), (v.width, v.height));
|
||||
assert!(g.read_texture(&t).unwrap() == f.premul8, "{name}: the texture holds the read-back bytes");
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_matches_the_oracle_on_analytic_scenes() {
|
||||
let Some(g) = gpu() else { return };
|
||||
for (name, dl, v) in scenes() {
|
||||
let f = g.render(&dl, &v, Output::Premul8).unwrap();
|
||||
let (oracle, _) = render(&dl, &v).unwrap();
|
||||
let d = compare_premul8(&f.premul8, &oracle.to_premul_rgba8()).unwrap();
|
||||
assert!(d.mean <= MEAN_TARGET / 16.0 && d.max <= 2, "{name}: {d:?}");
|
||||
assert_parity(g, name, &dl, &v);
|
||||
// Float output agrees closely too.
|
||||
let ff = g.render(&dl, &v, Output::Float).unwrap();
|
||||
let (oracle, _) = render(&dl, &v).unwrap();
|
||||
let (mean, max) = f32_diff(&ff.pixmap.unwrap().data, &oracle.data);
|
||||
assert!(mean < 1e-4 && max < 4e-3, "{name} (f32): mean {mean:e}, max {max:e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_matches_the_oracle_on_masks_groups_and_blend_modes() {
|
||||
let Some(g) = gpu() else { return };
|
||||
for (name, dl, v) in composited_scenes() {
|
||||
let d = assert_parity(g, name, &dl, &v);
|
||||
eprintln!("{name}: mean {:.5} / max {} / {} of {} px differ", d.mean, d.max, d.differing, d.pixels);
|
||||
}
|
||||
let comp = composited_sample();
|
||||
for (f, s) in [(0u32, 1.0f32), (7, 0.5), (24, 1.5), (40, 0.37)] {
|
||||
let d = assert_parity(g, "composited sample", &anicraft_doc::evaluate(&comp, f), &View::stage(&comp, s));
|
||||
eprintln!("composited sample {f} at {s}: mean {:.5} / max {} / {} of {} px differ", d.mean, d.max, d.differing, d.pixels);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_matches_the_oracle_on_the_sample_scene() {
|
||||
let Some(g) = gpu() else { return };
|
||||
@@ -277,14 +605,7 @@ fn gpu_matches_the_oracle_on_the_sample_scene() {
|
||||
let cam = camera_sample();
|
||||
let frames = doc.frame_count();
|
||||
for (d, f, s) in [(&doc, 0u32, 1.0f32), (&doc, 7, 0.5), (&doc, 13, 0.37), (&doc, frames / 2, 1.5), (&doc, frames.saturating_sub(1), 0.25), (&cam, 0, 1.0), (&cam, 20, 0.5)] {
|
||||
let doc = d;
|
||||
let dl = anicraft_doc::evaluate(doc, f);
|
||||
let v = View::stage(doc, s);
|
||||
let gpu = g.render(&dl, &v, Output::Premul8).unwrap();
|
||||
let (oracle, st) = render(&dl, &v).unwrap();
|
||||
let d = compare_premul8(&gpu.premul8, &oracle.to_premul_rgba8()).unwrap();
|
||||
assert!(d.mean <= MEAN_TARGET / 16.0 && d.max <= 2, "frame {f} at {s}: {d:?}");
|
||||
assert_eq!((gpu.stats.drawn, gpu.stats.culled), (st.drawn, st.culled));
|
||||
assert_parity(g, &format!("frame {f} at {s}"), &anicraft_doc::evaluate(d, f), &View::stage(d, s));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,22 +616,23 @@ fn gpu_matches_the_oracle_on_many_shapes_and_tiles() {
|
||||
let dl = anicraft_doc::evaluate(&doc, 5);
|
||||
// A whole frame and an offset, zoomed tile like the stage asks for.
|
||||
for v in [View::stage(&doc, 0.5), View { transform: Affine::translate(-512.0, -256.0).mul(&Affine::scale(1.7, 1.7)), width: 512, height: 512, background: Some(doc.stage.background) }] {
|
||||
let gpu = g.render(&dl, &v, Output::Premul8).unwrap();
|
||||
let (oracle, _) = render(&dl, &v).unwrap();
|
||||
let d = compare_premul8(&gpu.premul8, &oracle.to_premul_rgba8()).unwrap();
|
||||
assert!(d.mean <= MEAN_TARGET / 16.0 && d.max <= 2, "{d:?}");
|
||||
assert_parity(g, "stress", &dl, &v);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() {
|
||||
let Some(g) = gpu() else { return };
|
||||
let mut clipped = item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK));
|
||||
clipped.clip = Some(0);
|
||||
let dl = DisplayList { items: vec![clipped], clip_parents: vec![None], groups: Vec::new() };
|
||||
assert!(matches!(g.render(&dl, &view(8, 8, None), Output::Premul8), Err(GpuError::NeedsFull(NeedsFull::Clips))));
|
||||
let mut filtered = in_group(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), 0);
|
||||
filtered.color.alpha = 0.5;
|
||||
let mut grp = group(None, 1.0, BlendMode::Normal);
|
||||
grp.filters = Arc::from(vec![anicraft_doc::Filter::Blur { blur_x: 4.0, blur_y: 4.0, quality: 1 }]);
|
||||
let dl = DisplayList { items: vec![filtered], clip_parents: Vec::new(), groups: vec![grp] };
|
||||
assert!(matches!(g.render(&dl, &view(8, 8, None), Output::Premul8), Err(GpuError::NeedsFull(NeedsFull::Filters))));
|
||||
assert!(matches!(g.render_texture(&dl, &view(8, 8, None)), Err(GpuError::NeedsFull(NeedsFull::Filters))));
|
||||
assert!(matches!(g.render(&list(vec![]), &view(0, 8, None), Output::Premul8), Err(GpuError::TooLarge(_))));
|
||||
assert!(matches!(g.render(&list(vec![]), &view(100_000, 100_000, None), Output::Premul8), Err(GpuError::TooLarge(_))));
|
||||
assert!(matches!(g.render_texture(&list(vec![]), &view(0, 8, None)), Err(GpuError::TooLarge(_))));
|
||||
// An empty list is just the background; and the device is still fine afterwards.
|
||||
let f = g.render(&list(vec![]), &view(20, 3, Some(Rgba::new(0.0, 1.0, 0.0, 1.0))), Output::Premul8).unwrap();
|
||||
assert!(f.premul8.as_chunks::<4>().0.iter().all(|p| *p == [0, 255, 0, 255]));
|
||||
@@ -320,11 +642,11 @@ fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() {
|
||||
#[test]
|
||||
fn gpu_renders_from_many_threads_at_once() {
|
||||
let Some(g) = gpu() else { return };
|
||||
let doc = sample::demo();
|
||||
let doc = composited_sample();
|
||||
let dl = anicraft_doc::evaluate(&doc, 9);
|
||||
let v = View::stage(&doc, 0.25);
|
||||
let first = g.render(&dl, &v, Output::Premul8).unwrap().premul8;
|
||||
use rayon::prelude::*;
|
||||
let all: Vec<Vec<u8>> = (0..8).into_par_iter().map(|_| g.render(&dl, &v, Output::Premul8).unwrap().premul8).collect();
|
||||
let all: Vec<Vec<u8>> = (0..8).into_par_iter().map(|i| if i % 2 == 0 { g.render(&dl, &v, Output::Premul8).unwrap().premul8 } else { g.read_texture(&g.render_texture(&dl, &v).unwrap()).unwrap() }).collect();
|
||||
assert!(all.iter().all(|a| *a == first), "deterministic under concurrency");
|
||||
}
|
||||
+118
-34
@@ -245,13 +245,16 @@ pub fn render(dl: &DisplayList, view: &View) -> Result<(Pixmap, RenderStats), Re
|
||||
Ok((pm, stats))
|
||||
}
|
||||
|
||||
/// Why a display list needs the full renderer rather than plain fills (see [`plain_fills`]).
|
||||
/// Why a display list needs the full renderer rather than a prepared [`Scene`] (see
|
||||
/// [`prepare_scene`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum NeedsFull {
|
||||
/// Mask layers: items drawn inside a clip, or mask artwork.
|
||||
/// Mask layers nested deeper than the other renderer handles.
|
||||
Clips,
|
||||
/// Group opacity, blend modes or filters (symbol instances composited on their own).
|
||||
/// Symbol instances nested deeper than the other renderer handles.
|
||||
Groups,
|
||||
/// Filters (blurs, shadows, glows, bevels, colour adjustments) on a symbol instance.
|
||||
Filters,
|
||||
/// Bitmap fills.
|
||||
Bitmaps,
|
||||
}
|
||||
@@ -259,8 +262,9 @@ pub enum NeedsFull {
|
||||
impl std::fmt::Display for NeedsFull {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
NeedsFull::Clips => "masks",
|
||||
NeedsFull::Groups => "group opacity, blend modes or filters",
|
||||
NeedsFull::Clips => "deeply nested masks",
|
||||
NeedsFull::Groups => "deeply nested symbols",
|
||||
NeedsFull::Filters => "filters",
|
||||
NeedsFull::Bitmaps => "bitmap fills",
|
||||
})
|
||||
}
|
||||
@@ -268,35 +272,69 @@ impl std::fmt::Display for NeedsFull {
|
||||
|
||||
/// One fill operation in surface pixels, exactly as this renderer prepares it: flattened at
|
||||
/// [`TOLERANCE`], strokes already outlined by the stroker, the paint's shader (with its gradient
|
||||
/// table) built, and pixel bounds clamped to the surface. Drawing every fill in order, with
|
||||
/// analytic coverage, the fill rule and src-over, reproduces [`render`] for a display list that
|
||||
/// [`plain_fills`] accepts. Other renderers (the GPU stage, ADR 0019) start from these, so the
|
||||
/// geometry and the colours are the oracle's own.
|
||||
/// table) built, and pixel bounds clamped to the surface (and to its clip's bounds). Other
|
||||
/// renderers (the GPU stage, ADR 0019 and 0029) start from these, so the geometry and the
|
||||
/// colours are the oracle's own.
|
||||
pub struct Fill {
|
||||
pub polys: Vec<Vec<Vec2>>,
|
||||
pub rule: FillRule,
|
||||
pub shader: Shader,
|
||||
pub bounds: IRect,
|
||||
/// Drawn only inside this clip ([`Scene::clips`]): coverage times the clip's coverage.
|
||||
pub clip: Option<u32>,
|
||||
/// Composited inside this group ([`Scene::groups`]) and the groups around it.
|
||||
pub group: Option<u32>,
|
||||
}
|
||||
|
||||
/// The display list as plain fills, in drawing order, with the same culling and statistics as
|
||||
/// [`render`]; or why it needs the full renderer (masks, groups, bitmaps).
|
||||
pub fn plain_fills(dl: &DisplayList, view: &View) -> Result<(Vec<Fill>, RenderStats), NeedsFull> {
|
||||
/// A clip (a mask layer's area) as [`render`] composites it.
|
||||
pub struct ClipLayer {
|
||||
/// The clip this one is inside (always an earlier one; a malformed link is already `None`
|
||||
/// and its bounds empty, as [`render`] treats it).
|
||||
pub parent: Option<u32>,
|
||||
/// The mask artwork: solid fill areas whose coverages unite (`a + b − ab`).
|
||||
pub art: Vec<Fill>,
|
||||
/// Where the clip, and so anything drawn inside it, can be non-zero.
|
||||
pub bounds: IRect,
|
||||
}
|
||||
|
||||
/// A group (a symbol instance composited on its own) as [`render`] composites it.
|
||||
pub struct GroupLayer {
|
||||
/// The groups it is in, outermost first, ending with itself.
|
||||
pub chain: Vec<u32>,
|
||||
/// Opacity, already sanitized as [`render`] uses it (finite, `0..=1`).
|
||||
pub alpha: f32,
|
||||
pub blend: BlendMode,
|
||||
}
|
||||
|
||||
/// A display list prepared exactly as [`render`] prepares it, for another renderer: the fills
|
||||
/// in drawing order, with the clips and groups they are drawn in. Compositing it per pixel as
|
||||
/// [`render`]'s band compositor does reproduces [`render`]: each fill's analytic coverage under
|
||||
/// its fill rule, times its clip's coverage (the union of the clip's artwork, times its parent
|
||||
/// clip's), src-over into the innermost open group; a group opens (transparent) when the first
|
||||
/// of its fills draws and blends into what is below at its alpha and in its blend mode
|
||||
/// ([`blend`]) when its run of fills ends.
|
||||
pub struct Scene {
|
||||
pub fills: Vec<Fill>,
|
||||
pub clips: Vec<ClipLayer>,
|
||||
pub groups: Vec<GroupLayer>,
|
||||
}
|
||||
|
||||
/// The display list as a [`Scene`], with the same culling and statistics as [`render`]; or why
|
||||
/// it needs the full renderer (filters, bitmaps).
|
||||
pub fn prepare_scene(dl: &DisplayList, view: &View) -> Result<(Scene, RenderStats), NeedsFull> {
|
||||
if dl.groups.iter().any(|g| !g.filters.is_empty()) {
|
||||
return Err(NeedsFull::Filters);
|
||||
}
|
||||
for it in &dl.items {
|
||||
if it.clip.is_some() || it.masks.is_some() {
|
||||
return Err(NeedsFull::Clips);
|
||||
}
|
||||
if it.group.is_some() {
|
||||
return Err(NeedsFull::Groups);
|
||||
}
|
||||
if !it.guide && it.outline.is_none() && matches!(it.fill, Some(Paint::Bitmap { .. })) {
|
||||
if !it.guide && it.outline.is_none() && it.masks.is_none() && matches!(it.fill, Some(Paint::Bitmap { .. })) {
|
||||
return Err(NeedsFull::Bitmaps);
|
||||
}
|
||||
}
|
||||
let surface = IRect { x0: 0, y0: 0, x1: view.width as i32, y1: view.height as i32 };
|
||||
let prepared: Vec<Vec<Prepared>> = dl.items.par_iter().map(|item| prepare(item, &view.transform, surface)).collect();
|
||||
let mut stats = RenderStats { items: dl.items.len(), ..Default::default() };
|
||||
let mut out = Vec::with_capacity(prepared.len());
|
||||
let mut ops: Vec<Prepared> = Vec::with_capacity(prepared.len());
|
||||
let mut mask_ops: Vec<Prepared> = Vec::new();
|
||||
for p in prepared {
|
||||
if p.is_empty() {
|
||||
stats.culled += 1;
|
||||
@@ -305,13 +343,32 @@ pub fn plain_fills(dl: &DisplayList, view: &View) -> Result<(Vec<Fill>, RenderSt
|
||||
if matches!(op.shader, Shader::Bitmap { .. } | Shader::Image { .. }) {
|
||||
return Err(NeedsFull::Bitmaps);
|
||||
}
|
||||
stats.edges += op.polys.iter().map(Vec::len).sum::<usize>();
|
||||
stats.pixels_touched += (op.bounds.width() * op.bounds.height()) as u64;
|
||||
out.push(Fill { polys: op.polys, rule: op.rule, shader: op.shader, bounds: op.bounds });
|
||||
if op.masks.is_some() { mask_ops.push(op) } else { ops.push(op) }
|
||||
}
|
||||
}
|
||||
stats.drawn = out.len();
|
||||
Ok((out, stats))
|
||||
// The same clips, bounds and culling of clipped fills as `render`.
|
||||
let clips = Clips::new(&dl.clip_parents, mask_ops);
|
||||
ops.retain_mut(|op| {
|
||||
let Some(c) = op.clip else { return true };
|
||||
op.bounds = op.bounds.intersect(&clips.bounds(c));
|
||||
!op.bounds.is_empty()
|
||||
});
|
||||
let fill = |op: Prepared| Fill { polys: op.polys, rule: op.rule, shader: op.shader, bounds: op.bounds, clip: op.clip, group: op.group };
|
||||
let mut fills = Vec::with_capacity(ops.len());
|
||||
for op in ops {
|
||||
stats.edges += op.polys.iter().map(Vec::len).sum::<usize>();
|
||||
stats.pixels_touched += (op.bounds.width() * op.bounds.height()) as u64;
|
||||
fills.push(fill(op));
|
||||
}
|
||||
stats.drawn = fills.len();
|
||||
let Clips { parents, art, bounds } = clips;
|
||||
let clips = parents.into_iter().zip(art).zip(bounds).map(|((parent, art), bounds)| ClipLayer { parent, art: art.into_iter().map(fill).collect(), bounds }).collect();
|
||||
let groups = group_chains(&dl.groups)
|
||||
.into_iter()
|
||||
.zip(&dl.groups)
|
||||
.map(|(chain, g)| GroupLayer { chain, alpha: if g.alpha.is_finite() { g.alpha.clamp(0.0, 1.0) } else { 1.0 }, blend: g.blend })
|
||||
.collect();
|
||||
Ok((Scene { fills, clips, groups }, stats))
|
||||
}
|
||||
|
||||
/// A run of items inside a filtered group that has no filtered group around it.
|
||||
@@ -865,27 +922,54 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_fills_match_the_renderers_preparation_and_name_what_needs_more() {
|
||||
fn prepared_scenes_match_the_renderers_preparation_and_name_what_needs_more() {
|
||||
// A filled, stroked square and an off-screen circle: fill then stroke, one culled.
|
||||
let mut sq = item(Path::rect(2.0, 2.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK));
|
||||
sq.stroke = Some(anicraft_doc::Stroke { color: Rgba::WHITE, width: 2.0, profile: None });
|
||||
let off = item(Path::ellipse(500.0, 500.0, 10.0, 10.0), Paint::Solid(Rgba::BLACK));
|
||||
let dl = list(vec![sq.clone(), off]);
|
||||
let (fills, st) = plain_fills(&dl, &view(16, 16)).unwrap();
|
||||
let (scene, st) = prepare_scene(&dl, &view(16, 16)).unwrap();
|
||||
let (_, rst) = render(&dl, &view(16, 16)).unwrap();
|
||||
let fills = &scene.fills;
|
||||
assert_eq!(fills.len(), 2);
|
||||
assert_eq!((st.drawn, st.culled, st.edges), (rst.drawn, rst.culled, rst.edges));
|
||||
assert!(fills[0].shader.is_solid() == Some([0.0, 0.0, 0.0, 1.0]) && fills[1].shader.is_solid() == Some([1.0; 4]));
|
||||
assert!(fills.iter().all(|f| f.bounds.x0 >= 0 && f.bounds.x1 <= 16));
|
||||
// Masks, groups and bitmaps need the full renderer.
|
||||
assert!(fills.iter().all(|f| f.bounds.x0 >= 0 && f.bounds.x1 <= 16 && f.clip.is_none() && f.group.is_none()));
|
||||
// Clips: the mask artwork is the clip's, not a fill; a clipped fill is cut to the
|
||||
// clip's bounds; a nested clip's bounds are inside its parent's; a clip whose parent
|
||||
// link is bad is empty, and what it clips is culled, as `render` does.
|
||||
let mut clipped = sq.clone();
|
||||
clipped.clip = Some(0);
|
||||
assert_eq!(plain_fills(&list(vec![clipped]), &view(16, 16)).err(), Some(NeedsFull::Clips));
|
||||
clipped.stroke = None;
|
||||
clipped.clip = Some(1);
|
||||
let mut outer = item(Path::rect(0.0, 0.0, 6.0, 16.0), Paint::Solid(Rgba::WHITE));
|
||||
outer.masks = Some(0);
|
||||
let mut inner = item(Path::rect(4.0, 0.0, 12.0, 16.0), Paint::Solid(Rgba::WHITE));
|
||||
inner.masks = Some(1);
|
||||
let mut lost = clipped.clone();
|
||||
lost.clip = Some(2);
|
||||
let dl = DisplayList { items: vec![clipped, outer, inner, lost], clip_parents: vec![None, Some(0), Some(9)], groups: Vec::new() };
|
||||
let (scene, st) = prepare_scene(&dl, &view(16, 16)).unwrap();
|
||||
let (_, rst) = render(&dl, &view(16, 16)).unwrap();
|
||||
assert_eq!((st.drawn, st.edges, st.pixels_touched), (rst.drawn, rst.edges, rst.pixels_touched));
|
||||
assert_eq!(scene.fills.len(), 1);
|
||||
assert_eq!((scene.fills[0].clip, scene.fills[0].bounds), (Some(1), raster::IRect { x0: 4, y0: 2, x1: 6, y1: 10 }));
|
||||
assert_eq!(scene.clips.len(), 3);
|
||||
assert_eq!((scene.clips[1].parent, scene.clips[1].art.len(), scene.clips[1].bounds), (Some(0), 1, raster::IRect { x0: 4, y0: 0, x1: 6, y1: 16 }));
|
||||
assert!(scene.clips[2].parent.is_none() && scene.clips[2].bounds.is_empty());
|
||||
// Groups: chains outermost first, alpha sanitized.
|
||||
let mut grouped = sq.clone();
|
||||
grouped.group = Some(0);
|
||||
assert_eq!(plain_fills(&list(vec![grouped]), &view(16, 16)).err(), Some(NeedsFull::Groups));
|
||||
grouped.group = Some(1);
|
||||
let g = |parent, alpha| anicraft_doc::Group { parent, alpha, blend: BlendMode::Multiply, filters: Default::default(), clip: None };
|
||||
let dl = DisplayList { items: vec![grouped], clip_parents: vec![], groups: vec![g(None, 2.0), g(Some(0), f32::NAN)] };
|
||||
let (scene, _) = prepare_scene(&dl, &view(16, 16)).unwrap();
|
||||
assert!(scene.fills.iter().all(|f| f.group == Some(1)));
|
||||
assert_eq!((scene.groups[1].chain.clone(), scene.groups[0].alpha, scene.groups[1].alpha, scene.groups[1].blend), (vec![0, 1], 1.0, 1.0, BlendMode::Multiply));
|
||||
// Filters and bitmaps need the full renderer.
|
||||
let mut filtered = dl.clone();
|
||||
filtered.groups[0].filters = std::sync::Arc::from(vec![anicraft_doc::Filter::Blur { blur_x: 4.0, blur_y: 4.0, quality: 1 }]);
|
||||
assert_eq!(prepare_scene(&filtered, &view(16, 16)).err(), Some(NeedsFull::Filters));
|
||||
let bm = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine::IDENTITY });
|
||||
assert_eq!(plain_fills(&list(vec![bm]), &view(16, 16)).err(), Some(NeedsFull::Bitmaps));
|
||||
assert_eq!(prepare_scene(&list(vec![bm]), &view(16, 16)).err(), Some(NeedsFull::Bitmaps));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# ADR 0019: GPU stage renderer (first slice)
|
||||
|
||||
* Status: accepted (2026-11-09)
|
||||
* Status: accepted (2026-11-09); extended by ADR 0029 (no readback, masks and groups on the GPU)
|
||||
* Relates to: roadmap M3, ADR 0002 (render pipeline), ADR 0007 (tiled stage), AGENTS.md rule 4
|
||||
(the CPU renderer is the oracle)
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
# ADR 0029: GPU stage, second slice: no readback, masks and groups on the GPU
|
||||
|
||||
* Status: accepted (2026-11-09)
|
||||
* Relates to: roadmap M3, ADR 0019 (GPU stage, first slice), ADR 0007 (tiled stage), ADR 0010
|
||||
(mask layers), AGENTS.md rule 4 (the CPU renderer is the oracle)
|
||||
|
||||
## Context
|
||||
|
||||
The first slice (ADR 0019) drew plain fills on a headless wgpu device of its own and read
|
||||
every stage tile back to the CPU, where the shell uploaded it to egui again. Masks, group
|
||||
opacity, blend modes, filters and bitmaps sent the whole tile to the CPU. Measured: the 33 MB
|
||||
readback was most of the GPU's share at 4K, and any document with a mask layer or a faded
|
||||
symbol (most real ones) never reached the GPU at all.
|
||||
|
||||
The roadmap's M3 exit criteria: parity ≤ 1/255 mean error, 4K at 60 fps for 1,000 shapes,
|
||||
then the GPU as the default stage.
|
||||
|
||||
## Decision
|
||||
|
||||
### 1. Draw into the window's textures (no readback)
|
||||
|
||||
* **Share eframe's device.** `App::new` hands `CreationContext::wgpu_render_state` to the GPU
|
||||
stage; `GpuRenderer::shared(adapter, device, queue)` builds the pipelines on the window's
|
||||
device and checks it with the startup self-test (a known render read back, and through a
|
||||
texture). `render_texture` draws each stage tile into a fresh `Rgba8Unorm` storage texture
|
||||
(a second entry point, `main_texture`, writes exactly `k / 255`, so the texture holds the
|
||||
same bytes as `Pixmap::to_premul_rgba8`), submits, and returns without waiting: egui's own
|
||||
submission comes later on the same queue, so the window always samples a finished tile.
|
||||
* **The engine stays GPU-free.** A `Rasterizer` returns `Raster::Premul8(bytes)` or
|
||||
`Raster::Native { image, width, height }`, where `image` is an opaque
|
||||
`Arc<dyn Any + Send + Sync>`; the render service caches either (GPU pictures under their own
|
||||
384 MB budget, counted at 4 bytes a pixel) and only the shell, which installed the
|
||||
rasterizer, downcasts it to `anicraft_gpu::GpuTexture` and registers it with
|
||||
`egui_wgpu::Renderer::register_native_texture`. Evicting a stage tile frees the registration.
|
||||
* **Fallbacks, in order.** The window's device (direct) → a headless device of our own with
|
||||
readback (when the window runs on OpenGL, or its device lacks compute, storage textures or
|
||||
the limits) → the CPU oracle (no usable GPU, a device error, or content the GPU doesn't
|
||||
draw). Preferences › Stage says which ("straight into the window" or "copied to the window").
|
||||
|
||||
**The trade against ADR 0019's isolation.** ADR 0019 owned its device so that a GPU-stage
|
||||
failure could never touch the window. Sharing gives that up in part, deliberately:
|
||||
|
||||
| Risk on the shared device | What we do |
|
||||
|---|---|
|
||||
| A validation or internal error reaching the window's uncaptured-error handler (wgpu's default panics) | Every call the renderer makes is inside its own **thread-local** error scopes (validation, out-of-memory, internal) and `catch_unwind`; we install nothing on the window's device. A device error stops the GPU stage for the session (the CPU draws, Preferences says why); out of memory only fails that tile. |
|
||||
| A long dispatch tripping the driver's watchdog (a TDR resets the whole adapter) | A per-dispatch work bound (`MAX_WORK`, pieces plus entries over tiles, about 30× the 10k-shape 4K frame); beyond it the CPU draws. A TDR resets every device on the adapter anyway, so a private device never protected against this. |
|
||||
| Running out of graphics memory | The GPU picture cache has its own budget; the stage keeps at most 192 tile textures. |
|
||||
| Device loss | The window's device lost means the window is gone too; the headless fallback keeps its device-lost callback. |
|
||||
|
||||
What isolation bought in ADR 0019 (working when the window is on OpenGL, tests without a
|
||||
window) is kept by the headless fallback, which is the first slice's path unchanged.
|
||||
|
||||
### 2. Masks and groups on the GPU
|
||||
|
||||
* **Same input as the oracle.** `render::prepare_scene` (replacing `plain_fills`) returns the
|
||||
fills as `render` prepares them, now with each fill's clip and group, the clips (artwork as
|
||||
solid fills, cleaned parent links, bounds; clipped fills already cut to their clip's bounds
|
||||
and culled, as `render` does) and the groups (chains outermost first, alpha sanitized, blend
|
||||
mode). Only filters and bitmaps answer `NeedsFull`.
|
||||
* **Control entries in the tile streams.** The binning emits, per tile and in drawing order:
|
||||
before a clipped fill whose clip isn't the one computed last, `MASK_RESET` and per level of
|
||||
the clip chain `LEVEL_BEGIN`, the level's artwork entries in this tile, `LEVEL_END`; before
|
||||
a fill, `CLOSE` for each open group not in its chain and `OPEN` for each new one; `CLOSE`
|
||||
for the rest at the end. A clipped fill whose clip has a level with no artwork in the tile
|
||||
is left out there (its coverage would be 0).
|
||||
* **The shader mirrors the band compositor per pixel.** Artwork coverage unites into the
|
||||
level (`a + k − ak`), levels multiply into the clip coverage, a clipped fill's coverage is
|
||||
multiplied by it before the oracle's `> 1e-4` cut-off. `OPEN` pushes the colour on a
|
||||
per-pixel stack (8 deep) and continues on transparent; `CLOSE` composites the group into the
|
||||
colour below exactly as `close_group` does: src-over at the group's alpha for Normal and
|
||||
Layer, otherwise the oracle's `blend` (the W3C separable formulas, plus Alpha and Erase).
|
||||
**All 14 blend modes are on the GPU**; none falls back.
|
||||
* **Limits.** Groups nested deeper than 8 or clip chains longer than 16 go to the CPU (as
|
||||
`NeedsFull::Groups` / `NeedsFull::Clips`). The oracle decides group runs per 32-row band
|
||||
and the GPU per 16 × 16 tile; they agree whenever a group's items are contiguous in the
|
||||
display list, which is how `evaluate` emits every instance (an interleaved list, which
|
||||
nothing produces, could split a group differently on the two).
|
||||
|
||||
### 3. Binning stays on the CPU, for now
|
||||
|
||||
Measured (below), binning is the largest single term of a whole 10k-shape frame (4.7 ms at
|
||||
1080p, 7.5–9.6 ms at 4K), but the stage never draws whole frames: it draws 512 px tiles in
|
||||
parallel, which spreads preparation and binning over every core, and at 4K the 10k-shape
|
||||
frame already takes 10.2 ms that way, inside a 60 fps frame. A GPU binner (Vello-style coarse
|
||||
rasterization with prefix sums) only pays off together with flattening and stroking on the GPU
|
||||
(preparation is the other 3 ms), and those would have to match the oracle's flattening and
|
||||
stroker to keep parity. Not yet; revisit at 50k+ shapes or when 8K stages matter.
|
||||
|
||||
## Measured (2026-11-09, release, RTX 5090 over Vulkan, 32 threads)
|
||||
|
||||
`cargo run --release -p anicraft-gpu --example gpu_bench`. *Read-back* is the first slice's
|
||||
whole call; *direct* is what the calling thread spends with `render_texture` (prepare + bin +
|
||||
upload and submit); *tiled* is the stage's way, 512 px tiles in parallel, until the GPU has
|
||||
finished. Parity is the direct path's texture against the oracle.
|
||||
|
||||
| Scene | Size | CPU oracle | Read-back | Direct | Tiled (stage) | Parity (mean / max, 1/255) |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Stress, 50 × 200 (≈10k shapes) | 1920×1080 | 10.6 ms | 13.4 ms | 9.4–10.4 ms | 8.7 ms | < 0.0001 / 1 |
|
||||
| Stress, 50 × 200 | 3840×2160 | 25.8–28.1 ms | 23.2 ms | 16.8–18.7 ms | **10.2 ms** | < 0.0001 / 1 |
|
||||
| 1,000 shapes | 1920×1080 | 4.4–5.0 ms | 2.9–3.0 ms | 1.1–1.2 ms | 1.8 ms | < 0.0001 / 1 |
|
||||
| 1,000 shapes | 3840×2160 | 16.2–19.6 ms | 8.4–8.5 ms | **2.1–2.4 ms** | 4.8 ms | < 0.0001 / 1 |
|
||||
| Masked stress (half the shapes masks) | 1920×1080 | 25.4–26.2 ms | 10.7 ms | 8.7–9.4 ms | 6.6 ms | < 0.0001 / 1 |
|
||||
| Masked stress | 3840×2160 | 74.8–80.0 ms | 20.5–21.8 ms | 14.6–15.3 ms | 10.9 ms | < 0.0001 / 1 |
|
||||
| Sample with masks and faded symbols | 3840×2160 | 19.1–19.9 ms | 8.3–8.9 ms | 2.1–2.6 ms | 4.6 ms | < 0.0001 / 1 |
|
||||
|
||||
Parity tests (`crates/gpu/src/tests.rs`, every scene read back and through a texture, both
|
||||
byte-identical): masks, nested masks with union and even-odd artwork, group alpha (nested,
|
||||
across tiles and bands), all 14 blend modes at full and part alpha over a translucent
|
||||
backdrop, masks inside groups and groups inside masks, malformed links, and the sample built
|
||||
the way artists do it (a mask layer, faded and multiplied symbols): max 1/255, mean ≤ 0.0011/255;
|
||||
six of the ten new scenes and frames are byte-identical to the oracle.
|
||||
|
||||
## Recommendation: GPU as the default stage
|
||||
|
||||
**Not yet; next.** Parity (max 1/255) and speed (4K at 60 fps for 1,000 and for 10,000
|
||||
shapes, 2–8× the CPU at 4K, 7× on masked scenes) now meet the exit criteria. What is still
|
||||
missing before it should be the default:
|
||||
|
||||
1. **Bitmaps and filters** on the GPU (textures with the oracle's bilinear sampling; compute
|
||||
blurs): today any frame with a bitmap fill or a filtered symbol draws on the CPU, and
|
||||
imported Animate documents often have both.
|
||||
2. **Breadth of hardware**: verified on one NVIDIA card over Vulkan. It needs DX12, Metal and
|
||||
an integrated GPU, and a GPU runner (or a software adapter) in CI, since CI skips the GPU
|
||||
tests today.
|
||||
3. Then flip the preference's default (keeping the `gpu-stage` build feature until it is
|
||||
compiled in by default) and keep the oracle for exports and as the reference.
|
||||
|
||||
## Consequences
|
||||
|
||||
* `render::plain_fills` is gone; `prepare_scene` is the one hand-off to other renderers.
|
||||
* `Raster` and `NativeImage` in the render service: a future renderer (or a GPU export) plugs
|
||||
in the same way.
|
||||
* Smaller scenes lose a little in the tiled stage against one whole-frame call (per-tile
|
||||
set-up: 1.8 vs 1.1 ms at 1080p); buffer reuse across tiles is the next optimization.
|
||||
+12
-6
@@ -166,12 +166,18 @@ DisplayList ──► for each item:
|
||||
rasterizes 32-row bands in parallel, each compositing all ops that touch it, in order.
|
||||
Output is bit-identical to serial. Numbers are in [performance.md](performance.md).
|
||||
|
||||
**GPU stage** ([ADR 0019](adr/0019-gpu-stage.md), behind the shell's `gpu-stage` feature):
|
||||
`render::plain_fills` hands the oracle's own prepared fills to `anicraft-gpu`, which bins edge
|
||||
pieces into 16 × 16 tiles with per-row backdrops (CPU, parallel) and computes each pixel's
|
||||
exact area coverage and src-over in one compute pass. Display lists with masks, groups or
|
||||
bitmaps are drawn by the oracle instead. The engine's `RenderService` takes any `Rasterizer`
|
||||
and falls back to the oracle per job, so the engine itself never depends on the GPU.
|
||||
**GPU stage** ([ADR 0019](adr/0019-gpu-stage.md), [ADR 0029](adr/0029-gpu-stage-direct-masks-groups.md),
|
||||
behind the shell's `gpu-stage` feature): `render::prepare_scene` hands the oracle's own
|
||||
prepared fills, with their clips and groups, to `anicraft-gpu`, which bins edge pieces into
|
||||
16 × 16 tiles with per-row backdrops (CPU, parallel) and writes each tile's stream of entries
|
||||
in drawing order, with clip-coverage and group open/close entries. One compute pass computes
|
||||
each pixel's exact area coverage and composites it as the oracle's band compositor does (clip
|
||||
coverage, a per-pixel group stack, the W3C blend modes). On the window's wgpu device it draws
|
||||
each stage tile into a texture egui shows as it is (no readback); otherwise on a headless
|
||||
device of its own, read back. Filters and bitmaps are drawn by the oracle instead. The
|
||||
engine's `RenderService` takes any `Rasterizer`, whose pictures may be bytes or an opaque GPU
|
||||
image (`Raster::Native`) only the shell can show, and falls back to the oracle per job, so the
|
||||
engine itself never depends on the GPU.
|
||||
|
||||
## 5. Engine (`anicraft-engine`)
|
||||
|
||||
|
||||
@@ -86,6 +86,29 @@ scattering the tile lists in parallel per tile row. What is left: CPU binning on
|
||||
scenes (next: GPU binning) and the 33 MB readback at 4K (next: render into the texture egui
|
||||
shows).
|
||||
|
||||
### GPU stage, second slice: no readback, masks and groups (M3, ADR 0029)
|
||||
|
||||
Same bench and machine. *Read-back* is the call above; *direct* is the calling thread's time
|
||||
with `render_texture` (prepare + bin + upload and submit, the window's path); *tiled* is the
|
||||
stage's way, 512 px tiles drawn in parallel, until the GPU has finished.
|
||||
|
||||
| Scene | Size | CPU oracle | Read-back | Direct | Tiled (stage) | Parity |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Stress, 50 × 200 (≈10k shapes) | 1920×1080 | 10.6 ms | 13.4 ms | 9.4–10.4 ms (3.0 + 4.7 + 1.7) | 8.7 ms | < 0.0001 / 1 |
|
||||
| Stress, 50 × 200 | 3840×2160 | 25.8–28.1 ms | 23.2 ms | 16.8–18.7 ms (2.7 + 7.5 + 4.8) | **10.2 ms** ✅ 60 fps | < 0.0001 / 1 |
|
||||
| 1,000 shapes | 1920×1080 | 4.4–5.0 ms | 2.9–3.0 ms | 1.1–1.2 ms | 1.8 ms | < 0.0001 / 1 |
|
||||
| 1,000 shapes (M3 target: 4K at 60 fps) | 3840×2160 | 16.2–19.6 ms | 8.4–8.5 ms | **2.1–2.4 ms** ✅ | 4.8 ms | < 0.0001 / 1 |
|
||||
| Masked stress (every other layer a mask) | 1920×1080 | 25.4–26.2 ms | 10.7 ms | 8.7–9.4 ms | 6.6 ms | < 0.0001 / 1 |
|
||||
| Masked stress | 3840×2160 | 74.8–80.0 ms | 20.5–21.8 ms | 14.6–15.3 ms | 10.9 ms | < 0.0001 / 1 |
|
||||
| Sample with a mask and faded symbols | 3840×2160 | 19.1–19.9 ms | 8.3–8.9 ms | 2.1–2.6 ms | 4.6 ms | < 0.0001 / 1 |
|
||||
|
||||
Masked scenes are where the GPU gains most (7× at 4K): the oracle computes each clip's
|
||||
coverage per band into a buffer, the GPU per pixel from the artwork's tile entries. Binning is
|
||||
the largest term of a whole 10k-shape frame, but tiles spread it over every core; it stays on
|
||||
the CPU until scenes of 50k+ shapes or 8K stages need more (ADR 0029). Small scenes pay a
|
||||
little per-tile set-up in the tiled stage (1.8 vs 1.1 ms at 1080p); reusing buffers across
|
||||
tiles is next.
|
||||
|
||||
### How budgets are enforced
|
||||
|
||||
* **Budgets that don't depend on the machine** (undo memory, snapshot sharing, file size,
|
||||
@@ -122,3 +145,5 @@ buffer is tiny; the stage never waits on sound.
|
||||
* [ADR 0003](adr/0003-file-format-v2.md): compact file format with shared paths
|
||||
* [ADR 0015](adr/0015-crash-recovery-autosave.md): crash-recovery autosave on a worker thread
|
||||
* [ADR 0019](adr/0019-gpu-stage.md): GPU stage renderer (first slice), parity with the oracle
|
||||
* [ADR 0029](adr/0029-gpu-stage-direct-masks-groups.md): GPU stage without readback, masks and
|
||||
groups on the GPU, binning kept on the CPU
|
||||
+3
-3
@@ -9,7 +9,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| Dimension | Status |
|
||||
|---|---|
|
||||
| Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). |
|
||||
| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes `<g opacity>`. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. Not yet: no-readback textures, masks/groups/blend on the GPU, GPU binning, bitmaps and filters, GPU exports; the CPU stays the default and the oracle. |
|
||||
| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes `<g opacity>`. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. Not yet: bitmaps and filters on the GPU (they fall back per tile), GPU binning (not the bottleneck as stage tiles; ADR 0029), buffer reuse across tiles, GPU exports, CI with a GPU; the CPU stays the default and the oracle. |
|
||||
| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, onion skin (±2 frames), looping playback. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. Headless: `timeline.create_motion_tween`, `motion.*`. Not yet: motion paths on the stage, retiming keys, rescaling keys with the span, XFL motion-tween import. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tLine truncated
|
||||
| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. No brush or merge drawing yet. |
|
||||
| Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `<settings>/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. |
|
||||
@@ -32,7 +32,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. |
|
||||
| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (basic); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. |
|
||||
| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016; motion paths on stage, 3D and XFL import later); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). |
|
||||
| **M3** | GPU stage *(in progress)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); next: no-readback textures, masks/groups/blend modes on the GPU, GPU binning; becomes the default stage renderer once it covers the display list and is faster everywhere. |
|
||||
| **M3** | GPU stage *(in progress)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); GPU binning deferred (not the bottleneck as tiles); next: bitmaps and filters on the GPU and hardware breadth, then the default stage renderer. |
|
||||
| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. |
|
||||
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output; effects, volume and sounds in symbols later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. |
|
||||
| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: tier 1 keeps scripts (XFL frame scripts and class names stored verbatim, Actions panel, `script.*` commands); tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts. The full language, the `flash.*` API and SWF bytecode are not planned. |
|
||||
@@ -53,7 +53,7 @@ titled with its milestone.
|
||||
| Track | Next task | Depends on (all done) |
|
||||
|---|---|---|
|
||||
| M2 | Motion tweens with property curves and the Motion Editor | timeline evaluation, classic tweens |
|
||||
| M3 | GPU stage: no-readback textures, then masks, group opacity and blend modes on the GPU (first slice ✅, ADR 0019) | CPU oracle, tiled stage, GPU stage first slice |
|
||||
| M3 | GPU stage: bitmaps and filters on the GPU, then the default stage renderer (first slice ✅ ADR 0019, no readback and masks/groups ✅ ADR 0029) | CPU oracle, tiled stage, GPU stage slices 1–2 |
|
||||
| M4 | Text from Animate files | XFL import, text engine (M5 first slice) |
|
||||
| M5 | Audio layers: import, waveform, playback sync | timeline, layers |
|
||||
| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); next: command macros | command registry, plug-in host, action IR and player |
|
||||
|
||||
+4
-1
@@ -361,7 +361,10 @@ pub const VIEW_SHORTCUTS: &[(&str, &str)] = &[
|
||||
|
||||
impl App {
|
||||
pub fn new(cc: &eframe::CreationContext<'_>, session: Session, shot: Option<PathBuf>) -> App {
|
||||
App::with_context(&cc.egui_ctx, session, shot)
|
||||
let mut app = App::with_context(&cc.egui_ctx, session, shot);
|
||||
// The GPU stage shares the window's device when it runs on wgpu (ADR 0029).
|
||||
app.stage_cache.gpu.set_window_device(cc.wgpu_render_state.as_ref());
|
||||
app
|
||||
}
|
||||
|
||||
/// The app on an egui context (the window's, or a headless one in tests).
|
||||
|
||||
+2
-1
@@ -447,7 +447,8 @@ fn preferences(app: &mut App, ctx: &egui::Context) {
|
||||
let status = match app.stage_cache.gpu.state() {
|
||||
State::Off => None,
|
||||
State::Starting => Some("Starting the graphics card…".to_string()),
|
||||
State::Running(adapter) => Some(format!("Drawing on {adapter}.")),
|
||||
State::Running { adapter, direct: true } => Some(format!("Drawing on {adapter}, straight into the window.")),
|
||||
State::Running { adapter, direct: false } => Some(format!("Drawing on {adapter}, then copied to the window (slower: the window's graphics device can't be shared).")),
|
||||
State::Failed(why) => Some(format!("The graphics card can't draw the stage, so the CPU does: {why}")),
|
||||
};
|
||||
if crate::gpu_stage::wanted(p.stage_renderer) != p.stage_renderer {
|
||||
|
||||
+109
-19
@@ -1,14 +1,19 @@
|
||||
//! The GPU stage switch (ADR 0019). With the `gpu-stage` feature, Preferences › Stage ›
|
||||
//! Renderer can hand the stage to the wgpu renderer (`anicraft-gpu`): it starts off the UI
|
||||
//! thread, draws what it can, and the CPU oracle draws the rest (masks, symbol opacity, blend
|
||||
//! modes, filters, bitmaps) and everything when the GPU is missing or fails. Without the feature
|
||||
//! this is a stub and the CPU always draws. Exports never use it.
|
||||
//! The GPU stage switch (ADR 0019, ADR 0029). With the `gpu-stage` feature, Preferences ›
|
||||
//! Stage › Renderer can hand the stage to the wgpu renderer (`anicraft-gpu`): it starts off the
|
||||
//! UI thread, draws what it can, and the CPU oracle draws the rest (filters, bitmaps) and
|
||||
//! everything when the GPU is missing or fails. Without the feature this is a stub and the CPU
|
||||
//! always draws. Exports never use it.
|
||||
//!
|
||||
//! When the window runs on wgpu, the renderer shares the window's device and draws each stage
|
||||
//! tile into a texture the window shows as it is (no copy back to the CPU, ADR 0029). When it
|
||||
//! can't (the window on OpenGL, or the window's device lacks what the stage needs) it opens a
|
||||
//! device of its own and reads the tiles back, as in the first slice.
|
||||
//!
|
||||
//! `ANICRAFT_STAGE_RENDERER=gpu|cpu` overrides the preference (also in `--screenshot` runs,
|
||||
//! which otherwise use default preferences).
|
||||
|
||||
use crate::prefs::StageRenderer;
|
||||
use anicraft_engine::render_service::RenderService;
|
||||
use anicraft_engine::render_service::{NativeImage, RenderService};
|
||||
|
||||
/// Where the GPU stage is.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -17,8 +22,8 @@ pub enum State {
|
||||
/// The CPU draws (by choice, or because this build has no GPU stage).
|
||||
Off,
|
||||
Starting,
|
||||
/// Drawing, on this adapter.
|
||||
Running(String),
|
||||
/// Drawing, on this adapter; `direct` when straight into the window's textures.
|
||||
Running { adapter: String, direct: bool },
|
||||
/// Could not start or stopped working; the CPU draws. The reason, for Preferences.
|
||||
Failed(String),
|
||||
}
|
||||
@@ -41,6 +46,20 @@ pub struct GpuStage {
|
||||
imp: imp::Imp,
|
||||
}
|
||||
|
||||
/// A stage tile the GPU drew into a texture of the window's device, registered with the
|
||||
/// window's renderer for as long as this lives.
|
||||
pub struct NativeTile {
|
||||
id: egui::TextureId,
|
||||
#[cfg(feature = "gpu-stage")]
|
||||
_keep: imp::Registered,
|
||||
}
|
||||
|
||||
impl NativeTile {
|
||||
pub fn id(&self) -> egui::TextureId {
|
||||
self.id
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuStage {
|
||||
pub fn state(&self) -> State {
|
||||
#[cfg(feature = "gpu-stage")]
|
||||
@@ -49,6 +68,15 @@ impl GpuStage {
|
||||
State::Off
|
||||
}
|
||||
|
||||
/// The window's wgpu device, when it runs on wgpu (from eframe's creation context).
|
||||
#[allow(unused_variables)]
|
||||
pub fn set_window_device(&mut self, rs: Option<&eframe::egui_wgpu::RenderState>) {
|
||||
#[cfg(feature = "gpu-stage")]
|
||||
{
|
||||
self.imp.window = rs.cloned();
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies the choice to the render service (called every frame; cheap when nothing
|
||||
/// changes). Starting the renderer happens on its own thread and repaints when done.
|
||||
#[allow(unused_variables)]
|
||||
@@ -56,27 +84,67 @@ impl GpuStage {
|
||||
#[cfg(feature = "gpu-stage")]
|
||||
self.imp.sync(wanted(pref) == StageRenderer::Gpu, svc, ctx);
|
||||
}
|
||||
|
||||
/// Shows a picture the GPU drew into a texture: registers it with the window's renderer.
|
||||
/// `None` when it isn't one of ours (then nothing is shown and the tile is drawn again).
|
||||
#[allow(unused_variables)]
|
||||
pub fn register(&self, native: &NativeImage) -> Option<NativeTile> {
|
||||
#[cfg(feature = "gpu-stage")]
|
||||
return self.imp.register(native);
|
||||
#[cfg(not(feature = "gpu-stage"))]
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "gpu-stage")]
|
||||
mod imp {
|
||||
use super::State;
|
||||
use anicraft_engine::render_service::{Rasterizer, RenderService};
|
||||
use anicraft_gpu::{GpuError, GpuRenderer, Output};
|
||||
use super::{NativeTile, State};
|
||||
use anicraft_engine::render_service::{NativeImage, Raster, Rasterizer, RenderService};
|
||||
use anicraft_gpu::{GpuError, GpuRenderer, GpuTexture, Output};
|
||||
use eframe::egui_wgpu::{RenderState, Renderer};
|
||||
use std::sync::{Arc, mpsc};
|
||||
|
||||
pub struct Imp {
|
||||
pub state: State,
|
||||
pub window: Option<RenderState>,
|
||||
renderer: Option<Arc<GpuRenderer>>,
|
||||
starting: Option<mpsc::Receiver<Result<GpuRenderer, String>>>,
|
||||
}
|
||||
|
||||
impl Default for Imp {
|
||||
fn default() -> Self {
|
||||
Imp { state: State::Off, renderer: None, starting: None }
|
||||
Imp { state: State::Off, window: None, renderer: None, starting: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps a tile's texture alive and registered; frees the registration when dropped.
|
||||
pub struct Registered {
|
||||
id: egui::TextureId,
|
||||
renderer: Arc<egui::mutex::RwLock<Renderer>>,
|
||||
_texture: NativeImage,
|
||||
}
|
||||
|
||||
impl Drop for Registered {
|
||||
fn drop(&mut self) {
|
||||
self.renderer.write().free_texture(&self.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// The window's device first (no readback); a device of our own when that can't work.
|
||||
fn start(window: Option<RenderState>) -> Result<GpuRenderer, String> {
|
||||
let shared = match &window {
|
||||
Some(rs) => match GpuRenderer::shared(&rs.adapter, rs.device.clone(), rs.queue.clone()) {
|
||||
Ok(g) => return Ok(g),
|
||||
Err(e) => Some(e.to_string()),
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
GpuRenderer::new().map_err(|e| match shared {
|
||||
Some(s) => format!("{s}; and on a device of its own: {e}"),
|
||||
None => e.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
impl Imp {
|
||||
pub fn sync(&mut self, want: bool, svc: &RenderService, ctx: &egui::Context) {
|
||||
if let Some(rx) = &self.starting
|
||||
@@ -97,8 +165,9 @@ mod imp {
|
||||
if want && self.renderer.is_none() && self.starting.is_none() && !matches!(self.state, State::Failed(_)) {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let ctx = ctx.clone();
|
||||
let window = self.window.clone();
|
||||
let spawned = std::thread::Builder::new().name("anicraft-gpu-start".into()).spawn(move || {
|
||||
let _ = tx.send(GpuRenderer::new().map_err(|e| e.to_string()));
|
||||
let _ = tx.send(start(window));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
match spawned {
|
||||
@@ -113,12 +182,25 @@ mod imp {
|
||||
match (drawing, svc.has_rasterizer()) {
|
||||
(Some(g), false) => {
|
||||
let g = g.clone();
|
||||
self.state = State::Running(g.adapter.clone());
|
||||
let raster: Rasterizer = Arc::new(move |dl, view| match g.render(dl, view, Output::Premul8) {
|
||||
Ok(f) => Ok((f.premul8, f.stats)),
|
||||
Err(GpuError::NeedsFull(why)) => Err(why.to_string()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
});
|
||||
self.state = State::Running { adapter: g.adapter.clone(), direct: g.shared };
|
||||
let why = |e: GpuError| match e {
|
||||
GpuError::NeedsFull(why) => why.to_string(),
|
||||
e => e.to_string(),
|
||||
};
|
||||
let raster: Rasterizer = if g.shared {
|
||||
Arc::new(move |dl, view| match g.render_texture(dl, view) {
|
||||
Ok(t) => {
|
||||
let (width, height, stats) = (t.width, t.height, t.stats);
|
||||
Ok((Raster::Native { image: Arc::new(t), width, height }, stats))
|
||||
}
|
||||
Err(e) => Err(why(e)),
|
||||
})
|
||||
} else {
|
||||
Arc::new(move |dl, view| match g.render(dl, view, Output::Premul8) {
|
||||
Ok(f) => Ok((Raster::Premul8(f.premul8), f.stats)),
|
||||
Err(e) => Err(why(e)),
|
||||
})
|
||||
};
|
||||
svc.set_rasterizer(Some(raster));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
@@ -132,5 +214,13 @@ mod imp {
|
||||
self.state = State::Off;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(&self, native: &NativeImage) -> Option<NativeTile> {
|
||||
let rs = self.window.as_ref()?;
|
||||
let tex = native.downcast_ref::<GpuTexture>()?;
|
||||
// The texture lives on the window's device (only a shared renderer makes these).
|
||||
let id = rs.renderer.write().register_native_texture(&rs.device, &tex.view, eframe::wgpu::FilterMode::Linear);
|
||||
Some(NativeTile { id, _keep: Registered { id, renderer: rs.renderer.clone(), _texture: native.clone() } })
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -198,8 +198,8 @@ fn renderer_tag(app: &App) -> String {
|
||||
match (app.stage_cache.gpu.state(), &app.stage_cache.drawn_by) {
|
||||
(State::Starting, _) => " · GPU starting".into(),
|
||||
(State::Failed(_), _) => " · CPU (GPU unavailable)".into(),
|
||||
(State::Running(_), Some((true, _))) => " · GPU".into(),
|
||||
(State::Running(_), Some((false, Some(why)))) => format!(" · CPU for {why}"),
|
||||
(State::Running { .. }, Some((true, _))) => " · GPU".into(),
|
||||
(State::Running { .. }, Some((false, Some(why)))) => format!(" · CPU for {why}"),
|
||||
_ => " · CPU".into(),
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -49,7 +49,7 @@ pub enum StageRenderer {
|
||||
impl StageRenderer {
|
||||
pub const ALL: [(StageRenderer, &'static str, &'static str); 2] = [
|
||||
(StageRenderer::Cpu, "CPU (reference)", "The reference renderer. Exports always use it."),
|
||||
(StageRenderer::Gpu, "GPU (preview)", "Draws the stage on the graphics card. Masks, symbol opacity, blend modes, filters and bitmaps still draw on the CPU; the picture is the same either way."),
|
||||
(StageRenderer::Gpu, "GPU (preview)", "Draws the stage on the graphics card, masks, symbol opacity and blend modes included. Filters and bitmaps still draw on the CPU; the picture is the same either way."),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
+27
-3
@@ -32,10 +32,25 @@ struct TileTex {
|
||||
key: u64,
|
||||
/// Stage-space rectangle `[x0, y0, x1, y1]` this tile covers.
|
||||
rect: [f32; 4],
|
||||
tex: egui::TextureHandle,
|
||||
tex: TileImage,
|
||||
used: u64,
|
||||
}
|
||||
|
||||
/// A tile's texture: uploaded from the CPU's bytes, or drawn there by the GPU stage (ADR 0029).
|
||||
enum TileImage {
|
||||
Uploaded(egui::TextureHandle),
|
||||
Drawn(crate::gpu_stage::NativeTile),
|
||||
}
|
||||
|
||||
impl TileImage {
|
||||
fn id(&self) -> egui::TextureId {
|
||||
match self {
|
||||
TileImage::Uploaded(t) => t.id(),
|
||||
TileImage::Drawn(t) => t.id(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Cache {
|
||||
tiles: Vec<TileTex>,
|
||||
tick: u64,
|
||||
@@ -88,9 +103,18 @@ impl Cache {
|
||||
if self.tiles.iter().any(|t| t.key == img.key) {
|
||||
return None;
|
||||
}
|
||||
let image = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.rgba_premul);
|
||||
let tex = match &img.native {
|
||||
// Already on the window's device: shown as it is, nothing to upload.
|
||||
Some(native) => match self.gpu.register(native) {
|
||||
Some(t) => TileImage::Drawn(t),
|
||||
None => return Some("The GPU stage drew a picture the window can't show.".into()),
|
||||
},
|
||||
None => {
|
||||
let image = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.rgba_premul);
|
||||
TileImage::Uploaded(ctx.load_texture(format!("tile-{:x}", img.key), image, egui::TextureOptions::LINEAR))
|
||||
}
|
||||
};
|
||||
self.tick += 1;
|
||||
let tex = ctx.load_texture(format!("tile-{:x}", img.key), image, egui::TextureOptions::LINEAR);
|
||||
self.tiles.push(TileTex { key: img.key, rect, tex, used: self.tick });
|
||||
// Evict least recently used tiles that are not on screen.
|
||||
while self.tiles.len() > MAX_TILE_TEXTURES {
|
||||
|
||||
Reference in new issue
Block a user