Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Bound native rendering worksets and share completed frames

Sina Atalay61f47347761a
diff --git a/rust/engine/src/blend.wgsl b/rust/engine/src/blend.wgsl
index e3d5399b..7aab6629 100644
--- a/rust/engine/src/blend.wgsl
+++ b/rust/engine/src/blend.wgsl
@@ -120,30 +120,39 @@ fn clip_along(i: u32, d: vec3<f32>, d2: vec3<f32>) -> vec4<f32> {
return c;
}
-// A mesh face's depth over the screen at its edge from vertex `at` toward vertex `to`: the plane tangent to it there
-// (its normal at `at`: a flat face's own, a refined surface's), as (its depth gradient in pixels, its depth at `at`),
-// from `at`, `to` and the point across the edge in that plane; none (a zero gradient, `at`'s own depth) where the face
-// has no normal or is seen edge on. So the face's edge drawn by it lies on it, to the depth's digits.
+// A direction's projective differential at c, in pixel x, pixel y, depth. The common 1/c.w² cancels from a plane's
+// gradient. Scaling each direction before the cross product makes its magnitude irrelevant, including tiny normals.
+fn projected_direction(c: vec4<f32>, d: vec4<f32>) -> vec3<f32> {
+ let v = (c.w * d.xyz - d.w * c.xyz) * vec3<f32>(0.5 * view.pixels.xy, 1.0);
+ let scale = max(max(abs(v.x), abs(v.y)), abs(v.z));
+ if (scale == 0.0) {
+ return vec3<f32>(0.0);
+ }
+ return v / scale;
+}
+
+// A mesh face's tangent plane at its edge: (depth gradient in pixels, depth at `at`). Derivatives of the projective
+// map give the gradient directly: subtracting projected nearby points loses the small tangent in f32 rounding.
+// No gradient where the face has no normal or is seen edge on.
fn face_plane(i: u32, at: u32, to: u32) -> vec3<f32> {
- let sa = screen(clip(i, at));
+ let ca = clip(i, at);
+ let sa = screen(ca);
let n = vertex_extra(at).xyz;
let edge = vertex(to).xyz - vertex(at).xyz;
+ var edge2 = vec3<f32>(0.0);
var across2 = vec3<f32>(0.0);
if (ids_of(i).y != NONE) {
let k = ids_of(i).y - ids_of(i).x;
- across2 = cross(vertex_extra(at + k).xyz, vertex(to + k).xyz - vertex(at + k).xyz);
+ edge2 = vertex(to + k).xyz - vertex(at + k).xyz;
+ across2 = cross(vertex_extra(at + k).xyz, edge2);
}
- let sb = screen(clip(i, to));
- let sc = screen(clip(i, at) + clip_along(i, cross(n, edge), across2));
- let d1 = sb.xy - sa.xy;
- let d2 = sc.xy - sa.xy;
+ let d1 = projected_direction(ca, clip_along(i, edge, edge2));
+ let d2 = projected_direction(ca, clip_along(i, cross(n, edge), across2));
let det = d1.x * d2.y - d1.y * d2.x;
- if (dot(n, n) < 1e-24 || abs(det) < 1e-6 * (dot(d1, d1) + dot(d2, d2)) || sb.z < 0.0 || sc.z < 0.0) {
+ if (det * det <= 1e-12 * dot(d1.xy, d1.xy) * dot(d2.xy, d2.xy) || sa.z < 0.0 || screen(clip(i, to)).z < 0.0) {
return vec3<f32>(0.0, 0.0, sa.z);
}
- let dz1 = sb.z - sa.z;
- let dz2 = sc.z - sa.z;
- return vec3<f32>(dz1 * d2.y - dz2 * d1.y, dz2 * d1.x - dz1 * d2.x, 0.0) / det + vec3<f32>(0.0, 0.0, sa.z);
+ return vec3<f32>(d1.z * d2.y - d2.z * d1.y, d2.z * d1.x - d1.z * d2.x, 0.0) / det + vec3<f32>(0.0, 0.0, sa.z);
}
// How much nearer a face's edge is drawn than its face: a share of its depth (16 of its f32 steps) and its depth slope
@@ -177,7 +186,7 @@ fn along(i: u32, px: vec2<f32>) -> f32 {
// ── edges ─────────────────────────────────────────────────────────────────────
-// A count writes only the stencil: the least fragment work a pass with a color target allows.
+// A count writes depth and stencil: the least fragment work a pass with a color target allows.
@fragment
fn fs_none() -> @location(0) vec4<f32> {
return vec4<f32>(0.0);
@@ -379,10 +388,15 @@ fn carry(r0: vec4<f32>, r1: vec4<f32>, r2: vec4<f32>, n: vec3<f32>) -> vec3<f32>
// CE's light: half the cube of the cosine toward the light, halved again when facing away, on the side the eye sees
// from p (a 3D view's perspective; else, or `fixed` in the frame, the side toward the view).
fn shade(normal: vec3<f32>, p: vec3<f32>, fixed: bool) -> f32 {
+ let toward_light = view.light.xyz - p;
+ if (dot(normal, normal) == 0.0 || dot(toward_light, toward_light) == 0.0) {
+ return 0.0;
+ }
let seen = select(view.toward.xyz, view.eye.xyz - p, view.eye.w > 0.5 && !fixed);
let n = normalize(select(normal, -normal, dot(seen, normal) < 0.0));
- let l = normalize(view.light.xyz - p);
- let amount = 0.5 * pow(dot(n, l), 3.0);
+ let cosine = dot(n, normalize(toward_light));
+ // WGSL pow excludes negative bases; the signed cube is defined on both sides of a face.
+ let amount = 0.5 * cosine * cosine * cosine;
return select(amount, amount * 0.5, amount < 0.0);
}
diff --git a/rust/engine/src/blend_lists.wgsl b/rust/engine/src/blend_lists.wgsl
index e2077ab8..250132a9 100644
--- a/rust/engine/src/blend_lists.wgsl
+++ b/rust/engine/src/blend_lists.wgsl
@@ -47,7 +47,7 @@ struct Node {
@group(2) @binding(0) var<storage, read_write> heads: array<atomic<u32>>;
@group(2) @binding(1) var<storage, read_write> nodes: array<Node>;
@group(2) @binding(2) var<storage, read_write> appended: atomic<u32>;
-@group(2) @binding(3) var opaque_depth: texture_depth_multisampled_2d;
+@group(2) @binding(3) var opaque_depth: SampleDepth;
// Where sample s of n lies from its pixel's center (the standard patterns; others: the center).
fn sample_offset(n: u32, s: u32) -> vec2<f32> {
diff --git a/rust/engine/src/lib.rs b/rust/engine/src/lib.rs
index 3b67ed62..7a7b387e 100644
--- a/rust/engine/src/lib.rs
+++ b/rust/engine/src/lib.rs
@@ -17,6 +17,8 @@ mod chrome;
#[cfg(feature = "export")]
mod encode;
mod environment;
+#[cfg(any(feature = "python", feature = "render", test))]
+mod mesh;
#[cfg(feature = "export")]
mod export;
#[cfg(feature = "export")]
@@ -56,6 +58,10 @@ pub fn digest<'a>(parts: impl IntoIterator<Item = &'a [u8]>) -> u64 {
/// height, view, records).
pub(crate) type CameraView = (u64, u32, u32, Vec<u8>, Vec<u8>);
+pub(crate) fn check_key(key: u64) -> Result<(), String> {
+ if key == 0 { Err("key 0 is reserved".into()) } else { Ok(()) }
+}
+
/// Bytes as the items they hold (`what` names them in the error).
pub(crate) fn read<T: bytemuck::Pod>(bytes: &[u8], what: &str) -> Result<Vec<T>, String> {
if !bytes.len().is_multiple_of(size_of::<T>()) {
diff --git a/rust/engine/src/mesh.rs b/rust/engine/src/mesh.rs
new file mode 100644
index 00000000..4ca32387
--- /dev/null
+++ b/rust/engine/src/mesh.rs
@@ -0,0 +1,100 @@
+//! A mesh prepared for drawing or recording. Geometry is evaluated in its input precision;
+//! each sink rounds the finished vertices and normals to the GPU's precision.
+
+use std::borrow::Cow;
+
+pub(crate) struct Mesh<'a> {
+ pub(crate) points: Cow<'a, [[f64; 3]]>,
+ pub(crate) uvs: Cow<'a, [[f64; 2]]>,
+ pub(crate) normals: Cow<'a, [[f64; 3]]>,
+ pub(crate) triangles: Cow<'a, [u32]>,
+ pub(crate) outline: u32,
+ pub(crate) block: u32,
+}
+
+impl<'a> Mesh<'a> {
+ pub(crate) fn new(points: &'a [u8], uvs: &'a [u8], normals: &'a [u8], triangles: &'a [u8], outline: u32, block: u32) -> Result<Self, String> {
+ let p = read::<[f64; 3]>(points, "points")?;
+ let uv = read::<[f64; 2]>(uvs, "uvs")?;
+ let t = read::<u32>(triangles, "triangles")?;
+ if uv.len() != p.len() || !t.len().is_multiple_of(3) || t.iter().any(|&i| i as usize >= p.len()) {
+ return Err("a mesh needs a (u, v) per point, and whole triangles of its points".into());
+ }
+ let n = if normals.is_empty() { smooth_normals(&p, &t).into() } else { read::<[f64; 3]>(normals, "normals")? };
+ if n.len() != p.len() {
+ return Err("a mesh needs a normal per point".into());
+ }
+ let block = if block == 0 { outline } else { block };
+ if outline > 2 && (block < outline || !p.len().is_multiple_of(block as usize)) {
+ return Err("an outlined mesh is whole faces of vertices, each beginning with its loop".into());
+ }
+ // A reveal shows a surface face by face: each face's triangles are its own.
+ let faces = (p.len() / block.max(1) as usize).max(1);
+ let own = |(k, face): (usize, &[u32])| face.iter().all(|&i| i as usize / block as usize == k);
+ if outline > 2 && (!t.len().is_multiple_of(3 * faces) || (!t.is_empty() && !t.chunks(t.len() / faces).enumerate().all(own))) {
+ return Err("an outlined mesh's triangles are its faces' own, face after face, as many each".into());
+ }
+ Ok(Self {
+ points: p,
+ uvs: uv,
+ normals: n,
+ triangles: t,
+ outline,
+ block,
+ })
+ }
+}
+
+/// Borrow aligned input; a byte buffer with another alignment is read into aligned storage.
+fn read<'a, T: bytemuck::Pod>(bytes: &'a [u8], what: &str) -> Result<Cow<'a, [T]>, String> {
+ match bytemuck::try_cast_slice(bytes) {
+ Ok(values) => Ok(Cow::Borrowed(values)),
+ Err(_) => crate::read(bytes, what).map(Cow::Owned),
+ }
+}
+
+/// Area-weighted vertex normals: each corner receives its faces in one fixed order.
+fn smooth_normals(p: &[[f64; 3]], triangles: &[u32]) -> Vec<[f64; 3]> {
+ let faces: Vec<[f64; 3]> = triangles
+ .chunks_exact(3)
+ .map(|t| {
+ let (a, b, c) = (p[t[0] as usize], p[t[1] as usize], p[t[2] as usize]);
+ let (u, w) = ([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]);
+ [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]]
+ })
+ .collect();
+ let mut out = vec![[0.0f64; 3]; p.len()];
+ for k in 0..3 {
+ for (t, f) in triangles.chunks_exact(3).zip(&faces) {
+ let o = &mut out[t[k] as usize];
+ o[0] += f[0];
+ o[1] += f[1];
+ o[2] += f[2];
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn an_unaligned_byte_buffer_prepares_the_same_mesh() {
+ let points = [[1.0f64, 2.0, 3.0], [4.0, 5.0, 6.0], [2.0, 2.0, 0.0]];
+ let uvs = [[0.0f64; 2]; 3];
+ let triangles = [0u32, 1, 2];
+ let aligned = Mesh::new(bytemuck::cast_slice(&points), bytemuck::cast_slice(&uvs), &[], bytemuck::cast_slice(&triangles), 0, 0).unwrap();
+ let mut bytes = vec![0];
+ bytes.extend_from_slice(bytemuck::cast_slice(&points));
+ let end_points = bytes.len();
+ bytes.extend_from_slice(bytemuck::cast_slice(&uvs));
+ let end_uvs = bytes.len();
+ bytes.extend_from_slice(bytemuck::cast_slice(&triangles));
+ let shifted = Mesh::new(&bytes[1..end_points], &bytes[end_points..end_uvs], &[], &bytes[end_uvs..], 0, 0).unwrap();
+ assert_eq!(shifted.points, aligned.points);
+ assert_eq!(shifted.uvs, aligned.uvs);
+ assert_eq!(shifted.normals, aligned.normals);
+ assert_eq!(shifted.triangles, aligned.triangles);
+ }
+}
diff --git a/rust/engine/src/pack.rs b/rust/engine/src/pack.rs
index 7affb372..47724c96 100644
--- a/rust/engine/src/pack.rs
+++ b/rust/engine/src/pack.rs
@@ -28,7 +28,7 @@ pub(crate) const SECOND: u8 = 2;
pub(crate) const TAIL: u8 = 3;
/// Versions in a chain before a keyframe.
-#[cfg(any(feature = "python", test))]
+#[cfg(any(feature = "python", feature = "player", test))]
pub(crate) const DEPTH: u8 = 32;
/// What an array holds: its elements' type and how many lanes make one (coded lane by lane).
@@ -78,14 +78,14 @@ impl Kind {
}
/// Whether it arrives as float64 and goes as float32.
- #[cfg(any(feature = "python", test))]
+ #[cfg(any(feature = "python", all(test, not(target_arch = "wasm32"))))]
pub(crate) fn rounded(self) -> bool {
matches!(self, Kind::MeshPoints | Kind::MeshUvs | Kind::MeshNormals)
}
}
/// The array as a take carries it: a mesh's float64s as float32s, anything else as it is.
-#[cfg(any(feature = "python", test))]
+#[cfg(any(feature = "python", all(test, not(target_arch = "wasm32"))))]
pub(crate) fn canonical(kind: Kind, data: &[u8]) -> Vec<u8> {
if kind.rounded() {
let f: Vec<f64> = bytemuck::pod_collect_to_vec(data);
@@ -95,7 +95,7 @@ pub(crate) fn canonical(kind: Kind, data: &[u8]) -> Vec<u8> {
}
/// The key an array is sent under: of its kind and content (equal bytes of two kinds differ).
-#[cfg(any(feature = "python", test))]
+#[cfg(any(feature = "python", all(test, not(target_arch = "wasm32"))))]
pub(crate) fn key(kind: Kind, data: &[u8]) -> u64 {
crate::digest([&[kind as u8][..], data])
}
@@ -105,7 +105,7 @@ trait Lane: Pod {
fn ordered(self, float: bool) -> Self;
#[cfg_attr(not(any(feature = "player", test)), allow(dead_code))]
fn unordered(self, float: bool) -> Self;
- #[cfg_attr(not(any(feature = "python", test)), allow(dead_code))]
+ #[cfg_attr(not(any(feature = "python", all(test, not(target_arch = "wasm32")))), allow(dead_code))]
fn sub(self, other: Self) -> Self;
#[cfg_attr(not(any(feature = "player", test)), allow(dead_code))]
fn add(self, other: Self) -> Self;
@@ -160,7 +160,7 @@ impl Lane for u8 {
}
/// Elements lane by lane (all x's, then all y's, …), then byte by byte: what zstd compresses.
-#[cfg(any(feature = "python", test))]
+#[cfg(any(feature = "python", all(test, not(target_arch = "wasm32"))))]
fn planes<T: Pod>(values: &[T], lanes: usize) -> Vec<u8> {
let lanes = if lanes > 1 && values.len().is_multiple_of(lanes) { lanes } else { 1 };
let (n, w) = (values.len(), size_of::<T>());
@@ -195,7 +195,7 @@ fn unplanes<T: Pod>(bytes: &[u8], lanes: usize) -> Vec<T> {
/// Code `data` (canonical bytes) against its base (and the base's base), if any: the smallest of
/// the codings that apply. Returns (mode, compressed payload).
-#[cfg(any(feature = "python", test))]
+#[cfg(any(feature = "python", all(test, not(target_arch = "wasm32"))))]
pub(crate) fn encode(kind: Kind, data: &[u8], base: Option<&[u8]>, older: Option<&[u8]>) -> (u8, Vec<u8>) {
match kind.width() {
8 => encode_lanes::<u64>(kind, data, base, older),
@@ -204,7 +204,7 @@ pub(crate) fn encode(kind: Kind, data: &[u8], base: Option<&[u8]>, older: Option
}
}
-#[cfg(any(feature = "python", test))]
+#[cfg(any(feature = "python", all(test, not(target_arch = "wasm32"))))]
fn encode_lanes<T: Lane>(kind: Kind, data: &[u8], base: Option<&[u8]>, older: Option<&[u8]>) -> (u8, Vec<u8>) {
let (float, lanes) = (kind.float(), kind.lanes());
let a: Vec<T> = bytemuck::pod_collect_to_vec(data);
@@ -249,17 +249,20 @@ pub(crate) fn decode(kind: Kind, mode: u8, blob: &[u8], base: Option<&[u8]>, old
#[cfg(any(feature = "player", test))]
fn decode_lanes<T: Lane>(kind: Kind, mode: u8, bytes: &[u8], base: Option<&[u8]>, older: Option<&[u8]>) -> Result<Vec<u8>, String> {
let (float, lanes) = (kind.float(), kind.lanes());
+ if !bytes.len().is_multiple_of(size_of::<T>()) { return Err("an array ends inside an element".into()); }
let values: Vec<T> = unplanes(bytes, lanes);
- let base = || -> Result<Vec<T>, String> { base.map(bytemuck::pod_collect_to_vec).ok_or_else(|| "an array's base is missing".into()) };
+ let base = || -> Result<Vec<T>, String> { crate::read(base.ok_or("an array's base is missing")?, "array base") };
let ord = |v: &[T]| v.iter().map(|&x| x.ordered(float)).collect::<Vec<T>>();
let out: Vec<T> = match mode {
ALONE => values.iter().map(|&x| x.unordered(float)).collect(),
FIRST => {
let b = base()?;
+ if b.len() != values.len() { return Err("an array's difference and base have different lengths".into()); }
ord(&b).iter().zip(&values).map(|(&y, &r)| y.add(r).unordered(float)).collect()
}
SECOND => {
- let (b, o): (Vec<T>, Vec<T>) = (base()?, older.map(bytemuck::pod_collect_to_vec).ok_or("an array's second base is missing")?);
+ let (b, o): (Vec<T>, Vec<T>) = (base()?, crate::read(older.ok_or("an array's second base is missing")?, "array second base")?);
+ if b.len() != o.len() || b.len() != values.len() { return Err("an array's prediction and difference have different lengths".into()); }
let p: Vec<T> = b.iter().zip(&o).map(|(&b, &o)| T::predict(b, o)).collect::<Option<_>>().ok_or("a prediction is not finite")?;
ord(&p).iter().zip(&values).map(|(&y, &r)| y.add(r).unordered(float)).collect()
}
@@ -273,7 +276,7 @@ fn decode_lanes<T: Lane>(kind: Kind, mode: u8, bytes: &[u8], base: Option<&[u8]>
Ok(bytemuck::cast_slice(&out).to_vec())
}
-#[cfg(test)]
+#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
@@ -315,3 +318,22 @@ mod tests {
assert_ne!(key(Kind::MeshPoints, &[]), key(Kind::MeshTriangles, &[]));
}
}
+
+#[cfg(test)]
+mod decoder_contract {
+ use super::*;
+
+ #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
+ #[cfg_attr(not(target_arch = "wasm32"), test)]
+ fn malformed_arrays_are_not_padded_or_truncated() {
+ let base = [0u8; 8];
+ assert!(decode_lanes::<u32>(Kind::Points, ALONE, &[0; 3], None, None).is_err());
+ assert!(decode_lanes::<u64>(Kind::PathPoints, ALONE, &[0; 7], None, None).is_err());
+ assert!(decode_lanes::<u32>(Kind::Points, FIRST, &[], Some(&base), None).is_err());
+ assert!(decode_lanes::<u32>(Kind::Points, FIRST, &base, Some(&base[..3]), None).is_err());
+ assert!(decode_lanes::<u32>(Kind::Points, SECOND, &base, Some(&base), Some(&base[..4])).is_err());
+ assert!(decode_lanes::<u32>(Kind::Points, SECOND, &base[..4], Some(&base), Some(&base)).is_err());
+ assert_eq!(decode_lanes::<u32>(Kind::Points, FIRST, &base, Some(&base), None).unwrap(), base);
+ assert_eq!(decode_lanes::<u32>(Kind::Points, SECOND, &base, Some(&base), Some(&base)).unwrap(), base);
+ }
+}
diff --git a/rust/engine/src/project.rs b/rust/engine/src/project.rs
index 55d61276..03e39943 100644
--- a/rust/engine/src/project.rs
+++ b/rust/engine/src/project.rs
@@ -72,13 +72,30 @@ struct Coded {
kind: Kind,
mode: u8,
base: u64,
+ depth: u8,
blob: Blob,
}
impl Pack {
fn add(&mut self, f: &mut Fields) -> Result<(), String> {
let (key, base, kind, mode, data) = (f.u64()?, f.u64()?, Kind::from_u8(f.u8()?)?, f.u8()?, f.string()?);
- self.arrays.insert(key, Coded { kind, mode, base, blob: blob(data) });
+ crate::check_key(key)?;
+ if self.arrays.contains_key(&key) { return Err("an array key is immutable within a take".into()); }
+ // The writer sends every base first, once, and cuts each dependency chain at DEPTH.
+ // Enforcing that DAG on receipt keeps lazy decoding bounded and rules out cycles.
+ let depth = match mode {
+ pack::ALONE if base == 0 => 0,
+ pack::ALONE => return Err("an independent array cannot have a base".into()),
+ pack::FIRST | pack::SECOND | pack::TAIL => {
+ let parent = self.arrays.get(&base).ok_or("an array's base must precede it")?;
+ if parent.kind != kind { return Err("an array and its base have different kinds".into()); }
+ if mode == pack::SECOND && parent.base == 0 { return Err("an array's second base is missing".into()); }
+ if parent.depth >= pack::DEPTH { return Err("an array's dependency chain is too deep".into()); }
+ parent.depth + 1
+ }
+ _ => return Err(format!("unknown array coding {mode}")),
+ };
+ self.arrays.insert(key, Coded { kind, mode, base, depth, blob: blob(data) });
Ok(())
}
@@ -118,7 +135,7 @@ impl Pack {
/// How an upload is made from its arrays.
enum Recipe {
- Path { centroid_area: [f32; 6], points: u64, subpaths: u64, grown: Vec<(u64, bool)> },
+ Path { centroid_area: [f32; 6], points: u64, subpaths: u64, grown: Vec<(u32, u64, bool)>, applied: usize },
Points(u64),
Mesh { outline: u32, block: u32, arrays: [u64; 4] },
Rows(u64),
@@ -127,12 +144,24 @@ enum Recipe {
impl Recipe {
/// Put the shape (brush, texture) `key` into the player.
- fn make(&self, key: u64, pack: &mut Pack, player: &mut Player) -> Result<(), String> {
+ fn make(&mut self, key: u64, frame: u32, pack: &mut Pack, player: &mut Player) -> Result<(), String> {
+ if !matches!(self, Recipe::Path { .. }) && player.has(key) {
+ return Ok(());
+ }
match self {
- Recipe::Path { centroid_area, points, subpaths, grown } => {
- player.add_path(key, &pack.get(*points)?, &pack.get(*subpaths)?, *centroid_area)?;
- for &(tail, closed) in grown {
+ Recipe::Path { centroid_area, points, subpaths, grown, applied } => {
+ // A shot sees only growth that had arrived when it was recorded. The
+ // path's bounds, joints and closure belong to that version too: cropping
+ // a fully grown path's curve window cannot recover its earlier picture.
+ let wanted = grown.partition_point(|&(first, _, _)| first <= frame);
+ if !player.has(key) || *applied > wanted {
+ player.evict(&[key]);
+ player.add_path(key, &pack.get(*points)?, &pack.get(*subpaths)?, *centroid_area)?;
+ *applied = 0;
+ }
+ for &(_, tail, closed) in &grown[*applied..wanted] {
player.grow_path(key, &pack.get(tail)?, closed)?;
+ *applied += 1;
}
}
Recipe::Points(data) => player.add_points(key, &pack.get(*data)?)?,
@@ -171,6 +200,35 @@ pub(crate) struct Take {
}
impl Take {
+ /// One complete, successful recording, decoded by the same projector as a window or page.
+ #[cfg(any(feature = "python", test))]
+ pub(crate) fn read(stream: &[u8]) -> Result<Self, String> {
+ let mut projector = Projector::default();
+ projector.feed(stream)?;
+ if !projector.pending.is_empty() { return Err("a message of the take ends early".into()); }
+ if projector.takes != 1 { return Err("a recording must contain exactly one take".into()); }
+ let take = projector.shown.unwrap();
+ if !take.ended || take.failed { return Err("the take did not end successfully".into()); }
+ if take.frames == 0 || take.size.0 == 0 || take.size.1 == 0 || !take.fps.is_finite() || take.fps <= 0.0 {
+ return Err("a take needs frames, positive dimensions, and a finite positive frame rate".into());
+ }
+ Ok(take)
+ }
+
+ /// A recording's exact integer frame, including holds; every upload uses the projector's
+ /// existing recipes and bounded decoded-array cache.
+ #[cfg(any(feature = "python", test))]
+ pub(crate) fn frame_views(&mut self, frame: u32) -> Result<Vec<Frame>, String> {
+ if frame >= self.frames { return Err(format!("frame {frame} is outside the take's {} frames", self.frames)); }
+ self.views(self.shot(frame).ok_or("the take has no recorded frames")?)
+ }
+
+ /// Each recorded shot's first frame and repeat count, without expanding its held frames.
+ #[cfg(any(feature = "python", test))]
+ pub(crate) fn timeline(&self) -> Vec<(u32, u32)> {
+ self.shots.iter().enumerate().map(|(i, shot)| (shot.first, self.shots.get(i + 1).map_or(self.frames, |next| next.first) - shot.first)).collect()
+ }
+
/// Its frame at `time` seconds (the last, past its end).
pub(crate) fn frame(&self, time: f64) -> u32 {
((time * self.fps + 1e-6).floor().max(0.0) as u32).min(self.frames.saturating_sub(1))
@@ -181,11 +239,10 @@ impl Take {
f64::from(self.frames) > (time * self.fps + 1e-6).floor()
}
- /// Its shot showing the frame at `time` (the last, past its end).
- fn shot(&self, time: f64) -> Option<usize> {
+ /// Its shot showing `frame` (the last, past its end).
+ fn shot(&self, frame: u32) -> Option<usize> {
let last = self.shots.len().checked_sub(1)?;
- let index = self.frame(time);
- Some(self.shots.partition_point(|s| s.first <= index).saturating_sub(1).min(last))
+ Some(self.shots.partition_point(|s| s.first <= frame).saturating_sub(1).min(last))
}
/// Shot `at`'s views (its cameras', then the frame), everything they draw in the player.
@@ -201,10 +258,8 @@ impl Take {
for frame in &frames {
for keys in take::slots(bytemuck::cast_slice(&frame.records)) {
for key in keys.into_iter().filter(|&k| k != 0) {
- if !player.has(key)
- && let Some(recipe) = recipes.get(&key)
- {
- recipe.make(key, pack, player)?;
+ if let Some(recipe) = recipes.get_mut(&key) {
+ recipe.make(key, shot.first, pack, player)?;
}
used.insert(key, self.draws);
}
@@ -294,8 +349,14 @@ impl Projector {
fn message(&mut self, message: &[u8], notes: &mut Vec<(u32, Note)>) -> Result<(), String> {
let mut f = Fields(message);
let op = f.u8()?;
+ if op == 0 {
+ return Err("unversioned takes are unsupported; record the scene again with this version of manimgx".into());
+ }
if op == take::START {
+ let format = f.u32()?;
+ if format != take::VERSION { return Err(format!("unsupported take format {format}; this engine reads format {}", take::VERSION)); }
let (width, height, fps) = (f.u32()?, f.u32()?, f.f64()?);
+ if width == 0 || height == 0 || !fps.is_finite() || fps <= 0.0 { return Err("a take needs positive dimensions and a finite positive frame rate".into()); }
self.takes += 1;
let fresh = Take { number: self.takes, size: (width, height), player: Player::new(width, height, 4), pack: Pack::default(), recipes: HashMap::new(), shots: Vec::new(), used: HashMap::new(), draws: 0, frames: 0, fps, ended: false, failed: false };
// the first take is shown at once; a later one comes in beside it
@@ -313,6 +374,7 @@ impl Projector {
return Ok(());
}
let Some(t) = newest else { return Err("a take begins with START".into()) };
+ if t.ended { return Err("a take cannot change after END".into()); }
// filed, not made: a frame makes what it draws when it is drawn
let recipe = match op {
take::ARRAY => return t.pack.add(&mut f),
@@ -320,7 +382,7 @@ impl Projector {
(t.ended, t.failed) = (true, f.u8()? != 0);
return Ok(());
}
- take::PATH => (f.u64()?, Recipe::Path { centroid_area: f.f32s()?, points: f.u64()?, subpaths: f.u64()?, grown: Vec::new() }),
+ take::PATH => (f.u64()?, Recipe::Path { centroid_area: f.f32s()?, points: f.u64()?, subpaths: f.u64()?, grown: Vec::new(), applied: 0 }),
take::POINTS => (f.u64()?, Recipe::Points(f.u64()?)),
take::MESH => (f.u64()?, Recipe::Mesh { outline: f.u32()?, block: f.u32()?, arrays: [f.u64()?, f.u64()?, f.u64()?, f.u64()?] }),
take::ROWS => (f.u64()?, Recipe::Rows(f.u64()?)),
@@ -333,19 +395,20 @@ impl Projector {
take::GROW => {
let (key, closed, tail) = (f.u64()?, f.u8()? != 0, f.u64()?);
if let Some(Recipe::Path { grown, .. }) = t.recipes.get_mut(&key) {
- grown.push((tail, closed));
+ grown.push((t.frames, tail, closed));
}
- t.player.evict(&[key]); // made again, grown, when next drawn
return Ok(());
}
take::FRAME => {
let (repeat, view, records) = (f.u32()?, f.string()?.to_vec(), f.u64()?);
+ if repeat == 0 { return Err("a recorded frame needs a positive repeat count".into()); }
+ let frames = t.frames.checked_add(repeat).ok_or("the take has too many frames")?;
let mut cameras = Vec::new();
for _ in 0..f.u32()? {
cameras.push((f.u64()?, f.u32()?, f.u32()?, f.string()?.to_vec(), f.u64()?));
}
t.shots.push(Shot { first: t.frames, view, records, cameras });
- t.frames += repeat;
+ t.frames = frames;
return Ok(());
}
op => return Err(format!("unknown message {op} in the take")),
@@ -371,7 +434,7 @@ impl Projector {
/// Whether the frame at `time`, at `size`, is what was drawn last (nothing to draw again).
pub(crate) fn drawn(&self, time: f64, size: (u32, u32)) -> bool {
let Some(t) = self.shown.as_ref() else { return true };
- t.shot(time).is_none_or(|at| self.drawn == Some((t.number, at, size)))
+ t.shot(t.frame(time)).is_none_or(|at| self.drawn == Some((t.number, at, size)))
}
/// Draw the frame at `time` of the shown take at `size` (its proportions; a view is
@@ -380,7 +443,7 @@ impl Projector {
/// (`submitted`, then `settle`).
pub(crate) fn encode(&mut self, gpu: &mut Gpu, time: f64, size: (u32, u32)) -> Result<Option<wgpu::CommandEncoder>, String> {
let Some(t) = self.shown.as_mut() else { return Ok(None) };
- let Some(at) = t.shot(time) else { return Ok(None) };
+ let Some(at) = t.shot(t.frame(time)) else { return Ok(None) };
if (t.player.width, t.player.height) != size {
(t.player.width, t.player.height, t.player.targets) = (size.0, size.1, None);
}
@@ -453,7 +516,7 @@ fn resized(views: &[Frame], own: (u32, u32), size: (u32, u32)) -> std::borrow::C
std::borrow::Cow::Owned(views)
}
-#[cfg(test)]
+#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use crate::take::Writer;
@@ -476,6 +539,62 @@ mod tests {
p.shown.as_ref().map(|t| (t.number, t.frames, t.ended))
}
+ #[test]
+ fn a_recording_is_exactly_one_complete_successful_take() {
+ let stream = take(2, Some(false));
+ let recording = Take::read(&stream).unwrap();
+ assert_eq!((recording.size, recording.frames, recording.fps), ((64, 36), 2, 30.0));
+ for end in 0..stream.len() { assert!(Take::read(&stream[..end]).is_err(), "cut at {end}"); }
+ for bad in [take(0, Some(false)), take(2, None), take(2, Some(true)), [stream.clone(), stream].concat()] {
+ assert!(Take::read(&bad).is_err());
+ }
+ }
+
+ #[test]
+ fn an_unsupported_take_is_rejected_before_its_resources_are_read() {
+ let stream = take(2, Some(false));
+ for version in [0, take::VERSION + 1, u32::MAX] {
+ let mut unsupported = stream.clone();
+ unsupported[5..9].copy_from_slice(&version.to_le_bytes());
+ // Split even the length and version fields, as native and browser streams can be.
+ for chunk in [1, 3, unsupported.len()] {
+ let mut projector = Projector::default();
+ let result = unsupported.chunks(chunk).try_for_each(|bytes| projector.feed(bytes).map(|_| ()));
+ assert_eq!(result.unwrap_err(), format!("unsupported take format {version}; this engine reads format {}", take::VERSION));
+ assert!(projector.shown.is_none());
+ }
+ }
+ // The former START had no version, only width, height and fps (17 payload bytes).
+ let legacy = [17u32.to_le_bytes().as_slice(), &[0], &64u32.to_le_bytes(), &36u32.to_le_bytes(), &30f64.to_le_bytes()].concat();
+ let mut projector = Projector::default();
+ assert!(projector.feed(&legacy).err().unwrap().contains("unversioned takes are unsupported"));
+ assert!(projector.shown.is_none());
+ }
+
+ #[test]
+ fn a_recording_seeks_exact_integer_frames_including_holds() {
+ let mut w = Writer::default();
+ w.start(64, 36, 29.97);
+ let mut view = vec![0.0_f32; crate::render::VIEW_LENGTH];
+ view[44] = 0.25;
+ let cameras = vec![(7, 16, 12, bytemuck::cast_slice(&view).to_vec(), Vec::new())];
+ w.frame(bytemuck::cast_slice(&view), &[], 3, &cameras);
+ view[44] = 0.75;
+ w.frame(bytemuck::cast_slice(&view), &[], 2, &cameras);
+ w.close(false);
+ let mut recording = Take::read(&w.drain()).unwrap();
+ assert_eq!(recording.timeline(), [(0, 3), (3, 2)]);
+ for frame in [4, 0, 3, 2, 1, 4] {
+ let views = recording.frame_views(frame).unwrap();
+ assert_eq!(views.len(), 2);
+ assert_eq!((views[0].key, views[0].width, views[0].height), (7, 16, 12));
+ assert_eq!(views[0].view[44], 0.25);
+ assert_eq!(views[1].view[44], if frame < 3 { 0.25 } else { 0.75 });
+ }
+ assert!(recording.frame_views(5).is_err());
+ assert!(recording.frame_views(u32::MAX).is_err());
+ }
+
/// The first take is shown at once; a newer one comes in beside it and replaces it once it
/// has the moment shown — or has ended, shorter.
#[test]
@@ -531,3 +650,93 @@ mod tests {
}
}
}
+
+#[cfg(test)]
+mod decoder_contract {
+ use super::*;
+
+ fn message(op: u8, fields: &[u8]) -> Vec<u8> {
+ [(fields.len() as u32 + 1).to_le_bytes().as_slice(), &[op], fields].concat()
+ }
+ fn start(width: u32, height: u32, fps: f64) -> Vec<u8> {
+ message(take::START, &[take::VERSION.to_le_bytes().as_slice(), &width.to_le_bytes(), &height.to_le_bytes(), &fps.to_le_bytes()].concat())
+ }
+ fn array(key: u64, base: u64, kind: Kind, mode: u8) -> Vec<u8> {
+ [key.to_le_bytes().as_slice(), &base.to_le_bytes(), &[kind as u8, mode], &0u32.to_le_bytes()].concat()
+ }
+ fn frame(repeat: u32) -> Vec<u8> {
+ message(take::FRAME, &[repeat.to_le_bytes().as_slice(), &0u32.to_le_bytes(), &1u64.to_le_bytes(), &0u32.to_le_bytes()].concat())
+ }
+
+ #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
+ #[cfg_attr(not(target_arch = "wasm32"), test)]
+ fn arrays_have_immutable_preceding_bases_of_the_same_kind() {
+ let mut p = Projector::default();
+ p.feed(&start(64, 36, 30.0)).unwrap();
+ p.feed(&message(take::ARRAY, &array(1, 0, Kind::Points, pack::ALONE))).unwrap();
+ for bad in [
+ array(0, 0, Kind::Points, pack::ALONE),
+ array(1, 0, Kind::Points, pack::ALONE),
+ array(2, 2, Kind::Points, pack::FIRST), // self-cycle
+ array(2, 3, Kind::Points, pack::FIRST), // forward reference
+ array(2, 1, Kind::Texture, pack::FIRST),
+ array(2, 1, Kind::Points, pack::ALONE),
+ array(2, 0, Kind::Points, pack::FIRST),
+ array(2, 1, Kind::Points, pack::SECOND), // no grandparent
+ array(2, 1, Kind::Points, 255),
+ ] {
+ assert!(p.feed(&message(take::ARRAY, &bad)).is_err());
+ assert_eq!(p.shown.as_ref().unwrap().pack.arrays.len(), 1);
+ }
+ p.feed(&message(take::ARRAY, &array(2, 1, Kind::Points, pack::FIRST))).unwrap();
+ p.feed(&message(take::ARRAY, &array(3, 2, Kind::Points, pack::SECOND))).unwrap();
+ p.feed(&message(take::END, &[0])).unwrap();
+ p.feed(&message(take::NOTE, &[2u32.to_le_bytes().as_slice(), b"{}"].concat())).unwrap();
+ p.feed(&start(64, 36, 30.0)).unwrap();
+ p.feed(&message(take::ARRAY, &array(1, 0, Kind::Texture, pack::ALONE))).unwrap();
+ assert_eq!(p.shown.as_ref().unwrap().pack.arrays[&1].kind, Kind::Points);
+ assert_eq!(p.coming.as_ref().unwrap().pack.arrays[&1].kind, Kind::Texture);
+ }
+
+ #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
+ #[cfg_attr(not(target_arch = "wasm32"), test)]
+ fn array_dependencies_stop_at_the_writers_keyframe_bound() {
+ let mut pack = Pack::default();
+ for depth in 0..=pack::DEPTH {
+ let mode = if depth == 0 { pack::ALONE } else { pack::FIRST };
+ pack.add(&mut Fields(&array(depth as u64 + 1, depth as u64, Kind::Points, mode))).unwrap();
+ }
+ let deepest = pack::DEPTH as u64 + 1;
+ assert!(pack.add(&mut Fields(&array(deepest + 1, deepest, Kind::Points, pack::FIRST))).is_err());
+ assert_eq!(pack.arrays.len(), deepest as usize);
+ }
+
+ #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
+ #[cfg_attr(not(target_arch = "wasm32"), test)]
+ fn frame_holds_are_positive_checked_and_end_with_the_take() {
+ let mut p = Projector::default();
+ p.feed(&start(64, 36, 30.0)).unwrap();
+ assert!(p.feed(&frame(0)).is_err());
+ assert!(p.shown.as_ref().unwrap().shots.is_empty());
+ p.feed(&frame(u32::MAX)).unwrap();
+ assert!(p.feed(&frame(1)).is_err());
+ let t = p.shown.as_ref().unwrap();
+ assert_eq!((t.frames, t.shots.len()), (u32::MAX, 1));
+ p.feed(&message(take::END, &[0])).unwrap();
+ assert!(p.feed(&frame(1)).is_err());
+ assert!(p.feed(&message(take::ARRAY, &array(1, 0, Kind::Points, pack::ALONE))).is_err());
+ assert_eq!(p.shown.as_ref().unwrap().frames, u32::MAX);
+ }
+
+ #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
+ #[cfg_attr(not(target_arch = "wasm32"), test)]
+ fn invalid_start_does_not_replace_the_live_take() {
+ let mut p = Projector::default();
+ p.feed(&start(64, 36, 30.0)).unwrap();
+ for (width, height, fps) in [(0, 36, 30.0), (64, 0, 30.0), (64, 36, 0.0), (64, 36, -1.0), (64, 36, f64::INFINITY), (64, 36, f64::NAN)] {
+ assert!(p.feed(&start(width, height, fps)).is_err());
+ assert!(p.coming.is_none());
+ assert_eq!((p.takes, p.shown.as_ref().unwrap().size), (1, (64, 36)));
+ }
+ }
+}
diff --git a/rust/engine/src/python.rs b/rust/engine/src/python.rs
index f3ec68e1..6c51ecda 100644
--- a/rust/engine/src/python.rs
+++ b/rust/engine/src/python.rs
@@ -3,7 +3,8 @@
//! over the core in `render`, `take` and `typeset`.
#[cfg(feature = "render")]
-use pyo3::exceptions::{PyRuntimeError, PyValueError};
+use pyo3::exceptions::PyRuntimeError;
+use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::PyBytes;
@@ -14,6 +15,60 @@ use crate::{CameraView, take};
#[cfg(feature = "typeset")]
pyo3::create_exception!(_engine, TypstError, pyo3::exceptions::PyException);
+#[cfg(feature = "render")]
+impl Player {
+ /// The common readback for directly evaluated frames and recorded takes.
+ fn readback<'py>(&mut self, py: Python<'py>, frames: Vec<crate::render::Frame>) -> PyResult<Bound<'py, PyBytes>> {
+ py.detach(|| {
+ with_gpu(|gpu| -> Result<(), String> {
+ // drawn again while its see-through fragments overflow the lists
+ loop {
+ let (mut encoder, _, composited) = self.encode(gpu, &frames)?;
+ let t = self.targets.as_ref().expect("targets");
+ let pixels = t.padded as u64 * self.height as u64;
+ self.copy_pixels(&mut encoder);
+ let lists = self.lists.as_ref().filter(|_| composited);
+ if let Some(lists) = lists {
+ encoder.copy_buffer_to_buffer(&lists.appended, 0, &t.readback, pixels, Some(COUNT_BYTES));
+ }
+ let capacity = lists.map(|l| l.capacity);
+ gpu.queue.submit(Some(encoder.finish()));
+ self.map_pixels(gpu)?;
+ let Some(capacity) = capacity else { return Ok(()) };
+ let appended = count(&t.readback.slice(pixels..).get_mapped_range().map_err(|e| e.to_string())?);
+ if !self.overflowed(gpu, appended, capacity) {
+ return Ok(());
+ }
+ self.targets.as_ref().expect("targets").readback.unmap();
+ }
+ })?
+ })
+ .map_err(PyRuntimeError::new_err)?;
+ self.pixels(py)
+ }
+
+ fn pixels<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
+ let (width, height) = (self.width, self.height);
+ // copied once: from the mapped buffer into the bytes Python gets
+ let t = self.targets.as_ref().expect("targets");
+ let mapped = t.readback.slice(..t.padded as u64 * height as u64).get_mapped_range().map_err(|e| PyRuntimeError::new_err(e.to_string()))?;
+ let row = (width * 4) as usize;
+ let pixels = if t.padded as usize == row {
+ PyBytes::new(py, &mapped)
+ } else {
+ PyBytes::new_with(py, row * height as usize, |out| {
+ for (to, from) in out.chunks_exact_mut(row).zip(mapped.chunks_exact(t.padded as usize)) {
+ to.copy_from_slice(&from[..row]);
+ }
+ Ok(())
+ })?
+ };
+ drop(mapped);
+ t.readback.unmap();
+ Ok(pixels)
+ }
+}
+
#[cfg(feature = "render")]
#[pymethods]
impl Player {
@@ -54,6 +109,11 @@ impl Player {
self.stored()
}
+ #[pyo3(name = "pressured")]
+ fn py_pressured(&self, py: Python<'_>) -> PyResult<bool> {
+ py.detach(|| with_gpu(|gpu| self.pressured(gpu))).map_err(PyRuntimeError::new_err)
+ }
+
#[pyo3(name = "add_rows")]
fn py_add_rows(&mut self, key: u64, rows: &[u8]) -> PyResult<()> {
self.add_rows(key, rows).map_err(PyValueError::new_err)
@@ -75,54 +135,7 @@ impl Player {
#[pyo3(signature = (view, records, cameras = Vec::new()))]
fn render<'py>(&mut self, py: Python<'py>, view: &[u8], records: &[u8], cameras: Vec<CameraView>) -> PyResult<Bound<'py, PyBytes>> {
let frames = self.views(view, records, cameras).map_err(PyValueError::new_err)?;
- let (width, height) = (self.width, self.height);
- py.detach(|| {
- with_gpu(|gpu| -> Result<(), String> {
- // drawn again while its see-through fragments overflow the lists
- loop {
- let (mut encoder, _, composited) = self.encode(gpu, &frames)?;
- let t = self.targets.as_ref().expect("targets");
- let pixels = t.padded as u64 * height as u64;
- encoder.copy_texture_to_buffer(
- wgpu::TexelCopyTextureInfo { texture: t.frame.color.texture(), mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
- wgpu::TexelCopyBufferInfo { buffer: &t.readback, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(t.padded), rows_per_image: Some(height) } },
- wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
- );
- let lists = self.lists.as_ref().filter(|_| composited);
- if let Some(lists) = lists {
- encoder.copy_buffer_to_buffer(&lists.appended, 0, &t.readback, pixels, Some(COUNT_BYTES));
- }
- let capacity = lists.map(|l| l.capacity);
- gpu.queue.submit(Some(encoder.finish()));
- t.readback.slice(..).map_async(wgpu::MapMode::Read, |_| {});
- gpu.device.poll(wgpu::PollType::wait_indefinitely()).map_err(|e| e.to_string())?;
- let Some(capacity) = capacity else { return Ok(()) };
- let appended = count(&t.readback.slice(pixels..).get_mapped_range().map_err(|e| e.to_string())?);
- if !self.overflowed(gpu, appended, capacity) {
- return Ok(());
- }
- self.targets.as_ref().expect("targets").readback.unmap();
- }
- })?
- })
- .map_err(PyRuntimeError::new_err)?;
- // copied once: from the mapped buffer into the bytes Python gets
- let t = self.targets.as_ref().expect("targets");
- let mapped = t.readback.slice(..t.padded as u64 * height as u64).get_mapped_range().map_err(|e| PyRuntimeError::new_err(e.to_string()))?;
- let row = (width * 4) as usize;
- let pixels = if t.padded as usize == row {
- PyBytes::new(py, &mapped)
- } else {
- PyBytes::new_with(py, row * height as usize, |out| {
- for (to, from) in out.chunks_exact_mut(row).zip(mapped.chunks_exact(t.padded as usize)) {
- to.copy_from_slice(&from[..row]);
- }
- Ok(())
- })?
- };
- drop(mapped);
- t.readback.unmap();
- Ok(pixels)
+ self.readback(py, frames)
}
#[cfg(feature = "export")]
@@ -143,10 +156,12 @@ impl Player {
#[cfg(feature = "export")]
/// The next frame of the video, shown for `repeat` frames: a view and its records, with
/// `cameras` drawn first (as for `render`); `key`: a keyframe, where a player can start.
- #[pyo3(signature = (view, records, repeat = 1, cameras = Vec::new(), key = false))]
- fn push(&mut self, py: Python<'_>, view: &[u8], records: &[u8], repeat: u32, cameras: Vec<CameraView>, key: bool) -> PyResult<()> {
+ #[pyo3(signature = (view, records, repeat = 1, cameras = Vec::new(), key = false, capture = false))]
+ #[allow(clippy::too_many_arguments)]
+ fn push<'py>(&mut self, py: Python<'py>, view: &[u8], records: &[u8], repeat: u32, cameras: Vec<CameraView>, key: bool, capture: bool) -> PyResult<Option<Bound<'py, PyBytes>>> {
let frames = self.views(view, records, cameras).map_err(PyValueError::new_err)?;
- py.detach(|| with_gpu(|gpu| self.push_frames(gpu, frames, repeat, key))?).map_err(PyRuntimeError::new_err)
+ py.detach(|| with_gpu(|gpu| self.push_frames(gpu, frames, repeat, key, capture))?).map_err(PyRuntimeError::new_err)?;
+ capture.then(|| self.pixels(py)).transpose()
}
#[cfg(feature = "export")]
@@ -178,6 +193,43 @@ impl Player {
}
}
+/// A complete recorded take, drawn headlessly by the same decoder and player as a window.
+#[cfg(feature = "player")]
+#[pyclass(module = "manimgx._engine", unsendable)]
+struct Replay {
+ take: crate::project::Take,
+}
+
+#[cfg(feature = "player")]
+#[pymethods]
+impl Replay {
+ #[new]
+ fn new(data: &[u8]) -> PyResult<Self> {
+ crate::project::Take::read(data).map(|take| Self { take }).map_err(PyValueError::new_err)
+ }
+
+ #[getter]
+ fn size(&self) -> (u32, u32) { self.take.size }
+
+ #[getter]
+ fn frames(&self) -> u32 { self.take.frames }
+
+ #[getter]
+ fn fps(&self) -> f64 { self.take.fps }
+
+ #[getter]
+ fn timeline(&self) -> Vec<(u32, u32)> { self.take.timeline() }
+
+ /// A zero-based frame, in any order: RGBA8 rows, top to bottom, at the recorded size.
+ fn render<'py>(&mut self, py: Python<'py>, frame: i64) -> PyResult<Bound<'py, PyBytes>> {
+ if frame < 0 || frame >= self.take.frames as i64 {
+ return Err(pyo3::exceptions::PyIndexError::new_err(format!("frame {frame} is outside the take's {} frames", self.take.frames)));
+ }
+ let frames = self.take.frame_views(frame as u32).map_err(PyValueError::new_err)?;
+ self.take.player.readback(py, frames)
+ }
+}
+
/// The content key of some bytes, taken as one stream: xxh3, 64 bits, never 0 (reserved). What
/// names an upload, so that equal content is uploaded once.
#[pyfunction]
@@ -201,7 +253,10 @@ fn read_hdr<'py>(py: Python<'py>, data: &[u8]) -> PyResult<(u32, u32, Bound<'py,
#[pyfunction]
fn decode_audio<'py>(py: Python<'py>, data: Vec<u8>, rate: u32) -> PyResult<(Bound<'py, PyBytes>, usize)> {
let (samples, channels) = py
- .detach(|| crate::audio::decode(data).map(|(s, from, c)| (crate::audio::resample(&s, c, from as f64, rate as f64), c)))
+ .detach(|| {
+ let (samples, from, channels) = crate::audio::decode(data)?;
+ crate::audio::resample(&samples, channels, from as f64, rate as f64).map(|samples| (samples, channels))
+ })
.map_err(pyo3::exceptions::PyValueError::new_err)?;
Ok((PyBytes::new(py, bytemuck::cast_slice(&samples)), channels))
}
@@ -210,7 +265,7 @@ fn decode_audio<'py>(py: Python<'py>, data: Vec<u8>, rate: u32) -> PyResult<(Bou
#[pyfunction]
fn resample_audio<'py>(py: Python<'py>, samples: &[u8], channels: usize, rate: f64, to: f64) -> PyResult<Bound<'py, PyBytes>> {
let input: Vec<f32> = crate::read(samples, "samples").map_err(pyo3::exceptions::PyValueError::new_err)?;
- let out = py.detach(|| crate::audio::resample(&input, channels, rate, to));
+ let out = py.detach(|| crate::audio::resample(&input, channels, rate, to)).map_err(pyo3::exceptions::PyValueError::new_err)?;
Ok(PyBytes::new(py, bytemuck::cast_slice(&out)))
}
@@ -241,8 +296,11 @@ impl Recorder {
#[pyo3(signature = (key, points, uvs, normals, triangles, outline = 0, block = 0))]
#[allow(clippy::too_many_arguments)]
- fn add_mesh(&mut self, key: u64, points: &[u8], uvs: &[u8], normals: &[u8], triangles: &[u8], outline: u32, block: u32) {
- self.writer.mesh(key, points, uvs, normals, triangles, outline, block);
+ fn add_mesh(&mut self, key: u64, points: &[u8], uvs: &[u8], normals: &[u8], triangles: &[u8], outline: u32, block: u32) -> PyResult<()> {
+ crate::check_key(key).map_err(PyValueError::new_err)?;
+ let mesh = crate::mesh::Mesh::new(points, uvs, normals, triangles, outline, block).map_err(PyValueError::new_err)?;
+ self.writer.mesh(key, &mesh);
+ Ok(())
}
fn add_rows(&mut self, key: u64, rows: &[u8]) {
@@ -332,6 +390,11 @@ mod typesetting {
use super::TypstError;
use crate::typeset as core;
+ #[pyfunction]
+ pub(super) fn cache_directory() -> Option<std::path::PathBuf> {
+ core::cache_directory()
+ }
+
/// A typeset document: its rows (float64), its shapes' cubic points, its labelled groups, and
/// whether it needed the system's fonts.
type Layout = (Py<PyBytes>, Vec<Py<PyBytes>>, Vec<(String, Vec<usize>)>, bool);
@@ -421,6 +484,23 @@ fn start_gpu() -> bool {
began
}
+/// The adapter actually used by this engine, after bringing it up if necessary. Diagnostic
+/// consumers can distinguish renderer changes from a different backend, device or driver.
+#[cfg(feature = "player")]
+#[pyfunction]
+fn adapter_info(py: Python<'_>) -> PyResult<std::collections::BTreeMap<String, String>> {
+ let info = py.detach(|| with_gpu(|gpu| gpu.adapter.get_info())).map_err(PyRuntimeError::new_err)?;
+ Ok([
+ ("name", info.name),
+ ("vendor", info.vendor.to_string()),
+ ("device", info.device.to_string()),
+ ("device_type", format!("{:?}", info.device_type)),
+ ("driver", info.driver),
+ ("driver_info", info.driver_info),
+ ("backend", format!("{:?}", info.backend)),
+ ].into_iter().map(|(key, value)| (key.to_string(), value)).collect())
+}
+
/// Waits for the GPU's warm-up, at most 30 s; Python calls it as it exits. Exit unloads the
/// drivers, and must not unload one still starting on the warm-up's thread: lavapipe crashed a
/// process that loaded the engine and exited at once. A forked child has no warm-up to wait for.
@@ -446,6 +526,7 @@ fn window(py: Python<'_>, title: String, time: f64, fonts: Vec<String>) -> PyRes
#[pymodule]
fn _engine(m: &Bound<'_, PyModule>) -> PyResult<()> {
+ m.add("TAKE_VERSION", take::VERSION)?;
#[cfg(feature = "render")]
{
m.add_class::<Player>()?;
@@ -454,6 +535,11 @@ fn _engine(m: &Bound<'_, PyModule>) -> PyResult<()> {
}
#[cfg(feature = "window")]
m.add_function(wrap_pyfunction!(window, m)?)?;
+ #[cfg(feature = "player")]
+ {
+ m.add_class::<Replay>()?;
+ m.add_function(wrap_pyfunction!(adapter_info, m)?)?;
+ }
m.add_class::<Recorder>()?;
m.add_function(wrap_pyfunction!(note, m)?)?;
m.add_function(wrap_pyfunction!(web, m)?)?;
@@ -464,6 +550,7 @@ fn _engine(m: &Bound<'_, PyModule>) -> PyResult<()> {
#[cfg(feature = "typeset")]
{
use typesetting::*;
+ m.add_function(wrap_pyfunction!(cache_directory, m)?)?;
m.add_function(wrap_pyfunction!(typeset, m)?)?;
m.add_function(wrap_pyfunction!(glyph_outlines, m)?)?;
m.add_function(wrap_pyfunction!(ligature_carets, m)?)?;
diff --git a/rust/engine/src/render.rs b/rust/engine/src/render.rs
index e83f4396..55440e0a 100644
--- a/rust/engine/src/render.rs
+++ b/rust/engine/src/render.rs
@@ -24,8 +24,11 @@ use std::ops::Range;
use bytemuck::{Pod, Zeroable};
use wgpu::util::DeviceExt;
-use crate::{CameraView, environment, read};
+use crate::{CameraView, check_key, environment, mesh::Mesh, read};
+#[cfg(windows)]
+#[path = "dxc.rs"]
+mod dxc;
#[path = "bloom.rs"]
mod bloom;
#[cfg(not(target_arch = "wasm32"))]
@@ -41,7 +44,9 @@ mod vector;
pub(crate) const COLOR: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
/// What a 3D view with lit meshes keeps their light in, beside its display paint (`blend.wgsl`'s `Base`).
pub(crate) const RADIANCE: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
-const DEPTH: wgpu::TextureFormat = wgpu::TextureFormat::Depth24PlusStencil8;
+// Reversed Z keeps distant depth differences in a float's significant digits. Depth24Plus
+// may use fixed-point depth, where those differences vanish.
+const DEPTH: wgpu::TextureFormat = wgpu::TextureFormat::Depth32FloatStencil8;
const NONE: u32 = u32::MAX;
const OVERLAY: u64 = 1;
const LIT: u64 = 4;
@@ -175,7 +180,7 @@ struct Shape {
lo: [f32; 3], // bounds of what it draws in its own space (a path's control points: its curves lie within)
hi: [f32; 3],
middle: [f32; 3], // the center of its bounds, by which a 3D view orders it
- plane: [[f32; 3]; 3], // a path's: three points of the plane its control points lie nearest (`plane`)
+ plane: [[f64; 3]; 3], // a path's fitted plane; keep its precision through placement and projection
planar: bool, // a path's control points lie in that plane (a straight path's: on its line)
}
@@ -269,7 +274,7 @@ fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
/// Three points of the plane that points lie nearest (least squares): their mean, and the mean moved by their spread
/// along each of their two widest principal axes. A planar path's plane exactly; a straight path's line (its second
/// spread is none: its third point is its mean). And whether they lie in it (to rounding).
-fn plane(points: &[[f64; 3]]) -> ([[f32; 3]; 3], bool) {
+fn plane(points: &[[f64; 3]]) -> ([[f64; 3]; 3], bool) {
let n = points.len().max(1) as f64;
let mean = [0, 1, 2].map(|i| points.iter().map(|p| p[i]).sum::<f64>() / n);
let mut m = [[0.0f64; 3]; 3];
@@ -304,9 +309,9 @@ fn plane(points: &[[f64; 3]]) -> ([[f32; 3]; 3], bool) {
}
let mut axes = [0, 1, 2];
axes.sort_by(|&a, &b| m[b][b].total_cmp(&m[a][a]));
- let along = |k: usize| [0, 1, 2].map(|i| (mean[i] + m[k][k].max(0.0).sqrt() * v[i][k]) as f32);
+ let along = |k: usize| [0, 1, 2].map(|i| mean[i] + m[k][k].max(0.0).sqrt() * v[i][k]);
let planar = m[axes[2]][axes[2]].max(0.0).sqrt() <= 1e-6 * m[axes[0]][axes[0]].max(0.0).sqrt() + 1e-12;
- ([mean.map(|x| x as f32), along(axes[0]), along(axes[1])], planar)
+ ([mean, along(axes[0]), along(axes[1])], planar)
}
/// The largest second difference of a curve's control points (Wang's D, in its own units).
@@ -371,6 +376,24 @@ impl Store {
self.vertices.len() * VERTEX_BYTES + self.indices.len() * 4 + self.rows.len() * 16 + self.points.len() / 4 * CURVE_BYTES + self.ranges.len() * 16
}
+ /// The arrays sent to the GPU, in binding order (the indices are only an index buffer).
+ fn arrays(&self) -> [&[u8]; 7] {
+ [bytemuck::cast_slice(&self.vertices), bytemuck::cast_slice(&self.links), bytemuck::cast_slice(&self.indices), bytemuck::cast_slice(&self.rows), bytemuck::cast_slice(&self.extras), bytemuck::cast_slice(&self.ctrl), bytemuck::cast_slice(&self.ranges)]
+ }
+
+ fn fits(&self, limits: &wgpu::Limits) -> bool {
+ self.arrays().iter().enumerate().all(|(k, bytes)| bytes.len() as u64 <= store_limit(limits, k))
+ }
+
+ fn rooms(&self, limits: &wgpu::Limits) -> Result<[u64; 7], String> {
+ let arrays = self.arrays();
+ let mut rooms = [0; 7];
+ for (k, name) in ["vertices", "vertex links", "indices", "paint rows", "vertex normals and UVs", "curve points", "subpath ranges"].iter().enumerate() {
+ rooms[k] = buffer_room(arrays[k].len() as u64, 1, 1024, store_limit(limits, k), name)?;
+ }
+ Ok(rooms)
+ }
+
/// The bytes a shape holds in the arrays: a path's curves (with their room), a point cloud's or
/// mesh's vertices and index codes.
#[cfg(any(feature = "python", feature = "player"))]
@@ -391,48 +414,54 @@ impl Store {
}
}
- /// Pack the living once most of the arrays is dead (and there is enough of it to matter).
- fn pack_if_worthwhile(&mut self) {
- if self.dead < 16 << 20 || self.dead * 2 < self.bytes() {
+ /// Pack the living once most of the arrays is dead, or a binding needs the space now.
+ fn pack_if_worthwhile(&mut self, pressed: bool) {
+ if self.dead == 0 || (!pressed && (self.dead < 16 << 20 || self.dead * 2 < self.bytes())) {
return;
}
- let old = std::mem::take(self);
- self.generation = old.generation + 1; // (a path loses its room: it moves when it grows)
- let mut shapes: Vec<(&u64, &Shape)> = old.shapes.iter().collect();
+ *self = self.packed(|_| true);
+ }
+
+ /// A stable packing of selected resources; keys remain logical, offsets belong to this store.
+ fn packed(&self, keep: impl Fn(u64) -> bool) -> Self {
+ let old = self;
+ let mut packed = Self { generation: old.generation + 1, ..Default::default() };
+ let mut shapes: Vec<(&u64, &Shape)> = old.shapes.iter().filter(|(key, _)| keep(**key)).collect();
shapes.sort_by_key(|(_, s)| (s.curves.first, s.base)); // keep their order: packing is a stable move
for (&key, s) in shapes {
let mut shape = Shape { base: 0, count: 0, raster: Raster::default(), ..*s };
if s.kind == Kind::Path {
let c = s.curves;
let (a, b) = (4 * c.first as usize, 4 * (c.first + c.count) as usize);
- let first = self.push_curves(&old.points[a..b], c.count as usize);
- let first_subpath = self.ranges.len() as u32;
- self.ranges.extend_from_slice(&old.ranges[c.first_subpath as usize..(c.first_subpath + c.subpaths) as usize]);
+ let first = packed.push_curves(&old.points[a..b], c.count as usize);
+ let first_subpath = packed.ranges.len() as u32;
+ packed.ranges.extend_from_slice(&old.ranges[c.first_subpath as usize..(c.first_subpath + c.subpaths) as usize]);
shape.curves = Curves { first, room: c.count, first_subpath, ..c };
} else {
let (a, b) = (s.base as usize, (s.base + s.count) as usize);
- let base = self.push_vertices(&old.vertices[a..b], Some(&old.extras[a..b]));
+ let base = packed.push_vertices(&old.vertices[a..b], Some(&old.extras[a..b]));
let moved = |v: u32| v - s.base + base;
let r = &s.raster;
let linked = s.kind == Kind::Mesh && !r.stroke.is_empty();
- self.links.extend(old.links[a..b].iter().map(|l| if linked { [moved(l[0]), moved(l[1])] } else { [0, 0] }));
- let fill_start = self.indices.len() as u32;
- self.indices.extend(old.indices[r.fill.start as usize..r.fill.end as usize].iter().map(|&i| moved(i)));
- let stroke_start = self.indices.len() as u32;
- self.indices.extend(old.indices[r.stroke.start as usize..r.stroke.end as usize].iter().map(|&code| (moved(code >> 3) << 3) | (code & 7)));
- let end = self.indices.len() as u32;
+ packed.links.extend(old.links[a..b].iter().map(|l| if linked { [moved(l[0]), moved(l[1])] } else { [0, 0] }));
+ let fill_start = packed.indices.len() as u32;
+ packed.indices.extend(old.indices[r.fill.start as usize..r.fill.end as usize].iter().map(|&i| moved(i)));
+ let stroke_start = packed.indices.len() as u32;
+ packed.indices.extend(old.indices[r.stroke.start as usize..r.stroke.end as usize].iter().map(|&code| (moved(code >> 3) << 3) | (code & 7)));
+ let end = packed.indices.len() as u32;
let raster = Raster { count: r.count, fill: fill_start..stroke_start, stroke: stroke_start..end };
shape = Shape { base, count: s.count, raster, ..shape };
}
- self.shapes.insert(key, shape);
+ packed.shapes.insert(key, shape);
}
- let mut brushes: Vec<(&u64, &Brush)> = old.brushes.iter().collect();
+ let mut brushes: Vec<(&u64, &Brush)> = old.brushes.iter().filter(|(key, _)| keep(**key)).collect();
brushes.sort_by_key(|(_, b)| b.offset);
for (&key, b) in brushes {
- let offset = self.rows.len() as u32;
- self.rows.extend_from_slice(&old.rows[b.offset as usize..(b.offset + b.count) as usize]);
- self.brushes.insert(key, Brush { offset, count: b.count, see_through: b.see_through });
+ let offset = packed.rows.len() as u32;
+ packed.rows.extend_from_slice(&old.rows[b.offset as usize..(b.offset + b.count) as usize]);
+ packed.brushes.insert(key, Brush { offset, count: b.count, see_through: b.see_through });
}
+ packed
}
/// A path: its control points (four per curve) and subpaths (its own curve ranges: first, end,
@@ -945,7 +974,7 @@ struct Pipelines {
points: wgpu::RenderPipeline,
sprites: wgpu::RenderPipeline, // a 3D view's see-through points, blended in the order listed
mesh: wgpu::RenderPipeline,
- appends: Option<Appends>, // with more than one sample
+ appends: Appends,
}
/// A 3D view's listed see-through layers, each appending its fragments to the lists once (see
@@ -979,7 +1008,7 @@ pub(crate) struct Gpu {
occlusion: Option<occlusion::Occlusion>, // a 3D view's ambient occlusion's passes, made when a view first has it
no_occlusion: wgpu::TextureView, // what a view without it binds in its place: 1x1
bloom: Option<bloom::Bloom>, // a 3D view's bloom's passes, made when a view first has it
- blend: Option<wgpu::ShaderModule>, // the raster pipeline's shader, once made (for the shadow passes too)
+ blend: [Option<wgpu::ShaderModule>; 2], // single/multisample texture forms (the shadow passes share either)
shadow_passes: HashMap<usize, wgpu::RenderPipeline>, // by the light's slot in its view, made when first cast
}
@@ -1012,6 +1041,13 @@ fn shader(device: &wgpu::Device, label: &str, source: &str) -> wgpu::ShaderModul
device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) })
}
+/// One compositing algorithm; only its texture types differ at one sample. `textureLoad`'s
+/// last argument then names mip zero instead of sample zero.
+fn sampled_shader(device: &wgpu::Device, label: &str, source: &str, multisampled: bool) -> wgpu::ShaderModule {
+ let kind = if multisampled { "multisampled_2d" } else { "2d" };
+ shader(device, label, &format!("alias SampleColor = texture_{kind}<f32>;\nalias SampleDepth = texture_depth_{kind};\n{source}"))
+}
+
fn entry(binding: u32, ty: wgpu::BindingType) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT, ty, count: None }
}
@@ -1020,8 +1056,8 @@ fn storage(binding: u32) -> wgpu::BindGroupLayoutEntry {
entry(binding, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: true }, has_dynamic_offset: false, min_binding_size: None })
}
-/// How a pass uses the stencil: count a stroke's coverage, cover once where counted (zeroing it,
-/// even where depth rejects), or leave it alone.
+/// How a pass uses the stencil: count a stroke's coverage, cover once where visible (zeroing it
+/// only when depth passes), or leave it alone.
#[derive(Clone, Copy)]
enum Stencil {
Coverage,
@@ -1035,8 +1071,8 @@ pub(crate) fn blends_float32(adapter: &wgpu::Adapter) -> bool {
adapter.get_texture_format_features(wgpu::TextureFormat::R32Float).flags.contains(wgpu::TextureFormatFeatureFlags::BLENDABLE)
}
-/// An instance's high-performance adapter, which must blend float32 targets (a view adds its
-/// coverage in one).
+/// An instance's high-performance adapter: float32 coverage blending and floating-point depth
+/// with stencil, which its reversed-Z projection and stroke coverage require.
async fn adapter(instance: &wgpu::Instance) -> Result<wgpu::Adapter, String> {
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() })
@@ -1048,6 +1084,9 @@ async fn adapter(instance: &wgpu::Instance) -> Result<wgpu::Adapter, String> {
if !blends_float32(&adapter) {
return Err("the GPU cannot blend float32 targets (a view adds its coverage in one)".into());
}
+ if !adapter.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
+ return Err("the GPU cannot use float32 depth with stencil (reversed-Z depth needs floating-point precision)".into());
+ }
Ok(adapter)
}
@@ -1055,7 +1094,13 @@ impl Gpu {
/// The system's GPU, WebGPU's (Metal, Vulkan, DX12, the browser's): its device, and what draws on it.
pub(crate) async fn new() -> Result<Self, String> {
// the system's adapter; where none will do, the lavapipe a Linux wheel bundles
- let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { backends: wgpu::Backends::PRIMARY, ..wgpu::InstanceDescriptor::new_without_display_handle() });
+ let descriptor = wgpu::InstanceDescriptor { backends: wgpu::Backends::PRIMARY, ..wgpu::InstanceDescriptor::new_without_display_handle() };
+ #[cfg(windows)]
+ let descriptor = wgpu::InstanceDescriptor {
+ backend_options: wgpu::BackendOptions { dx12: wgpu::Dx12BackendOptions { shader_compiler: dxc::compiler()?, ..Default::default() }, ..descriptor.backend_options },
+ ..descriptor
+ };
+ let instance = wgpu::Instance::new(descriptor);
#[cfg(target_arch = "wasm32")]
let adapter = adapter(&instance).await?;
#[cfg(not(target_arch = "wasm32"))]
@@ -1074,7 +1119,7 @@ impl Gpu {
#[cfg(not(feature = "player"))]
drop(instance);
let specific = wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES;
- let required_features = adapter.features() & (specific | wgpu::Features::FLOAT32_BLENDABLE);
+ let required_features = (adapter.features() & (specific | wgpu::Features::FLOAT32_BLENDABLE)) | wgpu::Features::DEPTH32FLOAT_STENCIL8;
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: Some("manimgx"),
@@ -1118,9 +1163,10 @@ impl Gpu {
let shadows = layout("lighting", &[maps, compare, dfg, linear, cube, occlusion]);
// the scene's arrays; a 3D view's see-through lists, written (with the opaque depth), and its slab bounds
let written = |binding| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: false }, has_dynamic_offset: false, min_binding_size: None }, count: None };
- let depth = entry(3, wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Depth, view_dimension: wgpu::TextureViewDimension::D2, multisampled: true });
+ let depth = [false, true].map(|multisampled| entry(3, wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Depth, view_dimension: wgpu::TextureViewDimension::D2, multisampled }));
let bounds = entry(0, wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: false }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false });
- let (lists, slabs) = (layout("append", &[written(0), written(1), written(2), depth]), [layout("slab bounds", &[bounds]), layout("slab bounds and depth", &[bounds, depth])]);
+ let lists = depth.map(|depth| layout("append", &[written(0), written(1), written(2), depth]));
+ let slabs = depth.map(|depth| [layout("slab bounds", &[bounds]), layout("slab bounds and depth", &[bounds, depth])]);
let raster = RasterLayouts { scene: layout("scene", &[view, storage(1), storage(2), storage(4), storage(5), storage(6), storage(7)]), lists, slabs, shadows };
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("image"),
@@ -1153,7 +1199,7 @@ impl Gpu {
instance,
#[cfg(feature = "player")]
adapter,
- device, queue, raster, image_layout, sampler, pipelines: HashMap::new(), max_samples, vector, shadow_compare, dfg, linear, no_environment, prefilter: None, occlusion: None, no_occlusion, bloom: None, blend: None, shadow_passes: HashMap::new() })
+ device, queue, raster, image_layout, sampler, pipelines: HashMap::new(), max_samples, vector, shadow_compare, dfg, linear, no_environment, prefilter: None, occlusion: None, no_occlusion, bloom: None, blend: [None, None], shadow_passes: HashMap::new() })
}
/// The raster pipeline's passes at `samples`, made when a view first draws rasters with them.
@@ -1168,7 +1214,8 @@ impl Gpu {
// the body, and its reads: from storage buffers, with the see-through lists
let raster = &self.raster;
let parts = [include_str!("blend.wgsl"), include_str!("light.wgsl"), include_str!("blend_buffers.wgsl"), include_str!("blend_lists.wgsl")].concat();
- let shader = self.blend.get_or_insert_with(|| shader(device, "blend", &parts)).clone();
+ let kind = (samples > 1) as usize;
+ let shader = self.blend[kind].get_or_insert_with(|| sampled_shader(device, "blend", &parts, samples > 1)).clone();
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&raster.scene), Some(&self.image_layout), None, Some(&raster.shadows)], immediate_size: 0 });
let face = |compare, pass_op, depth_fail_op| wgpu::StencilFaceState { compare, fail_op: Op::Keep, depth_fail_op, pass_op };
// a view with lit meshes: two targets, its display paint and its light (`blend.wgsl`'s `Base`), each fragment
@@ -1189,7 +1236,7 @@ impl Gpu {
let p = |vs: &str, fs: Option<&str>, stencil: Stencil, write: bool, color: bool| {
let (front, back) = match stencil {
Stencil::Coverage => (face(C::Always, Op::IncrementClamp, Op::Keep), face(C::Always, Op::IncrementClamp, Op::Keep)),
- Stencil::Cover => (face(C::NotEqual, Op::Zero, Op::Zero), face(C::NotEqual, Op::Zero, Op::Zero)),
+ Stencil::Cover => (face(C::NotEqual, Op::Zero, Op::Keep), face(C::NotEqual, Op::Zero, Op::Keep)),
Stencil::Ignore => (face(C::Always, Op::Keep, Op::Keep), face(C::Always, Op::Keep, Op::Keep)),
};
let targets = targets_for(if color { wgpu::ColorWrites::ALL } else { wgpu::ColorWrites::empty() });
@@ -1215,7 +1262,7 @@ impl Gpu {
})
};
let stroke = |vs, fs| Passes {
- count: p(vs, Some("fs_none"), Stencil::Coverage, false, false),
+ count: p(vs, Some("fs_none"), Stencil::Coverage, true, false),
cover: p(vs, Some(fs), Stencil::Cover, true, true),
};
// the see-through layers' appends test the opaque depth themselves (read-only here) and
@@ -1237,15 +1284,15 @@ impl Gpu {
cache: None,
})
};
- let appends = (samples > 1).then(|| {
- let (append, based) = (group_layout(&raster.lists), group_layout(&raster.slabs[0]));
+ let appends = {
+ let (append, based) = (group_layout(&raster.lists[kind]), group_layout(&raster.slabs[kind][0]));
let appended = |vs: &str, fs: &str| compositing(&append, vs, fs, false, C::Always);
// the slabs, a target each, over the share of each pixel's samples in front of the opaque depth (their
// pass tests it, on a single sample)
let slab = Some(wgpu::ColorTargetState { format: COLOR, blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), write_mask: wgpu::ColorWrites::ALL });
let slabs = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("fs_sprites_slabs"),
- layout: Some(&device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&raster.scene), None, Some(&raster.slabs[1])], immediate_size: 0 })),
+ layout: Some(&device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&raster.scene), None, Some(&raster.slabs[kind][1])], immediate_size: 0 })),
vertex: wgpu::VertexState { module: &shader, entry_point: Some("vs_sprites"), compilation_options: Default::default(), buffers: &[] },
fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some("fs_sprites_slabs"), compilation_options: Default::default(), targets: &vec![slab; vector::SLABS] }),
primitive: wgpu::PrimitiveState::default(),
@@ -1260,7 +1307,7 @@ impl Gpu {
sprites: compositing(&based, "vs_sprites", "fs_sprites_base", true, C::GreaterEqual),
slabs,
}
- });
+ };
let pipelines = Pipelines {
stroke: [stroke("vs_stroke", "fs_stroke"), stroke("vs_stroke", "fs_stroke_gradient")],
points: p("vs_points", Some("fs_points"), Stencil::Ignore, true, true),
@@ -1275,7 +1322,7 @@ impl Gpu {
/// raster pipeline's shader is made by then).
fn shadow_pass(&mut self, slot: usize) -> &wgpu::RenderPipeline {
let (device, raster) = (&self.device, &self.raster);
- let shader = self.blend.as_ref().expect("the raster pipeline's shader");
+ let shader = self.blend.iter().flatten().next().expect("the raster pipeline's shader");
self.shadow_passes.entry(slot).or_insert_with(|| {
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&raster.scene)], immediate_size: 0 });
let constants = [("shadow_light", slot as f64)];
@@ -1383,8 +1430,8 @@ enum Depth {
/// opaque depth) and its slab bounds (as its sprites read them: into the base; into the slabs, with the opaque depth).
struct RasterLayouts {
scene: wgpu::BindGroupLayout,
- lists: wgpu::BindGroupLayout,
- slabs: [wgpu::BindGroupLayout; 2],
+ lists: [wgpu::BindGroupLayout; 2],
+ slabs: [[wgpu::BindGroupLayout; 2]; 2],
shadows: wgpu::BindGroupLayout, // what the lit passes read: the shadow maps and their comparison, the DFG table
}
@@ -1427,7 +1474,7 @@ impl Canvas {
}
/// Give it a 3D view's slabs (once; it has the raster pipeline's attachments).
- fn attach_slabs(&mut self, gpu: &Gpu) {
+ fn attach_slabs(&mut self, gpu: &Gpu, samples: u32) {
let attached = self.raster.as_mut().expect("the raster pipeline's attachments");
if attached.slabs.is_some() {
return;
@@ -1440,7 +1487,8 @@ impl Canvas {
let read = wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&bounds) };
let depth = wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&attached.depth_only) };
let group = |layout, entries: &[wgpu::BindGroupEntry]| gpu.device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("slab bounds"), layout, entries });
- let groups = [group(&gpu.raster.slabs[0], std::slice::from_ref(&read)), group(&gpu.raster.slabs[1], &[read, depth])];
+ let layouts = &gpu.raster.slabs[(samples > 1) as usize];
+ let groups = [group(&layouts[0], std::slice::from_ref(&read)), group(&layouts[1], &[read, depth])];
let slabs = slabs.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() });
attached.slabs = Some(Slabs { bounds, layers, slabs, groups });
}
@@ -1489,9 +1537,9 @@ impl Canvas {
pub(crate) struct Targets {
pub(crate) frame: Canvas,
- #[cfg(feature = "python")]
+ #[cfg(any(feature = "python", feature = "export"))]
pub(crate) readback: wgpu::Buffer, // the frame's pixels, then the lists' count (see `Lists`)
- #[cfg(feature = "python")]
+ #[cfg(any(feature = "python", feature = "export"))]
pub(crate) padded: u32,
}
@@ -1703,6 +1751,18 @@ fn whole(binding: u32, buffer: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {
wgpu::BindGroupEntry { binding, resource: buffer.as_entire_binding() }
}
+fn store_limit(limits: &wgpu::Limits, array: usize) -> u64 {
+ if array == 2 { limits.max_buffer_size } else { limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) }
+}
+
+/// Geometric growth may use spare space, but a binding can never expose more than its limit.
+fn buffer_room(needed: u64, stride: u64, minimum: u64, limit: u64, name: &str) -> Result<u64, String> {
+ if needed > limit / stride {
+ return Err(format!("resident {name} requires {} bytes; the GPU's buffer limit is {limit} bytes", needed.saturating_mul(stride)));
+ }
+ Ok(needed.max(minimum).next_power_of_two().min(limit / stride))
+}
+
/// Draw object `k`'s `range` with `pipeline` (set only when it changes).
fn run(pass: &mut wgpu::RenderPass, current: &mut *const wgpu::RenderPipeline, pipeline: &wgpu::RenderPipeline, range: &Range<u32>, k: u32) {
if !std::ptr::eq(*current, pipeline) {
@@ -1713,26 +1773,42 @@ fn run(pass: &mut wgpu::RenderPass, current: &mut *const wgpu::RenderPipeline, p
}
impl Player {
+ /// Copy the drawn frame's full-quality RGBA rows, independently of video conversion.
+ #[cfg(any(feature = "python", feature = "export"))]
+ pub(crate) fn copy_pixels(&self, encoder: &mut wgpu::CommandEncoder) {
+ let t = self.targets.as_ref().expect("targets");
+ encoder.copy_texture_to_buffer(
+ wgpu::TexelCopyTextureInfo { texture: t.frame.color.texture(), mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
+ wgpu::TexelCopyBufferInfo { buffer: &t.readback, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(t.padded), rows_per_image: Some(self.height) } },
+ wgpu::Extent3d { width: self.width, height: self.height, depth_or_array_layers: 1 },
+ );
+ }
+
+ #[cfg(any(feature = "python", feature = "export"))]
+ pub(crate) fn map_pixels(&self, gpu: &Gpu) -> Result<(), String> {
+ self.targets.as_ref().expect("targets").readback.slice(..).map_async(wgpu::MapMode::Read, |_| {});
+ gpu.device.poll(wgpu::PollType::wait_indefinitely()).map_err(|e| e.to_string())?;
+ Ok(())
+ }
+
/// Bring the GPU up to date: images made textures, the store's arrays sent — only what was
/// appended since last time; everything when they were packed or outgrew their buffers — and
/// room for `count` instances, `views` views and `sprites` sprites.
- fn prepare(&mut self, gpu: &Gpu, count: usize, views: usize, sprites: usize) {
+ fn prepare(&mut self, gpu: &Gpu, count: usize, views: usize, sprites: usize) -> Result<(), String> {
let device = &gpu.device;
+ let limits = device.limits();
for (key, (w, h, rgba)) in self.images.drain() {
self.image_groups.insert(key, gpu.image_group(w, h, &rgba));
}
self.image_groups.entry(0).or_insert_with(|| gpu.image_group(1, 1, &[255, 255, 255, 255]));
+ let rooms = self.store.rooms(&limits)?;
+ let capacity = buffer_room(count as u64, size_of::<Instance>() as u64, 1024, store_limit(&limits, 0), "instances")? as usize;
+ let room = buffer_room(sprites as u64, size_of::<[u32; 2]>() as u64, 1024, store_limit(&limits, 0), "sprites")? as usize;
+ let slots = buffer_room(views as u64, VIEW_STRIDE as u64, 4, limits.max_buffer_size, "views")? as usize;
+ // A rejected frame must leave pending in-place writes available for the next one.
let dirty = std::mem::take(&mut self.store.dirty);
let s = &self.store;
- let arrays: [&[u8]; 7] = [
- bytemuck::cast_slice(&s.vertices),
- bytemuck::cast_slice(&s.links),
- bytemuck::cast_slice(&s.indices),
- bytemuck::cast_slice(&s.rows),
- bytemuck::cast_slice(&s.extras),
- bytemuck::cast_slice(&s.ctrl),
- bytemuck::cast_slice(&s.ranges),
- ];
+ let arrays = s.arrays();
// (the passes read them as storage buffers; the indices are an index buffer too)
let storage = wgpu::BufferUsages::STORAGE;
let buffer = |size: u64| device.create_buffer(&wgpu::BufferDescriptor { label: Some("store"), size, usage: storage | wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
@@ -1741,7 +1817,6 @@ impl Player {
let sprite_buffer = |room: usize| device.create_buffer(&wgpu::BufferDescriptor { label: Some("sprites"), size: (room * size_of::<[u32; 2]>()) as u64, usage: storage | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
let mut rebind = false;
let buffers = self.buffers.get_or_insert_with(|| {
- let (slots, capacity, room) = (views.max(4).next_power_of_two(), count.max(1024).next_power_of_two(), sprites.max(1024).next_power_of_two());
let (views, instances, sprites, statics) = (view_buffer(slots), instances(capacity), sprite_buffer(room), [(); 7].map(|_| buffer(1024)));
rebind = true;
let shadow_maps = ShadowMaps::new(gpu, 1, 1, (None, &gpu.no_environment));
@@ -1758,7 +1833,7 @@ impl Player {
}
for (k, bytes) in arrays.iter().enumerate() {
if bytes.len() as u64 > buffers.sizes[k] {
- buffers.sizes[k] = (bytes.len() as u64).next_power_of_two();
+ buffers.sizes[k] = rooms[k];
buffers.statics[k] = buffer(buffers.sizes[k]);
buffers.sent[k] = 0;
rebind = true;
@@ -1769,41 +1844,42 @@ impl Player {
}
}
if buffers.capacity < count {
- buffers.capacity = count.next_power_of_two();
+ buffers.capacity = capacity;
buffers.instances = instances(buffers.capacity);
rebind = true;
}
if buffers.slots < views {
- buffers.slots = views.next_power_of_two();
+ buffers.slots = slots;
buffers.views = view_buffer(buffers.slots);
rebind = true;
}
if buffers.room < sprites {
- buffers.room = sprites.next_power_of_two();
+ buffers.room = room;
buffers.sprites = sprite_buffer(buffers.room);
rebind = true;
}
if rebind {
buffers.group = Some(scene_group(gpu, buffers));
}
+ Ok(())
}
pub(crate) fn targets(&mut self, gpu: &Gpu) -> &Targets {
let (width, height) = (self.width, self.height);
self.targets.get_or_insert_with(|| {
- #[cfg(feature = "python")]
+ #[cfg(any(feature = "python", feature = "export"))]
let padded = (width * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
Targets {
frame: Canvas::new(gpu, width, height),
// read back natively (`render`); in the browser a frame goes to its canvas
- #[cfg(feature = "python")]
+ #[cfg(any(feature = "python", feature = "export"))]
readback: gpu.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("readback"),
size: (padded * height) as u64 + COUNT_BYTES,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
}),
- #[cfg(feature = "python")]
+ #[cfg(any(feature = "python", feature = "export"))]
padded,
}
})
@@ -1903,8 +1979,8 @@ impl Player {
};
// which passes change pixels
let (fill, stroke) = a.raster.shown([r.params[0], r.params[1]]); // (a path has no raster form: nothing)
- // a mesh's faces' edges blend and write depth once per pixel, by the stencil: even opaque,
- // where blending twice is invisible, the first fragment's depth must be the one kept
+ // a mesh's edges first find their nearest covered depth, then blend once per sample:
+ // a hidden ribbon cannot consume another ribbon's visible coverage
let stroked = a.kind == Kind::Mesh && !stroke.is_empty() && r.params[2] > 0.0 && (paint.stroke[3] > 0.0 || many_stroke);
// a layer can be seen through where its color is, or a row of its brushes (a tween's
// either paint); a textured mesh also where its picture can be
@@ -1959,7 +2035,29 @@ impl Player {
/// composited in more than one group (its objects overflowed the atlases), and whether a 3D
/// view composited see-through layers through the lists (whose count tells if they held).
pub(crate) fn encode(&mut self, gpu: &mut Gpu, frames: &[Frame]) -> Result<(wgpu::CommandEncoder, bool, bool), String> {
- self.store.pack_if_worthwhile(); // before anything reads where a shape is
+ self.with_working_set(&gpu.device.limits(), frames, |player| player.encode_frame(gpu, frames))
+ }
+
+ /// CPU residency includes nearby frames. Only the complete current frame must fit on the GPU.
+ /// A temporary packing never evicts logical keys, consumes their pending writes, or leaks its
+ /// offsets into the resident store; even a failed encoding restores that store unchanged.
+ fn with_working_set<T>(&mut self, limits: &wgpu::Limits, frames: &[Frame], draw: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {
+ self.store.pack_if_worthwhile(!self.store.fits(limits));
+ if self.store.fits(limits) {
+ return draw(self);
+ }
+ let used: Keyed<()> = frames.iter().flat_map(|f| crate::take::slots(bytemuck::cast_slice(&f.records))).flatten().map(|key| (key, ())).collect();
+ let working = self.store.packed(|key| used.contains_key(&key));
+ working.rooms(limits)?;
+ let resident = std::mem::replace(&mut self.store, working);
+ let result = draw(self);
+ let generation = self.store.generation + 1;
+ self.store = resident;
+ self.store.generation = generation; // the next GPU upload cannot reuse temporary offsets
+ result
+ }
+
+ fn encode_frame(&mut self, gpu: &mut Gpu, frames: &[Frame]) -> Result<(wgpu::CommandEncoder, bool, bool), String> {
let samples = self.samples.clamp(1, gpu.max_samples);
let mut instances: Vec<Instance> = Vec::new();
let mut sprites: Vec<[u32; 2]> = Vec::new();
@@ -1977,7 +2075,7 @@ impl Player {
}
let camera = Camera::new(&f.view);
let drawing = if camera.three_d {
- // its paths are exact vector layers over the raster base (its meshes and points), depth tested
+ // its paths are analytic vector layers over the raster base (its meshes and points), depth tested
// against it; everything else is the base
let order = self.order(&camera, &f.records)?;
let path = |k: &usize| self.store.shapes.get(&f.records[*k].key1).is_some_and(|s| s.kind == Kind::Path);
@@ -2033,14 +2131,11 @@ impl Player {
[x0, y0, x1 - x0, y1 - y0]
};
let listed = pixels(listed);
- // its see-through points are sprites, unless the listed layers need lists it
- // cannot have (one sample): then everything is drawn as given
- let at = sprites.len() as u32;
- let sprites_here = if samples > 1 || !draws.iter().any(Draw::listed) { self.sprites(&instances[offset as usize..], &draws, offset, &mut sprites) } else { at..at };
- // its listed layers are composited per pixel, in depth order, through the lists (with multisamples),
- // by its composite; and among them and its paths in the scene, its sprites, through slabs
- let lists = samples > 1 && draws.iter().any(Draw::listed);
- let slabs = samples > 1 && !sprites_here.is_empty() && (lists || !casting.is_empty());
+ // Transparency has the same depth ordering at every sample count. Point sprites
+ // blend between the other layers through slabs; mesh fragments use lists.
+ let sprites_here = self.sprites(&instances[offset as usize..], &draws, offset, &mut sprites);
+ let lists = draws.iter().any(Draw::listed);
+ let slabs = !sprites_here.is_empty() && (lists || !casting.is_empty());
// its lit meshes' light, kept apart from its paint in its base and shown once by its composite (a
// camera's integration of what is lit)
let light = draws.iter().any(|d| d.lit && !d.overlay);
@@ -2092,7 +2187,7 @@ impl Player {
}
}
}
- self.prepare(gpu, instances.len(), frames.len(), sprites.len());
+ self.prepare(gpu, instances.len(), frames.len(), sprites.len())?;
self.targets(gpu);
for f in &frames[..frames.len() - 1] {
self.canvas(gpu, f.key, f.width, f.height);
@@ -2106,11 +2201,11 @@ impl Player {
let canvas = if f.key == 0 { &mut self.targets.as_mut().expect("targets").frame } else { self.canvases.get_mut(&f.key).expect("canvas") };
canvas.attach(gpu, samples, *light);
if *slabs {
- canvas.attach_slabs(gpu);
+ canvas.attach_slabs(gpu, samples);
}
// and where its ambient occlusion is found, if it has some
if occlusion_of(&f.view).is_some() && canvas.occluded.is_none() {
- let occlusion = gpu.occlusion.get_or_insert_with(|| occlusion::Occlusion::new(&gpu.device, gpu.blend.as_ref().expect("the raster pipeline's shader"), &gpu.raster.scene));
+ let occlusion = gpu.occlusion.get_or_insert_with(|| occlusion::Occlusion::new(&gpu.device, gpu.blend[(samples > 1) as usize].as_ref().expect("the raster pipeline's shader"), &gpu.raster.scene));
canvas.occluded = Some(occlusion.occluded(&gpu.device, [canvas.width, canvas.height]));
}
// and where its glow is made, if it has some
@@ -2141,7 +2236,7 @@ impl Player {
if attached.append.as_ref().is_none_or(|(generation, _)| *generation != lists.generation) {
let group = gpu.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("append"),
- layout: &gpu.raster.lists,
+ layout: &gpu.raster.lists[(samples > 1) as usize],
entries: &[whole(0, &lists.heads), whole(1, &lists.nodes), whole(2, &lists.appended), wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&attached.depth_only) }],
});
attached.append = Some((lists.generation, group));
@@ -2302,7 +2397,7 @@ impl Player {
gpu.bloom.as_ref().expect("the bloom's passes").encode(&gpu.queue, encoder, b, strength, tone);
}
};
- let (Some(appends), true) = (pipelines.appends.as_ref(), *listing || *slabs) else {
+ if !(*listing || *slabs) {
if rasterized || plan.is_none() {
let mut pass = canvas.pass(&mut encoder, Some((cleared, true)), if plan.is_some() { Depth::Kept } else { Depth::Fresh }, base.as_ref(), base_light.as_ref());
pass.set_bind_group(0, buffers.group.as_ref(), &slot);
@@ -2322,7 +2417,8 @@ impl Player {
}
layered(&mut encoder, &mut gpu.vector, None, None);
continue;
- };
+ }
+ let appends = &pipelines.appends;
// the opaque layers, their samples and depth kept
{
let mut pass = canvas.pass(&mut encoder, Some((cleared, false)), Depth::Kept, base.as_ref(), base_light.as_ref());
@@ -2331,9 +2427,9 @@ impl Player {
self.draw(&mut pass, pipelines, indices, draws, *offset, Phase::Opaque);
}
let attached = canvas.raster.as_ref().expect("the raster pipeline's attachments");
- let colors = attached.msaa.as_ref().expect("multisamples");
+ let colors = attached.msaa.as_ref().or(base.as_ref()).expect("base samples");
let [_, y, _, h] = *listed;
- let listed = lists.filter(|_| *listing).map(|l| vector::Listed { heads: &l.heads, nodes: &l.nodes, rows: [y, y + h], samples, colors, depths: &attached.depth_only, lights: attached.msaa_light.as_ref() });
+ let listed = lists.filter(|_| *listing).map(|l| vector::Listed { heads: &l.heads, nodes: &l.nodes, rows: [y, y + h], samples, colors, depths: &attached.depth_only, lights: attached.msaa_light.as_ref().or(base_light.as_ref()) });
// the listed see-through layers appended to the lists (only in their rows are heads cleared and read)
if let Some(l) = &listed {
let row = canvas.width as u64 * 4;
@@ -2439,7 +2535,7 @@ impl Player {
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_stencil_reference(0);
let mut current: *const wgpu::RenderPipeline = std::ptr::null();
- let appends = pipelines.appends.as_ref().filter(|_| phase == Phase::SeeThrough);
+ let appends = (phase == Phase::SeeThrough).then_some(&pipelines.appends);
for (k, draw) in draws.iter().enumerate() {
if phase != Phase::All && draw.overlay != (phase == Phase::Overlay) {
continue;
@@ -2495,36 +2591,6 @@ impl Player {
}
}
-/// Area-weighted vertex normals: each triangle's (b − a) × (c − a) added to its corners — every
-/// triangle's first corner, then every second, then every third, so that each vertex sums its
-/// faces in one fixed order.
-fn smooth_normals(p: &[[f64; 3]], triangles: &[u32]) -> Vec<[f64; 3]> {
- let faces: Vec<[f64; 3]> = triangles
- .chunks_exact(3)
- .map(|t| {
- let (a, b, c) = (p[t[0] as usize], p[t[1] as usize], p[t[2] as usize]);
- let (u, w) = ([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]);
- [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]]
- })
- .collect();
- let mut out = vec![[0.0f64; 3]; p.len()];
- for k in 0..3 {
- for (t, f) in triangles.chunks_exact(3).zip(&faces) {
- let o = &mut out[t[k] as usize];
- o[0] += f[0];
- o[1] += f[1];
- o[2] += f[2];
- }
- }
- out
-}
-
-
-/// `bytes` as whole items of `T`.
-pub(crate) fn check_key(key: u64) -> Result<(), String> {
- if key == 0 { Err("key 0 is reserved".into()) } else { Ok(()) }
-}
-
/// What every host asks of a player: shapes, brushes and images uploaded once under a key, then
/// frames drawn from views and records (see `python` and `web`).
impl Player {
@@ -2578,30 +2644,10 @@ impl Player {
#[allow(clippy::too_many_arguments)]
pub(crate) fn add_mesh(&mut self, key: u64, points: &[u8], uvs: &[u8], normals: &[u8], triangles: &[u8], outline: u32, block: u32) -> Result<(), String> {
check_key(key)?;
- let p = read::<[f64; 3]>(points, "points")?;
- let uv = read::<[f64; 2]>(uvs, "uvs")?;
- let t = read::<u32>(triangles, "triangles")?;
- if uv.len() != p.len() || !t.len().is_multiple_of(3) || t.iter().any(|&i| i as usize >= p.len()) {
- return Err("a mesh needs a (u, v) per point, and whole triangles of its points".into());
- }
- let n = if normals.is_empty() { smooth_normals(&p, &t) } else { read::<[f64; 3]>(normals, "normals")? };
- if n.len() != p.len() {
- return Err("a mesh needs a normal per point".into());
- }
- let block = if block == 0 { outline } else { block };
- if outline > 2 && (block < outline || !p.len().is_multiple_of(block as usize)) {
- return Err("an outlined mesh is whole faces of vertices, each beginning with its loop".into());
- }
- // a reveal shows a surface face by face (`Raster`): each face's triangles are its own, in its turn
- let faces = (p.len() / block.max(1) as usize).max(1);
- let own = |(k, face): (usize, &[u32])| face.iter().all(|&i| i as usize / block as usize == k);
- if outline > 2 && (!t.len().is_multiple_of(3 * faces) || (!t.is_empty() && !t.chunks(t.len() / faces).enumerate().all(own))) {
- return Err("an outlined mesh's triangles are its faces' own, face after face, as many each".into());
- }
- // what the shaders read: (x, y, z, v) and (normal, u)
- let v: Vec<[f32; 4]> = p.iter().zip(&uv).map(|(p, uv)| [p[0] as f32, p[1] as f32, p[2] as f32, uv[1] as f32]).collect();
- let e: Vec<[f32; 4]> = n.iter().zip(&uv).map(|(n, uv)| [n[0] as f32, n[1] as f32, n[2] as f32, uv[0] as f32]).collect();
- self.store.add_mesh(key, &v, &e, &t, outline, block);
+ let mesh = Mesh::new(points, uvs, normals, triangles, outline, block)?;
+ let v: Vec<[f32; 4]> = mesh.points.iter().zip(&*mesh.uvs).map(|(p, uv)| [p[0] as f32, p[1] as f32, p[2] as f32, uv[1] as f32]).collect();
+ let e: Vec<[f32; 4]> = mesh.normals.iter().zip(&*mesh.uvs).map(|(n, uv)| [n[0] as f32, n[1] as f32, n[2] as f32, uv[0] as f32]).collect();
+ self.store.add_mesh(key, &v, &e, &mesh.triangles, mesh.outline, mesh.block);
Ok(())
}
@@ -2631,12 +2677,17 @@ impl Player {
}
#[cfg(feature = "python")]
- /// (bytes in the store's arrays, of which dead): what the arrays sent to the GPU hold, which
- /// must stay under wgpu's 4 GiB buffer limit (the feed evicts early past its budget).
+ /// (bytes in the store's arrays, of which dead).
pub(crate) fn stored(&self) -> (usize, usize) {
(self.store.bytes(), self.store.dead)
}
+ #[cfg(feature = "python")]
+ /// Whether retaining the current cache exceeds an individual GPU buffer's capacity.
+ pub(crate) fn pressured(&self, gpu: &Gpu) -> bool {
+ !self.store.fits(&gpu.device.limits())
+ }
+
#[cfg(feature = "player")]
/// Whether it holds `key`: a shape, brush or texture.
pub(crate) fn has(&self, key: u64) -> bool {
@@ -2732,3 +2783,166 @@ pub(crate) const COUNT_BYTES: u64 = 4;
pub(crate) fn count(bytes: &[u8]) -> u64 {
bytemuck::pod_read_unaligned::<u32>(&bytes[..4]) as u64
}
+
+#[cfg(test)]
+mod buffer_contract {
+ use super::*;
+
+ #[test]
+ fn growth_never_exposes_more_than_the_binding_allows() {
+ for stride in [1, 8, 16, size_of::<Instance>() as u64, VIEW_STRIDE as u64] {
+ for limit in [1024, 1600, 4096, 65536] {
+ for needed in [0, 1, limit / stride, limit / stride + 1] {
+ let room = buffer_room(needed, stride, 1024, limit, "test");
+ if needed <= limit / stride {
+ let room = room.unwrap();
+ assert!(room >= needed);
+ assert!(room * stride <= limit);
+ } else {
+ assert!(room.unwrap_err().contains("GPU's buffer limit"));
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn binding_pressure_reclaims_a_dead_minority() {
+ let mut store = Store::default();
+ for key in 1..=3 {
+ store.add_rows(key, &[[key as f32, 0.0, 0.0, 1.0]; 40]);
+ }
+ store.evict(&[2]);
+ assert!(store.dead * 2 < store.bytes());
+ let limits = wgpu::Limits { max_storage_buffer_binding_size: 1280, ..Default::default() };
+ assert!(!store.fits(&limits));
+ store.pack_if_worthwhile(true);
+ assert!(store.fits(&limits));
+ assert_eq!(store.dead, 0);
+ for key in [1, 3] {
+ let brush = &store.brushes[&key];
+ assert_eq!(&store.rows[brush.offset as usize..(brush.offset + brush.count) as usize], &[[key as f32, 0.0, 0.0, 1.0]; 40]);
+ }
+ }
+
+ fn retained_frames() -> Player {
+ let mut player = Player::new(1, 1, 1);
+ for key in 1..=3 {
+ player.store.add_points(key, &[[key as f32, 0.0, 0.0, 0.0]; 80]);
+ player.store.add_rows(key + 10, &[[key as f32, 0.0, 0.0, 1.0]; 80]);
+ }
+ player.store.dirty.push((0, 16..32));
+ player
+ }
+
+ fn frame(camera: u64, shape: u64) -> Frame {
+ Frame { key: camera, width: 1, height: 1, view: Vec::new(), records: vec![Record { key1: shape, fill_rows: shape + 10, ..Zeroable::zeroed() }] }
+ }
+
+ #[test]
+ fn a_draw_uses_every_camera_but_does_not_evict_other_frames_even_on_error() {
+ let mut player = retained_frames();
+ let limits = wgpu::Limits { max_storage_buffer_binding_size: 2560, ..Default::default() };
+ let frames = [frame(9, 3), frame(0, 1)];
+ for fail in [false, true, false] {
+ let generation = player.store.generation;
+ let result = player.with_working_set(&limits, &frames, |p| {
+ assert!(p.store.fits(&limits));
+ assert_eq!(p.store.shapes.len(), 2);
+ assert_eq!(p.store.brushes.len(), 2);
+ assert!(!p.store.shapes.contains_key(&2));
+ let moved = &p.store.shapes[&3];
+ assert_eq!(moved.base, 80);
+ assert_eq!(p.store.indices[moved.raster.stroke.start as usize] >> 3, 80);
+ assert_eq!(p.store.vertices[moved.base as usize][0], 3.0);
+ let rows = &p.store.brushes[&13];
+ assert_eq!(p.store.rows[rows.offset as usize][0], 3.0);
+ assert!(p.store.dirty.is_empty());
+ // As preparation does: temporary writes are consumed independently.
+ p.store.dirty.clear();
+ if fail { Err("rejected frame".into()) } else { Ok(()) }
+ });
+ assert_eq!(result.is_err(), fail);
+ assert_eq!(player.store.shapes.len(), 3);
+ assert_eq!(player.store.brushes.len(), 3);
+ assert_eq!(player.store.shapes[&3].base, 160);
+ assert_eq!(player.store.dirty, [(0, 16..32)]);
+ assert!(player.store.generation > generation);
+ }
+ }
+
+ #[test]
+ fn a_frame_that_itself_exceeds_capacity_is_rejected_without_losing_residency() {
+ let mut player = retained_frames();
+ let limits = wgpu::Limits { max_storage_buffer_binding_size: 2560, ..Default::default() };
+ let frames = [frame(8, 1), frame(9, 2), frame(0, 3)];
+ let result = player.with_working_set(&limits, &frames, |_| -> Result<(), String> { panic!("oversized frame reached the GPU") });
+ assert!(result.unwrap_err().contains("resident vertices requires 3840 bytes"));
+ assert_eq!(player.store.shapes.len(), 3);
+ assert_eq!(player.store.dirty, [(0, 16..32)]);
+ }
+
+ /// Alternating working sets must upload their own offsets, including after ordinary
+ /// residency fits again. Compare actual pixels with the same draws without projection.
+ #[test]
+ fn projected_residency_preserves_pixels_across_draws() {
+ fn player() -> Player {
+ let mut p = Player::new(64, 64, 4);
+ for key in 1..=3 {
+ p.store.add_points(key, &[[key as f32 * 0.4 - 0.8, 0.0, 0.5, 0.0]; 80]);
+ let mut color = [0.0, 0.0, 0.0, 1.0];
+ color[key as usize - 1] = 1.0;
+ p.store.add_rows(key + 10, &[color; 80]);
+ }
+ p
+ }
+ fn image(p: &mut Player, gpu: &mut Gpu, limits: &wgpu::Limits, key: u64) -> Vec<u8> {
+ let mut f = frame(0, key);
+ (f.width, f.height) = (64, 64);
+ f.view = vec![0.0; VIEW_LENGTH];
+ for at in [0, 16] {
+ for i in 0..4 {
+ f.view[at + i * 5] = 1.0;
+ }
+ }
+ f.view[32..36].copy_from_slice(&[64.0, 64.0, 32.0, 1.0]);
+ f.view[39] = 1.0;
+ f.view[42] = 1.0;
+ f.view[47] = 1.0;
+ let r = &mut f.records[0];
+ r.m1 = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
+ r.fill = [1.0; 4];
+ r.params[1] = 80.0;
+ r.gradient_a[3] = 0.25;
+ let frames = [f];
+ let (mut encoder, _, listed) = p.with_working_set(limits, &frames, |p| p.encode_frame(gpu, &frames)).unwrap();
+ assert!(!listed);
+ let buffer = gpu.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 64 * 64 * 4, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
+ encoder.copy_texture_to_buffer(
+ wgpu::TexelCopyTextureInfo { texture: p.targets.as_ref().unwrap().frame.color.texture(), mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
+ wgpu::TexelCopyBufferInfo { buffer: &buffer, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256), rows_per_image: Some(64) } },
+ wgpu::Extent3d { width: 64, height: 64, depth_or_array_layers: 1 },
+ );
+ gpu.queue.submit(Some(encoder.finish()));
+ buffer.slice(..).map_async(wgpu::MapMode::Read, |r| r.unwrap());
+ gpu.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
+ buffer.slice(..).get_mapped_range().unwrap().to_vec()
+ }
+ with_gpu(|gpu| {
+ let limits = wgpu::Limits { max_storage_buffer_binding_size: 2560, ..gpu.device.limits() };
+ let (mut projected, mut reference) = (player(), player());
+ let mut images = Vec::new();
+ for key in [1, 3, 2, 1] {
+ let expected = image(&mut reference, gpu, &gpu.device.limits(), key);
+ assert!(expected.chunks_exact(4).any(|pixel| pixel[..3] != [0, 0, 0]));
+ assert_eq!(image(&mut projected, gpu, &limits, key), expected);
+ images.push(expected);
+ }
+ assert_ne!(images[0], images[1]);
+ for p in [&mut projected, &mut reference] {
+ p.store.evict(&[2, 3, 12, 13]);
+ }
+ assert_eq!(image(&mut projected, gpu, &limits, 1), image(&mut reference, gpu, &gpu.device.limits(), 1));
+ }).unwrap();
+ }
+}
diff --git a/rust/engine/src/vector.rs b/rust/engine/src/vector.rs
index ff27b8c5..ddf44cc7 100644
--- a/rust/engine/src/vector.rs
+++ b/rust/engine/src/vector.rs
@@ -1,6 +1,6 @@
-//! A view's paths, drawn exactly (see `vector.wgsl`): from their control points, flattened per
+//! A view's paths, drawn with analytic segment coverage (see `vector.wgsl`): flattened per
//! frame on the GPU to the size they are drawn at through the view's camera (projectively in 3D),
-//! their exact area accumulated into a float atlas and composited per 16×16 tile in depth order
+//! their segment areas accumulated into a float atlas and composited per 16×16 tile in depth order
//! (the draw order among equal depths: a 2D view's whole order), each pixel kept as two regions. A
//! 2D view's point clouds and meshes are drawn by the raster pipeline (`blend.wgsl`), each alone in
//! its rectangle of a raster atlas, which the composite lays in its place in the order; a 3D view's
@@ -12,7 +12,7 @@
use bytemuck::{Pod, Zeroable};
-use super::{Camera, Kind, Mat34, NONE, Paint, ROUND, Record, SQUARE, Store, compose};
+use super::{Camera, Kind, Mat34, NONE, Paint, ROUND, Record, SQUARE, Shape, Store, compose};
const TILE: u32 = 16;
const ATLAS_WIDTH: u32 = 4096;
@@ -246,6 +246,54 @@ struct Flats {
points: Vec<[[f64; 3]; 3]>, // each flat's: three points of its plane in the world (a line's: on it)
}
+/// Place plane witnesses without rounding their basis into a different plane. In-plane
+/// principal axes may rotate freely when their spreads coincide; only the plane matters.
+fn world_plane(a: &Shape, b: Option<&Shape>, record: &Record) -> [[f64; 3]; 3] {
+ let at = |m: &Mat34, p: [f64; 3], translate: bool| [0, 1, 2].map(|k| m[k][0] as f64 * p[0] + m[k][1] as f64 * p[1] + m[k][2] as f64 * p[2] + if translate { m[k][3] as f64 } else { 0.0 });
+ std::array::from_fn(|i| {
+ let first = at(&record.m1, a.plane[i], true);
+ let second = b.map_or([0.0; 3], |b| at(&record.m2, b.plane[i], false));
+ [0, 1, 2].map(|k| first[k] + second[k])
+ })
+}
+
+#[cfg(test)]
+mod plane_precision {
+ use super::*;
+
+ #[test]
+ fn a_planes_projection_does_not_depend_on_its_principal_axes() {
+ // Equal in-plane spreads have no preferred eigenbasis. Tiny changes can rotate
+ // the witnesses by a large angle, but must not rotate or translate their plane.
+ for perturbation in [-f64::EPSILON, 0.0, f64::EPSILON] {
+ let mut points = [[-1.0, -1.0, 0.0], [1.0, -1.0, 0.0], [1.0, 1.0, 0.0], [-1.0, 1.0, 0.0]];
+ points[0][0] += perturbation;
+ let mut store = Store::default();
+ store.add_path(1, &points, &[[0, 1, 1, 0]], [0.0; 3], [0.0, 0.0, 1.0]);
+ let shape = store.shapes.get(&1).unwrap();
+ for offset in [0.0f32, 100.0, 100_000.0] {
+ let m = [[0.81, 0.24, 0.55, offset], [0.44, 0.93, -0.14, -offset], [0.37, -0.62, 0.89, offset]];
+ let record = Record::filled(1, 1, m, [1.0; 4]);
+ let placed = world_plane(shape, None, &record);
+ let actual = fit_plane(&placed);
+ let m = m.map(|row| row.map(f64::from));
+ let determinant = m[0][0] * m[1][1] - m[0][1] * m[1][0];
+ let a = (m[2][0] * m[1][1] - m[2][1] * m[1][0]) / determinant;
+ let b = (m[0][0] * m[2][1] - m[0][1] * m[2][0]) / determinant;
+ // Evaluate the fitted plane where the shape actually lies. Intercepts
+ // alone are ill-conditioned for a plane translated far from the origin.
+ for x in [-1.0, 0.0, 1.0] {
+ for y in [-1.0, 0.0, 1.0] {
+ let wanted = m[2][3] + a * x + b * y;
+ let found = actual[0] * (m[0][3] + x) + actual[1] * (m[1][3] + y) + actual[2];
+ assert!((wanted - found).abs() <= 8.0 * f64::EPSILON * (1.0 + offset as f64), "{perturbation} {offset}: {wanted} != {found}");
+ }
+ }
+ }
+ }
+ }
+}
+
fn flats(store: &Store, records: &[Record], order: &[usize]) -> Flats {
type P = [f64; 3];
let sub = |a: P, b: P| -> P { [a[0] - b[0], a[1] - b[1], a[2] - b[2]] };
@@ -279,8 +327,7 @@ fn flats(store: &Store, records: &[Record], order: &[usize]) -> Flats {
continue; // in the frame, not the scene
}
let b = if r.key2 == 0 { None } else { store.shapes.get(&r.key2) };
- let at = |m: &super::Mat34, p: [f32; 3], translate: bool| -> P { [0, 1, 2].map(|i| (m[i][0] * p[0] + m[i][1] * p[1] + m[i][2] * p[2] + if translate { m[i][3] } else { 0.0 }) as f64) };
- let points: [P; 3] = std::array::from_fn(|i| add(at(&r.m1, a.plane[i], true), b.map_or([0.0; 3], |b| at(&r.m2, b.plane[i], false))));
+ let points = world_plane(a, b, r);
let scale = points.iter().flat_map(|p| p.iter()).fold(1.0f64, |m, x| m.max(x.abs()));
let (u, v) = (sub(points[1], points[0]), sub(points[2], points[0]));
let n = cross(u, v);
@@ -585,14 +632,15 @@ struct GroupBuffers {
tiles: Data,
}
-/// The GPU side of drawing views exactly: its pipelines, and what they draw with.
+/// The GPU's path coverage and view composition: its pipelines, and what they draw with.
pub(crate) struct Vector {
limit: u32, // the largest texture side
shader: wgpu::ShaderModule,
+ single_shader: Option<wgpu::ShaderModule>, // the same composite with single-sample textures
write_layout: wgpu::BindGroupLayout,
- flatten: wgpu::ComputePipeline,
- composite: [Option<[wgpu::ComputePipeline; 2]>; 16], // by what a view lays (`LIT`, ...): the composite, `keep`; made when first needed
- crossing: [Option<[wgpu::ComputePipeline; 2]>; 16], // where depths cross: the count, the pixels (alike)
+ flatten: [Option<wgpu::ComputePipeline>; 2], // independent fill and stroke records, made when needed
+ composite: [Option<[wgpu::ComputePipeline; 2]>; 32], // by what a view lays (`LIT`, ...): the composite, `keep`; made when first needed
+ crossing: [Option<[wgpu::ComputePipeline; 2]>; 32], // where depths cross: the count, the pixels (alike)
crossings: (wgpu::Buffer, wgpu::Buffer, u64), // their list, the second pass's workgroups; pixels it holds
groups_layout: wgpu::BindGroupLayout, // the workgroups, as the count writes them
records: Option<(wgpu::Buffer, wgpu::Buffer, [u32; 2])>, // fill, stroke records' slots; how many they hold
@@ -600,12 +648,12 @@ pub(crate) struct Vector {
depth_resolve: [wgpu::ComputePipeline; 2],
nothing: wgpu::Buffer, // a view's lists when it has none (and strokes' depths)
stroke_depths: Option<(wgpu::Buffer, u64)>, // a non-planar path's strokes' depths, per pixel of the atlas
- no_samples: [wgpu::TextureView; 2], // its base's samples when it has none (color, depth)
+ no_samples: [[wgpu::TextureView; 2]; 2], // its base's samples when it has none (color, depth)
nearest: Option<(wgpu::BindGroupLayout, [wgpu::RenderPipeline; 2])>, // a light's map, a view's opaque depth, from its paths (made when first needed)
bounds: Option<([wgpu::BindGroupLayout; 2], wgpu::ComputePipeline)>, // a 3D view's slab bounds: what they read, where they go (made when first needed)
no_slabs: wgpu::TextureView, // a view's slabs when it has none: 1x1, one layer
scene_layout: wgpu::BindGroupLayout,
- image_layout: wgpu::BindGroupLayout,
+ image_layout: [wgpu::BindGroupLayout; 2],
read_layout: wgpu::BindGroupLayout,
fill: wgpu::RenderPipeline,
stroke: wgpu::RenderPipeline,
@@ -624,9 +672,13 @@ pub(crate) struct Vector {
}
impl Vector {
+ fn shader(device: &wgpu::Device, multisampled: bool) -> wgpu::ShaderModule {
+ super::sampled_shader(device, "vector", &[include_str!("vector.wgsl"), include_str!("light.wgsl"), include_str!("vector_buffers.wgsl"), include_str!("vector_compute.wgsl")].concat(), multisampled)
+ }
+
pub(crate) fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
let limits = device.limits();
- let shader = super::shader(device, "vector", &[include_str!("vector.wgsl"), include_str!("light.wgsl"), include_str!("vector_buffers.wgsl"), include_str!("vector_compute.wgsl")].concat());
+ let shader = Self::shader(device, true);
let (vertex, fragment, compute) = (wgpu::ShaderStages::VERTEX, wgpu::ShaderStages::FRAGMENT, wgpu::ShaderStages::COMPUTE);
// where the composite runs, and the accumulate pass
let (composing, all) = (compute, wgpu::ShaderStages::VERTEX_FRAGMENT | compute);
@@ -635,7 +687,7 @@ impl Vector {
let layout = |label, entries: &[wgpu::BindGroupLayoutEntry]| device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries });
let scene_layout = layout("vector scene", &[entry(0, all, wgpu::BufferBindingType::Uniform), entry(1, all, read), entry(2, all, read), entry(3, all, read), entry(4, all, read), entry(5, all, read)]);
let texture = |binding| wgpu::BindGroupLayoutEntry { binding, visibility: composing, ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: false }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false }, count: None };
- let multisampled = |binding, sample_type| wgpu::BindGroupLayoutEntry { binding, visibility: compute, ty: wgpu::BindingType::Texture { sample_type, view_dimension: wgpu::TextureViewDimension::D2, multisampled: true }, count: None };
+ let sampled = |binding, sample_type, multisampled| wgpu::BindGroupLayoutEntry { binding, visibility: compute, ty: wgpu::BindingType::Texture { sample_type, view_dimension: wgpu::TextureViewDimension::D2, multisampled }, count: None };
let target = |format| wgpu::BindingType::StorageTexture { access: wgpu::StorageTextureAccess::WriteOnly, format, view_dimension: wgpu::TextureViewDimension::D2 };
// what its paths with a material are lit with: a 3D view's lights' shadow maps and their comparison, the DFG
// table and its bilinear reads, its environment's cube, its ambient occlusion
@@ -646,10 +698,10 @@ impl Vector {
let cube = wgpu::BindGroupLayoutEntry { binding: 15, visibility: composing, ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::Cube, multisampled: false }, count: None };
// and a 3D view's see-through points' slabs, as many layers as `SLABS`
let slabs = wgpu::BindGroupLayoutEntry { binding: 21, visibility: composing, ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: false }, view_dimension: wgpu::TextureViewDimension::D2Array, multisampled: false }, count: None };
- let image_layout = layout(
+ let image_layout = [false, true].map(|multisampled| layout(
"vector images",
- &[texture(0), texture(1), texture(2), wgpu::BindGroupLayoutEntry { binding: 3, visibility: compute, ty: target(super::COLOR), count: None }, texture(4), entry(5, compute, read), entry(6, compute, read), multisampled(7, wgpu::TextureSampleType::Float { filterable: false }), multisampled(8, wgpu::TextureSampleType::Depth), entry(9, compute, read), maps, compare, dfg, linear, entry(14, compute, rw), cube, texture(16), texture(17), multisampled(18, wgpu::TextureSampleType::Float { filterable: false }), wgpu::BindGroupLayoutEntry { binding: 19, visibility: compute, ty: target(super::RADIANCE), count: None }, texture(20), slabs],
- );
+ &[texture(0), texture(1), texture(2), wgpu::BindGroupLayoutEntry { binding: 3, visibility: compute, ty: target(super::COLOR), count: None }, texture(4), entry(5, compute, read), entry(6, compute, read), sampled(7, wgpu::TextureSampleType::Float { filterable: false }, multisampled), sampled(8, wgpu::TextureSampleType::Depth, multisampled), entry(9, compute, read), maps, compare, dfg, linear, entry(14, compute, rw), cube, texture(16), texture(17), sampled(18, wgpu::TextureSampleType::Float { filterable: false }, multisampled), wgpu::BindGroupLayoutEntry { binding: 19, visibility: compute, ty: target(super::RADIANCE), count: None }, texture(20), slabs],
+ ));
let read_layout = layout("records in", &[entry(0, vertex, read), entry(1, vertex, read), entry(2, fragment, rw)]);
let pipeline_layout = |groups: &[Option<&wgpu::BindGroupLayout>]| device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: groups, immediate_size: 0 });
let accumulate = pipeline_layout(&[Some(&scene_layout), None, None, Some(&read_layout)]);
@@ -678,22 +730,19 @@ impl Vector {
let depth_resolve = [("nearest_of_samples", &depth_layouts[0]), ("single_sample", &depth_layouts[1])].map(|(entry, l)| {
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some(entry), layout: Some(&pipeline_layout(&[Some(l)])), module: &depth_shader, entry_point: Some(entry), compilation_options: Default::default(), cache: None })
});
- // workgroup memory is written before it is read: zeroing it would only cost time
- let options = wgpu::PipelineCompilationOptions { zero_initialize_workgroup_memory: false, ..Default::default() };
- let flatten = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("flatten"), layout: Some(&pipeline_layout(&[Some(&scene_layout), None, Some(&write_layout)])), module: &shader, entry_point: Some("flatten"), compilation_options: options, cache: None });
- let no_samples = [(super::COLOR, None), (super::DEPTH, Some(wgpu::TextureAspect::DepthOnly))].map(|(format, aspect)| {
+ let no_samples = [1, 4].map(|samples| [(super::COLOR, None), (super::DEPTH, Some(wgpu::TextureAspect::DepthOnly))].map(|(format, aspect)| {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("no samples"),
size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
mip_level_count: 1,
- sample_count: 4,
+ sample_count: samples,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
texture.create_view(&wgpu::TextureViewDescriptor { aspect: aspect.unwrap_or_default(), ..Default::default() })
- });
+ }));
let far = {
let t = device.create_texture(&wgpu::TextureDescriptor {
label: Some("far"),
@@ -711,8 +760,9 @@ impl Vector {
Self {
limit: limits.max_texture_dimension_2d,
shader,
+ single_shader: None,
write_layout,
- flatten,
+ flatten: [None, None],
composite: Default::default(),
crossing: Default::default(),
crossings: (buffer(device, "crossings", 16, wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST), buffer(device, "crossing groups", 16, wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::INDIRECT), 3),
@@ -890,18 +940,12 @@ impl Vector {
// its fill lit by the view's lights: a 3D view's planar path with a material, in the scene (not fixed in
// the frame); its plane's normal in the world (a morph's: both terms' plane points, summed, as its depth
// plane takes them)
- let world = |i: usize| -> [f32; 3] {
- let (p1, p2) = (a.plane[i], b.map_or([0.0; 3], |b| b.plane[i]));
- let at = |m: &super::Mat34, p: [f32; 3], translate: bool| [0, 1, 2].map(|k| m[k][0] * p[0] + m[k][1] * p[1] + m[k][2] * p[2] + if translate { m[k][3] } else { 0.0 });
- let (q1, q2) = (at(&r.m1, p1, true), if b.is_some() { at(&r.m2, p2, false) } else { [0.0; 3] });
- [0, 1, 2].map(|k| q1[k] + q2[k])
- };
- let (q0, q1, q2) = (world(0), world(1), world(2));
+ let [q0, q1, q2] = world_plane(a, b, r);
let (u, v) = ([0, 1, 2].map(|k| q1[k] - q0[k]), [0, 1, 2].map(|k| q2[k] - q0[k]));
let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
let length = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
let lit = camera.three_d && r.material[3] > 0.0 && r.flags & super::OVERLAY == 0 && a.planar && b.is_none_or(|b| b.planar) && length > 1e-12;
- let normal = if lit { n.map(|x| x / length) } else { [0.0; 3] };
+ let normal = if lit { n.map(|x| (x / length) as f32) } else { [0.0; 3] };
// else lit as a whole, like CE (where it is shaded in 3D): solid colors here, gradients by the composite
// (`place`)
let light = if lit { 0.0 } else { store.light(camera, r)? };
@@ -911,7 +955,7 @@ impl Vector {
}
}
let [pa, pb, pc] = if camera.three_d {
- let row = |t: &[f32; 4], p: [f32; 3]| [0, 1, 2].map(|j| t[j] as f64 * p[j] as f64).iter().sum::<f64>() + t[3] as f64;
+ let row = |t: &[f32; 4], p: [f64; 3]| [0, 1, 2].map(|j| t[j] as f64 * p[j]).iter().sum::<f64>() + t[3] as f64;
let points: Vec<[f64; 3]> = (0..3)
.filter_map(|i| {
let (p1, p2) = (a.plane[i], b.map_or([0.0; 3], |b| b.plane[i]));
@@ -960,11 +1004,11 @@ impl Vector {
let [p0, p1, p2] = a.plane;
let (u, v) = ([0, 1, 2].map(|k| p1[k] - p0[k]), [0, 1, 2].map(|k| p2[k] - p0[k]));
let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
- let dot = |a: [f32; 3], b: [f32; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
- let z = [z1[0] + t1w[0], z1[1] + t1w[1], z1[2] + t1w[2]]; // clip z's
+ let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+ let z = [0, 1, 2].map(|i| z1[i] as f64 + t1w[i] as f64); // clip z's
let g = if dot(n, n) > 1e-20 { [0, 1, 2].map(|k| z[k] - n[k] * dot(z, n) / dot(n, n)) } else { z };
let d = dot(z, g);
- if d.abs() > 1e-20 { [g[0], g[1], g[2], 1.0 / d] } else { [z[0], z[1], z[2], 1.0 / dot(z, z).max(1e-20)] }
+ (if d.abs() > 1e-20 { [g[0], g[1], g[2], 1.0 / d] } else { [z[0], z[1], z[2], 1.0 / dot(z, z).max(1e-20)] }).map(|v| v as f32)
} else {
[0.0; 4]
};
@@ -1057,21 +1101,39 @@ impl Vector {
}
/// The composite's pipelines for views that lay what `key` says (`LIT`, `RASTERS`, `LISTS`: the overrides in
- /// `vector.wgsl`), made when first needed.
- fn composite(&mut self, device: &wgpu::Device, key: usize) {
- if self.composite[key].is_some() {
+ /// `vector.wgsl`), made when first needed. Only a 3D view needs the passes where depths cross.
+ fn composite(&mut self, device: &wgpu::Device, key: usize, crossings: bool) {
+ if self.composite[key].is_some() && (!crossings || self.crossing[key].is_some()) {
return;
}
+ let kind = (key & SINGLE == 0) as usize;
+ let shader = if kind == 0 { self.single_shader.get_or_insert_with(|| Self::shader(device, false)) } else { &self.shader };
let constants = [("lighting", (key & LIT) as f64), ("rasters", (key & RASTERS != 0) as u8 as f64), ("lists", (key & LISTS != 0) as u8 as f64), ("points", (key & POINTS != 0) as u8 as f64)];
let layout = |groups: &[Option<&wgpu::BindGroupLayout>]| device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: groups, immediate_size: 0 });
- let (composing, counting) = (layout(&[Some(&self.scene_layout), Some(&self.image_layout)]), layout(&[Some(&self.scene_layout), Some(&self.image_layout), Some(&self.groups_layout)]));
+ let composing = layout(&[Some(&self.scene_layout), Some(&self.image_layout[kind])]);
// workgroup memory is written before it is read: zeroing it would only cost time
let make = |entry: &str, layout: &wgpu::PipelineLayout| {
let options = wgpu::PipelineCompilationOptions { constants: &constants, zero_initialize_workgroup_memory: false };
- device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some(entry), layout: Some(layout), module: &self.shader, entry_point: Some(entry), compilation_options: options, cache: None })
+ device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some(entry), layout: Some(layout), module: shader, entry_point: Some(entry), compilation_options: options, cache: None })
};
- self.composite[key] = Some([make("composite", &composing), make("keep", &composing)]);
- self.crossing[key] = Some([make("count_crossings", &counting), make("settle_crossings", &composing)]);
+ if self.composite[key].is_none() {
+ self.composite[key] = Some([make("composite", &composing), make("keep", &composing)]);
+ }
+ if crossings && self.crossing[key].is_none() {
+ let counting = layout(&[Some(&self.scene_layout), Some(&self.image_layout[kind]), Some(&self.groups_layout)]);
+ self.crossing[key] = Some([make("count_crossings", &counting), make("settle_crossings", &composing)]);
+ }
+ }
+
+ /// Fill and stroke records have independent producers. A view pays only for the families it draws.
+ fn prepare_flatten(&mut self, device: &wgpu::Device, counts: [u32; 2]) {
+ for (i, count) in counts.into_iter().enumerate() {
+ if count == 0 || self.flatten[i].is_some() { continue; }
+ let entry = ["flatten_fill", "flatten_stroke"][i];
+ let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&self.scene_layout), None, Some(&self.write_layout)], immediate_size: 0 });
+ let options = wgpu::PipelineCompilationOptions { zero_initialize_workgroup_memory: false, ..Default::default() };
+ self.flatten[i] = Some(device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some(entry), layout: Some(&layout), module: &self.shader, entry_point: Some(entry), compilation_options: options, cache: None }));
+ }
}
/// The pipelines of a light's map and of a view's opaque depth from its paths (`fs_nearest`), made when one is
@@ -1123,6 +1185,7 @@ impl Vector {
#[allow(clippy::too_many_arguments)]
pub(crate) fn encode(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, plan: &Plan, g: usize, statics: &[wgpu::BindingResource<'_>; 3], out: Out<'_>) {
let group = &plan.groups[g];
+ self.prepare_flatten(device, [group.fills, group.strokes]);
let [w, h] = plan.size;
let [tiles_x, tiles_y] = [w.div_ceil(TILE), h.div_ceil(TILE)];
let (base, light, listed, glowing, slabs) = match &out {
@@ -1158,9 +1221,10 @@ impl Vector {
}
// its composite's pipeline: with the code of what the group lays alone (`vector.wgsl`'s overrides)
let rastered = !group.rasters.is_empty() || (g == 0 && base.is_some());
- let key = lit as usize * LIT | rastered as usize * RASTERS | (g == 0 && listed.is_some()) as usize * LISTS | slabs.is_some() as usize * POINTS;
+ let kind = (!listed.is_some_and(|l| l.samples == 1)) as usize;
+ let key = (kind == 0) as usize * SINGLE | lit as usize * LIT | rastered as usize * RASTERS | (g == 0 && listed.is_some()) as usize * LISTS | slabs.is_some() as usize * POINTS;
match out {
- Out::Color { .. } => self.composite(device, key),
+ Out::Color { .. } => self.composite(device, key, plan.crossings),
Out::Bounds { .. } => self.bounds(device),
Out::Depth(_) | Out::Opaque(_) => self.nearest(device),
}
@@ -1258,10 +1322,11 @@ impl Vector {
};
let write = bind(&self.write_layout, &[(0, fill_records.as_entire_binding()), (1, stroke_records.as_entire_binding())]);
let read = bind(&self.read_layout, &[(0, fill_records.as_entire_binding()), (1, stroke_records.as_entire_binding()), (2, depths.as_entire_binding())]);
- let slots = group.fills.saturating_add(group.strokes).div_ceil(64); // workgroups: a thread per slot
- if slots > 0 {
+ for (pipeline, count) in self.flatten.iter().zip([group.fills, group.strokes]) {
+ let slots = count.div_ceil(64); // workgroups: a thread per slot
+ if slots == 0 { continue; }
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("flatten"), timestamp_writes: None });
- pass.set_pipeline(&self.flatten);
+ pass.set_pipeline(pipeline.as_ref().expect("the required record producer"));
pass.set_bind_group(0, &scene, &[]);
pass.set_bind_group(2, &write, &[]);
pass.dispatch_workgroups(slots.min(65535), slots.div_ceil(65535), 1);
@@ -1279,8 +1344,8 @@ impl Vector {
}
encoder.clear_buffer(&self.crossings.0, 0, Some(4));
let (heads, nodes) = listed.map_or((&self.nothing, &self.nothing), |l| (l.heads, l.nodes));
- let [colors, sample_depths] = listed.map_or([&self.no_samples[0], &self.no_samples[1]], |l| [l.colors, l.depths]);
- let lights = listed.and_then(|l| l.lights).unwrap_or(&self.no_samples[0]);
+ let [colors, sample_depths] = listed.map_or([&self.no_samples[kind][0], &self.no_samples[kind][1]], |l| [l.colors, l.depths]);
+ let lights = listed.and_then(|l| l.lights).unwrap_or(&self.no_samples[kind][0]);
// the light under the group (the raster base's, or what the group before left), and where it leaves its own
let carried = self.carried.as_ref().map(|(c, _)| c);
let light_in = if g == 0 { light.unwrap_or(&self.empty) } else { carried.map_or(&self.empty, |c| &c[(g - 1) % 2]) };
@@ -1290,7 +1355,7 @@ impl Vector {
None => &self.no_light_out,
};
let images = bind(
- &self.image_layout,
+ &self.image_layout[kind],
&[(0, view(atlas)), (1, view(rasters.unwrap_or(&self.empty))), (2, view(under)), (3, view(written)), (4, view(depth)), (5, heads.as_entire_binding()), (6, nodes.as_entire_binding()), (7, view(colors)), (8, view(sample_depths)), (9, depths.as_entire_binding()), (10, view(lighting.maps)), (11, wgpu::BindingResource::Sampler(lighting.compare)), (12, view(lighting.dfg)), (13, wgpu::BindingResource::Sampler(lighting.linear)), (14, self.crossings.0.as_entire_binding()), (15, view(lighting.environment)), (16, view(lighting.occlusion)), (17, view(light_in)), (18, view(lights)), (19, view(light_out)), (20, view(slabs.map_or(&self.empty, |s| s[0]))), (21, view(slabs.map_or(&self.no_slabs, |s| s[1])))],
);
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("composite"), timestamp_writes: None });
@@ -1337,6 +1402,52 @@ const LIT: usize = 1;
const RASTERS: usize = 2;
const LISTS: usize = 4;
const POINTS: usize = 8;
+const SINGLE: usize = 16; // single-sample texture bindings, with the same compositing code
+
+#[cfg(test)]
+mod pipeline_demand {
+ use super::*;
+
+ #[test]
+ fn record_families_compile_only_when_first_needed() {
+ super::super::with_gpu(|gpu| {
+ for first in 0..2 {
+ let mut vector = Vector::new(&gpu.device, &gpu.queue);
+ vector.prepare_flatten(&gpu.device, [0, 0]);
+ assert!(vector.flatten.iter().all(Option::is_none));
+ let mut counts = [0, 0];
+ counts[first] = 1;
+ vector.prepare_flatten(&gpu.device, counts);
+ assert!(vector.flatten[1 - first].is_none());
+ let pipeline = vector.flatten[first].clone().unwrap();
+ for counts in [[0, 0], counts, [1, 1]] {
+ vector.prepare_flatten(&gpu.device, counts);
+ assert_eq!(vector.flatten[first].as_ref(), Some(&pipeline));
+ }
+ assert!(vector.flatten.iter().all(Option::is_some));
+ }
+ }).unwrap();
+ }
+
+ #[test]
+ fn two_d_views_leave_crossing_passes_for_the_first_three_d_view() {
+ super::super::with_gpu(|gpu| {
+ let mut vector = Vector::new(&gpu.device, &gpu.queue);
+ for key in [0, SINGLE] {
+ for _ in 0..2 {
+ vector.composite(&gpu.device, key, false);
+ assert!(vector.composite[key].is_some());
+ assert!(vector.crossing[key].is_none());
+ }
+ for crossings in [true, false, true] {
+ vector.composite(&gpu.device, key, crossings);
+ assert!(vector.composite[key].is_some());
+ assert!(vector.crossing[key].is_some());
+ }
+ }
+ }).unwrap();
+ }
+}
/// What group `g` of `groups` lies over and writes: each lies over what the ones before it made (the first over
/// `first`); the last writes the target, the others alternate with the scratch image behind it.
diff --git a/rust/engine/src/vector.wgsl b/rust/engine/src/vector.wgsl
index 0d9a7c22..8d14649b 100644
--- a/rust/engine/src/vector.wgsl
+++ b/rust/engine/src/vector.wgsl
@@ -162,9 +162,10 @@ fn dbernstein(t: f32) -> vec4<f32> {
// The four control points from `first` with weights w (Bernstein or its derivative).
fn weighted(first: u32, w: vec4<f32>) -> vec3<f32> {
var acc = vec3<f32>(0.0);
- for (var k = 0u; k < 4u; k++) {
- acc += w[k] * control(first + k).xyz;
- }
+ acc = fma(vec3<f32>(w.x), control(first).xyz, acc);
+ acc = fma(vec3<f32>(w.y), control(first + 1u).xyz, acc);
+ acc = fma(vec3<f32>(w.z), control(first + 2u).xyz, acc);
+ acc = fma(vec3<f32>(w.w), control(first + 3u).xyz, acc);
return acc;
}
@@ -1851,6 +1852,11 @@ fn crossed(gid: vec2<u32>, b: Begun) -> Mix {
// A pixel's nearest layers' depths met so far, far to near (NO_LAYER past the last), with a layer at depth z among them:
// where all SLABS are met, only if it is nearer than the farthest, which makes room.
fn nearer(k: vec4<f32>, z: f32) -> vec4<f32> {
+ // A boundary is a depth, not a fragment: triangles and per-sample invocations can
+ // contribute several nodes at one depth without creating another slab for points.
+ if (any(k == vec4<f32>(z))) {
+ return k;
+ }
var out = k;
if (out.w > NO_LAYER) {
if (z >= out.x) {
diff --git a/rust/engine/src/vector_buffers.wgsl b/rust/engine/src/vector_buffers.wgsl
index cd908a64..db3d15dd 100644
--- a/rust/engine/src/vector_buffers.wgsl
+++ b/rust/engine/src/vector_buffers.wgsl
@@ -11,9 +11,9 @@
@group(1) @binding(6) var<storage, read> nodes: array<Node>;
// where it has see-through fragments, its raster base sample by sample: color (premultiplied), depth
-@group(1) @binding(7) var base_samples: texture_multisampled_2d<f32>;
-@group(1) @binding(18) var base_light_samples: texture_multisampled_2d<f32>; // (its light: `base_at`)
-@group(1) @binding(8) var base_sample_depths: texture_depth_multisampled_2d;
+@group(1) @binding(7) var base_samples: SampleColor;
+@group(1) @binding(18) var base_light_samples: SampleColor; // (its light: `base_at`)
+@group(1) @binding(8) var base_sample_depths: SampleDepth;
// the depth of a non-planar path's strokes per pixel of their atlas (as `stroke_depths` keeps it)
@group(1) @binding(9) var<storage, read> stroke_depths_in: array<u32>;
diff --git a/rust/engine/src/vector_compute.wgsl b/rust/engine/src/vector_compute.wgsl
index b0ebb236..26ba38f2 100644
--- a/rust/engine/src/vector_compute.wgsl
+++ b/rust/engine/src/vector_compute.wgsl
@@ -21,12 +21,18 @@ fn store(gid: vec2<u32>, m: Mix) {
@group(2) @binding(1) var<storage, read_write> stroke_out: array<Seg>;
@compute @workgroup_size(64)
-fn flatten(@builtin(global_invocation_id) gid: vec3<u32>, @builtin(num_workgroups) groups: vec3<u32>) {
+fn flatten_fill(@builtin(global_invocation_id) gid: vec3<u32>, @builtin(num_workgroups) groups: vec3<u32>) {
let q = gid.x + gid.y * groups.x * 64u;
if (q < frame.tiles.z) {
fill_out[q] = fill_slot(q);
- } else if (q - frame.tiles.z < frame.tiles.w) {
- stroke_out[q - frame.tiles.z] = stroke_slot(q - frame.tiles.z);
+ }
+}
+
+@compute @workgroup_size(64)
+fn flatten_stroke(@builtin(global_invocation_id) gid: vec3<u32>, @builtin(num_workgroups) groups: vec3<u32>) {
+ let q = gid.x + gid.y * groups.x * 64u;
+ if (q < frame.tiles.w) {
+ stroke_out[q] = stroke_slot(q);
}
}
diff --git a/src/manimgx/_engine.pyi b/src/manimgx/_engine.pyi
index 9969c57c..9cb6762f 100644
--- a/src/manimgx/_engine.pyi
+++ b/src/manimgx/_engine.pyi
@@ -2,12 +2,16 @@
encodes them into an MP4.
Shapes, brushes and images are uploaded once, under a nonzero key; a frame is then a view (48
-float32: projection, overlay, pixels, light, toward; then the background) and one 320-byte record
+float32: projection, overlay, pixels, light, toward; then the background) and one 336-byte record
per object (see `manimgx.rendering.feed`). A document is typeset in this process by Typst as a library, and
its layout read off Typst's frames (see `manimgx.drawing.typesetting`).
"""
from collections.abc import Sequence
+from pathlib import Path
+
+TAKE_VERSION: int
+"""The take format written by Recorder and supported by Replay and the native/browser player."""
# a camera's view, drawn into a texture that later views sample by its key:
# (key, width, height, view, records)
@@ -60,6 +64,9 @@ class Player:
def stored(self) -> tuple[int, int]:
"""(bytes in the store's arrays, of which dead): what the arrays sent to the GPU hold."""
+ def pressured(self) -> bool:
+ """Whether the resident arrays exceed a GPU buffer's capacity; brings up the GPU."""
+
def render(
self, view: bytes, records: bytes, cameras: Sequence[CameraView] = ...
) -> bytes:
@@ -82,9 +89,11 @@ class Player:
repeat: int = 1,
cameras: Sequence[CameraView] = ...,
key: bool = False,
- ) -> None:
+ capture: bool = False,
+ ) -> bytes | None:
"""The next frame of the video, shown for `repeat` frames; `key`: a keyframe, where a
- player can start (a section's first frame)."""
+ player can start (a section's first frame). With `capture`, return the same draw's
+ full-quality RGBA8 pixels, waiting for any overflow retries."""
def abort_export(self) -> None:
"""Abandon the video: nothing is written."""
@@ -101,12 +110,39 @@ class Player:
bits a second. Returns (seconds, of which in x264, share of macroblocks converted,
bytes)."""
+class Replay:
+ """One complete, successful take, using the native player's decoder and renderer."""
+
+ def __init__(self, data: bytes) -> None: ...
+ @property
+ def size(self) -> tuple[int, int]:
+ """The recorded width and height, in pixels."""
+
+ @property
+ def frames(self) -> int:
+ """The frame count, including repeated frames."""
+
+ @property
+ def fps(self) -> float: ...
+ @property
+ def timeline(self) -> list[tuple[int, int]]:
+ """Each recorded shot's first frame and repeat count."""
+
+ def render(self, frame: int) -> bytes:
+ """A zero-based frame, in any order, as RGBA8 bytes; out-of-range indices fail."""
+
def start_gpu() -> bool:
"""Start bringing the GPU up, on a thread of its own, unless that has begun; whether this
call began it (natively only). What draws first waits for it, and so does Python as it
exits. A process that will draw calls it as early as it knows; one that never draws never
brings the GPU up."""
+def adapter_info() -> dict[str, str]:
+ """The active GPU's name, vendor, device, device_type, driver, driver_info and backend.
+
+ Brings the GPU up if necessary; available in the native engine.
+ """
+
def decode_audio(data: bytes, rate: int) -> tuple[bytes, int]:
"""A file's audio (its bytes, any container and codec the engine's FFmpeg decodes: WAV,
AIFF, CAF, MP3, AAC, Opus, Vorbis, FLAC, ALAC; in MP4, MOV, WebM, Matroska) at `rate` samples
@@ -195,6 +231,9 @@ def digest(*parts: bytes) -> int:
class TypstError(Exception):
"""Typst could not typeset a document (its errors, joined)."""
+def cache_directory() -> Path | None:
+ """The current user's cache root, or the browser's private filesystem; None disables it."""
+
def typeset(
source: str, font_paths: Sequence[str], packages: str | None = None
) -> tuple[bytes, list[bytes], list[tuple[str, list[int]]], bool]:
diff --git a/src/manimgx/rendering/feed.py b/src/manimgx/rendering/feed.py
index 86b22483..1bb0e56f 100644
--- a/src/manimgx/rendering/feed.py
+++ b/src/manimgx/rendering/feed.py
@@ -1,4 +1,4 @@
-"""Feed the player: shapes once, then one 320-byte record per object and frame.
+"""Feed the player: shapes once, then one 336-byte record per object and frame.
A shape is uploaded as its object defines it, and the player derives what drawing needs. A path
goes as control points in its own space, with its subpaths as curve ranges, so a reveal is a
@@ -12,6 +12,7 @@ widths and flags; the camera is one 4×4 matrix."""
import functools
import itertools
import struct
+from collections.abc import Iterator, Sequence
from dataclasses import dataclass
from typing import TYPE_CHECKING
@@ -169,9 +170,10 @@ def centroid_area(points: np.ndarray) -> list[float]:
# A surface is its samples of func(u, v) on a grid; drawn, it is the tensor-product cubic
# spline through them (periodic along a direction whose ends meet, not-a-knot otherwise): C²,
# exact for cubics, O(h⁴) from a smooth func — a coarse grid draws the surface, not flat
-# quads. Each face (a grid cell) is refined into m × m cells of its spline patch, m chosen per
-# shape so that no chord leaves the spline by more than SURFACE_TOLERANCE; normals are the
-# spline's (smooth shading). A face keeps its own vertices, so a checkerboard keeps its sharp
+# quads. Each face (a grid cell) is refined into m × m cells of its spline patch. The shape's
+# midpoint deviation estimates m, capped by SURFACE_STEPS; this is not a bound on triangle
+# error (a saddle can have zero midpoint deviation). Normals are the spline's. A face keeps
+# its own vertices, so a checkerboard keeps its sharp
# cells, and its edge loop (4m + 1 vertices) is its outline.
# scene units: a quarter pixel at 1080p, the frame 8 units high
@@ -253,8 +255,11 @@ def _patches(cells: np.ndarray, x: np.ndarray) -> tuple[np.ndarray, ...]:
def surface_steps(g: np.ndarray, linear: np.ndarray) -> int:
- """m: cells per face and direction for no chord to leave the spline by more than
- SURFACE_TOLERANCE where `linear` places it (a chord's deviation falls as 1/m²)."""
+ """Estimate cells per face and direction from midpoint deviation after `linear`.
+
+ SURFACE_TOLERANCE is the target of this estimate, not a guaranteed error bound;
+ refinement is capped at SURFACE_STEPS and midpoint sampling can miss curvature.
+ """
mid = _patches(_cells(g[..., :3]), np.array([0.5]))[0][:, :, 0, 0]
flat = (g[:-1, :-1, :3] + g[1:, :-1, :3] + g[:-1, 1:, :3] + g[1:, 1:, :3]) / 4
deviation = float(np.linalg.norm((mid - flat) @ linear.T, axis=-1).max())
@@ -557,16 +562,15 @@ class Feeder:
self.last_used.update(dict.fromkeys(keys, last))
self.last_used.pop(0, None)
- def sweep(self) -> None:
+ def sweep(self, pinned: Sequence[bytes] = (), *, pressed: bool = False) -> None:
"""Evict what no frame has shown for KEEP frames (frames mark what they show every MARK
- frames; the film holds back at most one frame). Past BUDGET living bytes (a scene making
- big new shapes every frame), all the last frame does not show goes at once: the store
- stays far below wgpu's 4 GiB buffer limit however long the scene."""
+ frames; the film holds back at most one frame). Memory pressure keeps only the latest
+ frame and the records pinned by the caller, including every pending camera view."""
stored, dead = self.player.stored()
- pressed = stored - dead + sum(self.texture_bytes.values()) > BUDGET
+ pressed |= stored - dead + sum(self.texture_bytes.values()) > BUDGET
if self.frames - self.swept < SWEEP and not pressed:
return
- for data in self.latest:
+ for data in (*self.latest, *pinned):
self.shown(np.frombuffer(data, RECORD), self.frames)
self.swept = self.frames
keep = 0 if pressed else KEEP
@@ -921,7 +925,7 @@ class Feeder:
cameras: list[CameraView],
fixed: "set[Mobject]",
) -> bytes | None:
- """One object's record (320 bytes), or None if it draws nothing. It is a function of the
+ """One object's record (336 bytes), or None if it draws nothing. It is a function of the
object's geometry and paint (values), a mesh's topology (indices or lattice dimensions, with uvs:
values too), its camera flags and lighting, so it is kept on the object and remade only
when one of them changes (or what it draws was evicted); a camera's picture is remade
@@ -1105,10 +1109,11 @@ class Feeder:
camera: "Camera",
mobjects: "list[Mobject]",
leaves: "list[tuple[Mobject, list[Mobject], Path, np.ndarray, np.ndarray]]",
- ) -> list[tuple[bytes, bytes]]:
- """(view, records) for every frame of a pure play at once: per leaf and keyframe interval, the
- two keyframe records are mixed over all its frames (`mix`); a leaf that cannot be mixed is
- materialized per distinct t. The view is the play's first, unless the play moves the camera.
+ ) -> Iterator[tuple[bytes, bytes]]:
+ """Mix whole keyframe intervals on the CPU; upload an interval when it first appears.
+
+ A leaf that cannot be mixed is materialized when its frame is yielded, so a long
+ play never makes every future shape resident on the GPU before drawing its first.
"""
self.sweep()
frames = len(leaves[0][3]) if leaves else 0
@@ -1116,7 +1121,7 @@ class Feeder:
camera, self.width, self.height, self.lights(mobjects)
)
views = self.views(camera, mobjects, leaves, frames)
- fixed = camera.fixed_in_frame_mobjects # read once a play
+ fixed = camera.fixed_in_frame_mobjects
args = (camera, three_d, mobjects, self.width, self.height, [], fixed)
base = [unpack(self.record(mob, *args)) for mob in mobjects]
rows = np.zeros((frames, len(mobjects)), RECORD)
@@ -1125,45 +1130,88 @@ class Feeder:
if r is not None:
rows[:, k], present[:, k] = r, True
position = {id(mob): k for k, mob in enumerate(mobjects)}
- drawn = [
- r for r in base if r is not None
- ] # a record of every key the play draws
+ type Interval = tuple[
+ Mobject, Mobject, Mobject, Path, np.ndarray, np.ndarray, int
+ ]
+ type Cached = dict[float, tuple[np.void | None, tuple[int, ...]]]
+ type Materialize = tuple[
+ Mobject, Mobject, Mobject, Path, np.ndarray, float, int, Cached
+ ]
+ starts: dict[int, list[Interval]] = {}
+ moving: dict[int, list[Materialize]] = {}
+ restores: dict[int, list[tuple[Mobject, np.ndarray, int, set[Mobject]]]] = {}
for leaf, keys, path, index, t in leaves:
k = position.get(id(leaf))
if k is None:
continue
- present[index == -2, k] = False # not in the scene yet
- for interval in dict.fromkeys(index[index >= 0].tolist()):
+ present[index == -2, k] = False
+ initial = None
+ for interval in dict.fromkeys(index[index >= -1].tolist()):
at = np.nonzero(index == interval)[0]
- a, b = keys[interval], keys[interval + 1]
- # a frame is a function of its t: each distinct t once (a held stretch is one)
- distinct = dict.fromkeys(t[at].tolist())
+ # A nonmonotone clock can leave an interval and return: its inputs may
+ # have been evicted while absent, so entering it prepares them again.
+ for run in np.split(at, np.flatnonzero(np.diff(at) != 1) + 1):
+ if interval == -1:
+ if run[0] > 0:
+ # A clock can return to before the animation began. Keep
+ # its original CPU state, not its now-unused uploads.
+ if initial is None:
+ initial = leaf.copy()
+ pinned = fixed | {initial} if leaf in fixed else fixed
+ restores.setdefault(int(run[0]), []).append(
+ (initial, run, k, pinned)
+ )
+ continue
+ starts.setdefault(int(run[0]), []).append(
+ (leaf, keys[interval], keys[interval + 1], path, run, t[run], k)
+ )
+ for f in range(frames):
+ self.sweep()
+ for initial, at, k, pinned in restores.pop(f, ()):
+ r = unpack(self.record(initial, *args[:-1], pinned))
+ present[at, k] = r is not None
+ if r is not None:
+ rows[at, k] = r
+ for leaf, a, b, path, at, t, k in starts.pop(f, ()):
+ distinct = dict.fromkeys(t.tolist())
ts = np.array(list(distinct))
- where = np.array(
- [*map({x: j for j, x in enumerate(distinct)}.get, t[at].tolist())]
- )
+ where = np.array([*map({x: j for j, x in enumerate(distinct)}.get, t)])
mixed = self.mix(a, b, path, ts, args, base[k])
if mixed is not None:
rows[at, k], present[at, k] = mixed[where], True
- drawn.append(mixed[0])
continue
- for j, x in enumerate(
- ts
- ): # not mixable here: the leaf itself, at each t
- leaf.interpolate(a, b, float(x), path)
+ cache: Cached = {}
+ # A hold has one materialization. Revisited values reuse their records
+ # while resident, and reconstruct from their keyframes after eviction.
+ for run in np.split(
+ np.arange(len(at)), np.flatnonzero(np.diff(where)) + 1
+ ):
+ moving.setdefault(int(at[run[0]]), []).append(
+ (leaf, a, b, path, at[run], float(t[run[0]]), k, cache)
+ )
+ for leaf, a, b, path, at, t, k, cache in moving.pop(f, ()):
+ known = cache.get(t)
+ if known is None or any(key not in self.sizes for key in known[1]):
+ leaf.interpolate(a, b, t, path)
r = unpack(self.record(leaf, *args))
- shown = at[where == j]
- present[shown, k] = r is not None
- if r is not None:
- rows[shown, k] = r
- drawn.append(r)
- if drawn:
- self.shown(np.array(drawn, RECORD), self.frames + frames)
- self.frames += frames
- return [
- (uniform if views is None else views[f], rows[f][present[f]].tobytes())
- for f in range(frames)
- ]
+ keys = (
+ ()
+ if r is None
+ else tuple(
+ int(r[name]) for name in (*KEYS, "texture") if r[name]
+ )
+ )
+ known = cache[t] = (r, keys)
+ r = known[0]
+ present[at, k] = r is not None
+ if r is not None:
+ rows[at, k] = r
+ data = rows[f][present[f]].tobytes()
+ self.latest = [data]
+ if self.frames % MARK == 0:
+ self.shown(np.frombuffer(data, RECORD), self.frames)
+ self.frames += 1
+ yield uniform if views is None else views[f], data
def views(
self,
diff --git a/tests/integration/test_compositing.py b/tests/integration/test_compositing.py
index edf0cdbc..7f2a87e9 100644
--- a/tests/integration/test_compositing.py
+++ b/tests/integration/test_compositing.py
@@ -25,6 +25,9 @@ def stack(
points: frozenset[int] = frozenset(),
colors: tuple[m.ManimColor, ...] = COLORS,
meshes: frozenset[int] = frozenset(),
+ *,
+ mesh_resolution: int = 1,
+ mesh_shift: float = 0.0,
) -> m.Scene:
"""Layers one behind another, layer k nearer than layer k - 1, in `colors[k]`, each
see-through; added in `order`. Each is a plane filling the view (a shape, or, if in
@@ -40,11 +43,12 @@ def stack(
lambda u, v: np.array([u, v, 0.0]),
u_range=[-20, 20],
v_range=[-20, 20],
- resolution=1,
+ resolution=mesh_resolution,
checkerboard_colors=False,
stroke_width=0,
shade_in_3d=False, # (its color as given, as a shape's)
).set_fill(color, OPACITY)
+ shape.shift(mesh_shift * (m.RIGHT - m.UP))
else:
shape = m.Square(side_length=40.0).set_fill(color, OPACITY)
shape.set_stroke(width=0)
@@ -120,6 +124,28 @@ def test_see_through_points_composite_in_depth_order_in_any_order(
assert np.abs(center - composite(colors)).max() <= 2.0
[email protected]("resolution", [1, 2, 4])
[email protected]("offset", [0.0, 0.02, 0.04])
+def test_surface_tessellation_preserves_points_depth_order(
+ resolution: int, offset: float
+) -> None:
+ # More triangles may meet a pixel, or a backend may append one node per sample.
+ # Neither creates more depth boundaries: each point stays between the same planes.
+ # Moving the grid by half a pixel makes its triangles share the center's samples.
+ for order in (list(range(len(COLORS))), list(reversed(range(len(COLORS))))):
+ shown = picture(
+ stack(
+ order,
+ ODD,
+ meshes=frozenset({2, 4}),
+ mesh_resolution=resolution,
+ mesh_shift=offset,
+ )
+ )
+ center = shown[SIZE[1] // 2, SIZE[0] // 2].astype(float)
+ assert np.abs(center - composite()).max() <= 2.0
+
+
def test_a_title_fixed_in_the_frame_changes_no_pixel_but_its_own() -> None:
# a deep pile of see-through points and a line beside it: a title fixed in the frame, over
# everything, takes no place among the scene's depths, so the pile is drawn as without it
diff --git a/tests/integration/test_engine.py b/tests/integration/test_engine.py
index e3d37a5b..d3b3b3d4 100644
--- a/tests/integration/test_engine.py
+++ b/tests/integration/test_engine.py
@@ -72,7 +72,7 @@ def test_the_command_line_starts_the_gpu_for_a_command_that_draws(
"from manimgx.cli import main\ntry:\n main()\nexcept SystemExit as e:\n"
)
drawn = run(
- "import sys\nsys.argv = ['manimgx', 'check', 'scene.py']\n"
+ "import sys\nsys.argv = ['manimgx', 'inspect', 'scene.py']\n"
+ command
+ " assert not e.code, e.code",
cwd=tmp_path,
diff --git a/tests/integration/test_mesh_strokes.py b/tests/integration/test_mesh_strokes.py
new file mode 100644
index 00000000..ad57287c
--- /dev/null
+++ b/tests/integration/test_mesh_strokes.py
@@ -0,0 +1,115 @@
+"""A mesh's nearest outlined face is visible, independently of face and object order."""
+
+import itertools
+
+import numpy as np
+import pytest
+
+import manimgx as m
+from manimgx import _engine
+from manimgx.rendering import feed
+
+SIZE = (160, 90)
+
+
+def outlined_faces(
+ depths: tuple[float, ...], *, filled: bool, occluder_first: bool, samples: int
+) -> np.ndarray:
+ """Coincident projected squares; a red square lies between their depths."""
+ player = _engine.Player(*SIZE, samples)
+ camera = m.Camera(three_d=True, focal_distance=20)
+ view, _, _ = feed.view(camera, *SIZE)
+
+ def mesh(
+ key: int, planes: tuple[float, ...], extent: float, *, filled: bool
+ ) -> None:
+ loop = np.array([[-1, -1], [1, -1], [1, 1], [-1, 1], [-1, -1]])
+ # Perspective maps every face to the same square. The nearest one wholly hides
+ # the others; reversing the mesh's face order cannot change its picture.
+ vertices = np.concatenate(
+ [
+ np.column_stack([loop * extent * (1 - z / 20), np.full(len(loop), z)])
+ for z in planes
+ ]
+ ).astype("<f8")
+ triangles = np.concatenate(
+ [np.array([0, 1, 2, 0, 2, 3]) + 5 * i for i in range(len(planes))]
+ ).astype("<u4")
+ player.add_mesh(
+ key,
+ vertices.tobytes(),
+ np.zeros((len(vertices), 2), "<f8").tobytes(),
+ np.tile([0.0, 0.0, 1.0], (len(vertices), 1)).astype("<f8").tobytes(),
+ triangles.tobytes() if filled else b"",
+ 5,
+ 5,
+ )
+
+ mesh(1, depths, 2, filled=filled)
+ mesh(2, (5.0,), 3, filled=True)
+ records = np.zeros(2, feed.RECORD)
+ records["key1"] = [1, 2]
+ records["m1"][:, :, :3] = np.eye(3)
+ records["fill"][0] = [0.125, 0.25, 0.75, float(filled)]
+ records["stroke"][0] = [0.875, 0.875, 0.875, 1]
+ records["params"][0] = [0, len(depths), 0.2, 0]
+ records["fill"][1] = [0.75, 0.125, 0.125, 1]
+ records["params"][1] = [0, 1, 0, 0]
+ if occluder_first:
+ records = records[::-1].copy()
+ return np.frombuffer(player.render(view, records.tobytes()), np.uint8).reshape(
+ SIZE[1], SIZE[0], 4
+ )
+
+
[email protected]("filled", [False, True], ids=["stroke-only", "filled"])
[email protected]("occluder_first", [False, True])
[email protected]("samples", [1, 4])
+def test_mesh_strokes_keep_the_nearest_face_in_every_order(
+ filled: bool, occluder_first: bool, samples: int
+) -> None:
+ def picture(depths: tuple[float, ...]) -> np.ndarray:
+ return outlined_faces(
+ depths, filled=filled, occluder_first=occluder_first, samples=samples
+ )
+
+ expected = picture((10.0,))
+ np.testing.assert_array_equal(
+ expected[SIZE[1] // 2, SIZE[0] // 2, :3],
+ [32, 64, 191] if filled else [191, 32, 32],
+ )
+ for depths in itertools.permutations((0.0, 2.0, 10.0)):
+ np.testing.assert_array_equal(picture(depths), expected)
+
+
+def test_a_normal_magnitude_cannot_change_an_outlined_planes_visibility() -> None:
+ """The same tilted plane, with equivalent normals across forty binary orders."""
+ view, _, _ = feed.view(m.Camera(three_d=True), *SIZE)
+ points = np.array(
+ [[-2, -2, -2], [2, -2, 2], [2, 2, 2], [-2, 2, -2], [-2, -2, -2]], "<f8"
+ )
+ records = np.zeros(1, feed.RECORD)
+ records["key1"] = 1
+ records["m1"][0, :, :3] = np.eye(3)
+ records["fill"] = [0.125, 0.25, 0.75, 1]
+ records["stroke"] = [0.875, 0.875, 0.875, 1]
+ records["params"] = [0, 1, 0.5, 0]
+
+ def picture(scale: float) -> np.ndarray:
+ player = _engine.Player(*SIZE, 4)
+ player.add_mesh(
+ 1,
+ points.tobytes(),
+ np.zeros((len(points), 2), "<f8").tobytes(),
+ (np.tile([-1.0, 0.0, 1.0], (len(points), 1)) * scale)
+ .astype("<f8")
+ .tobytes(),
+ np.array([0, 1, 2, 0, 2, 3], "<u4").tobytes(),
+ 5,
+ 5,
+ )
+ return np.frombuffer(player.render(view, records.tobytes()), np.uint8)
+
+ expected = picture(1.0)
+ for exponent in [-20, -10, 10, 20]:
+ np.testing.assert_array_equal(picture(2.0**exponent), expected)
diff --git a/tests/integration/test_perspective.py b/tests/integration/test_perspective.py
index d525f869..8d616702 100644
--- a/tests/integration/test_perspective.py
+++ b/tests/integration/test_perspective.py
@@ -121,7 +121,7 @@ def test_shapes_a_hair_apart_meet_by_depth_at_any_distance(distance: float) -> N
assert np.abs(shown.astype(int) - BLUE).max() <= 2
[email protected]("distance", [5.0, 20.0, 60.0])
[email protected]("distance", [5.0, 20.0, 60.0, 200.0])
def test_meshes_a_hair_apart_meet_by_depth_at_any_distance(distance: float) -> None:
# the nearer surface, 0.001 above, drawn first: the nearer shows, wherever the camera is
def sheet(side: float, color: m.ManimColor, z: float) -> m.Mobject:
diff --git a/tests/integration/test_samples.py b/tests/integration/test_samples.py
new file mode 100644
index 00000000..1d3da47d
--- /dev/null
+++ b/tests/integration/test_samples.py
@@ -0,0 +1,106 @@
+"""Antialiasing changes edge coverage, never depth ordering or transparency."""
+
+from itertools import permutations
+
+import numpy as np
+import pytest
+
+import manimgx as m
+from manimgx import _engine
+from manimgx.rendering import feed
+
+SIZE = (160, 90)
+RED = np.array([0.75, 0.125, 0.125])
+BLUE = np.array([0.125, 0.125, 0.75])
+
+
[email protected]("samples", [1, 4])
[email protected]("alpha", [0.0, 0.25, 0.5, 1.0])
[email protected]("order", [(0, 1), (1, 0)])
+def test_a_foreground_mesh_obscures_only_its_opacity(
+ samples: int, alpha: float, order: tuple[int, int]
+) -> None:
+ player = _engine.Player(*SIZE, samples)
+ view, _, _ = feed.view(m.Camera(three_d=True, focal_distance=20), *SIZE)
+ for key, z in ((1, 10), (2, 5)):
+ # Both quads project to the same square; the center is far from every edge.
+ xy = np.array([[-1, -1], [1, -1], [1, 1], [-1, 1]]) * 2 * (1 - z / 20)
+ points = np.column_stack([xy, np.full(4, z)]).astype("<f8")
+ player.add_mesh(
+ key,
+ points.tobytes(),
+ np.zeros((4, 2), "<f8").tobytes(),
+ np.tile([0, 0, 1], (4, 1)).astype("<f8").tobytes(),
+ np.array([0, 1, 2, 0, 2, 3], "<u4").tobytes(),
+ )
+ records = np.zeros(2, feed.RECORD)
+ records["key1"] = [1, 2]
+ records["m1"][:, :, :3] = np.eye(3)
+ records["fill"] = [[*BLUE, alpha], [*RED, 1]]
+ records["params"][:, 1] = 2
+ pixels = np.frombuffer(
+ player.render(view, records[list(order)].tobytes()), np.uint8
+ ).reshape(SIZE[1], SIZE[0], 4)
+ expected = 255 * (alpha * BLUE + (1 - alpha) * RED)
+ assert np.abs(pixels[SIZE[1] // 2, SIZE[0] // 2, :3] - expected).max() <= 1
+
+
[email protected]("samples", [1, 4])
[email protected]("meshes", [False, True])
[email protected]("order", list(permutations(range(3))))
+def test_points_between_layers_keep_the_same_composite_at_each_sample_count(
+ samples: int, meshes: bool, order: tuple[int, ...]
+) -> None:
+ player = _engine.Player(*SIZE, samples)
+ feeder = feed.Feeder(*SIZE, player)
+ camera = m.Camera(three_d=True)
+ opacity = 0.4
+ colors = (m.RED, m.GREEN, m.BLUE)
+ layers: list[m.Mobject] = []
+ for i, color in enumerate(colors):
+ if i == 1:
+ mob = m.PMobject(stroke_width=180).add_points(
+ [m.ORIGIN], color=color, alpha=opacity
+ )
+ elif meshes:
+ mob = m.MeshMobject(
+ np.array([[-10, -10, 0], [10, -10, 0], [10, 10, 0], [-10, 10, 0]]),
+ np.array([[0, 1, 2], [0, 2, 3]]),
+ color=color,
+ fill_opacity=opacity,
+ )
+ else:
+ mob = m.Square(
+ side_length=20, color=color, fill_opacity=opacity, stroke_width=0
+ )
+ layers.append(mob.shift(i * m.OUT))
+ pixels = np.frombuffer(
+ player.render(*feeder.frame(camera, [layers[i] for i in order])), np.uint8
+ ).reshape(SIZE[1], SIZE[0], 4)
+ expected = np.zeros(3)
+ for color in colors:
+ expected = opacity * m.ManimColor(color).to_rgb() + (1 - opacity) * expected
+ assert np.abs(pixels[SIZE[1] // 2, SIZE[0] // 2, :3] - 255 * expected).max() <= 2
+
+
+def test_material_layers_keep_the_same_interior_color_at_each_sample_count() -> None:
+ layers: list[m.Mobject] = [m.AmbientLight(intensity=0.5)]
+ for z, color, alpha in [(0, m.RED, 1), (1, m.BLUE, 0.4)]:
+ layers.append(
+ m.MeshMobject(
+ np.array([[-10, -10, z], [10, -10, z], [10, 10, z], [-10, 10, z]]),
+ np.array([[0, 1, 2], [0, 2, 3]]),
+ color=color,
+ fill_opacity=alpha,
+ ).set_material(m.Material(roughness=1))
+ )
+ images: list[np.ndarray] = []
+ for samples in [1, 4]:
+ player = _engine.Player(*SIZE, samples)
+ feeder = feed.Feeder(*SIZE, player)
+ pixels = np.frombuffer(
+ player.render(*feeder.frame(m.Camera(three_d=True), layers)), np.uint8
+ ).reshape(SIZE[1], SIZE[0], 4)
+ images.append(pixels[SIZE[1] // 2, SIZE[0] // 2, :3].astype(int))
+ assert images[0].max() > 20
+ assert np.abs(images[0] - images[1]).max() <= 1
diff --git a/tests/unit/rendering/test_feed.py b/tests/unit/rendering/test_feed.py
index b745291b..c60f5c81 100644
--- a/tests/unit/rendering/test_feed.py
+++ b/tests/unit/rendering/test_feed.py
@@ -146,7 +146,10 @@ MESHES: dict[str, tuple[dict[str, np.ndarray], bool]] = { # a mesh's changes; t
@pytest.mark.parametrize("name", MESHES)
-def test_a_mesh_is_taken_if_it_fits_its_points(name: str) -> None:
[email protected]("sink", [Player, Recorder])
+def test_a_mesh_is_taken_if_it_fits_its_points(
+ name: str, sink: type[Player] | type[Recorder]
+) -> None:
changes, taken = MESHES[name]
mesh = {
"points": np.zeros((4, 3)),
@@ -156,7 +159,7 @@ def test_a_mesh_is_taken_if_it_fits_its_points(name: str) -> None:
} | changes
def add() -> None:
- Player(16, 16, 1).add_mesh(
+ sink(16, 16, 1).add_mesh(
1,
np.asarray(mesh["points"], "<f8").tobytes(),
np.asarray(mesh["uvs"], "<f8").tobytes(),
@@ -171,6 +174,12 @@ def test_a_mesh_is_taken_if_it_fits_its_points(name: str) -> None:
add()
[email protected]("sink", [Player, Recorder])
+def test_mesh_uploads_reserve_key_zero(sink: type[Player] | type[Recorder]) -> None:
+ with pytest.raises(ValueError, match="key 0 is reserved"):
+ sink(16, 16, 1).add_mesh(0, b"", b"", b"", b"")
+
+
@pytest.mark.parametrize("start_paced", [False, True])
@pytest.mark.parametrize("end_paced", [False, True])
def test_batched_reveals_follow_the_same_pace_as_individual_frames(
@@ -398,6 +407,143 @@ class Sink:
return self.engine.stored()
+def test_a_tween_materializes_only_the_frames_consumed_and_reloads_evicted_values() -> (
+ None
+):
+ """A non-affine cloud morph, revisiting old values after their uploads were evicted."""
+ points = np.array(
+ [[-1, -1, 0], [1, -1, 0], [1, 1, 0], [-1, 1, 0], [0.25, 0.5, 0]], float
+ )
+ start = m.PMobject().add_points(points)
+ end = start.copy().set_points(points + np.array([[0, 0, 0]] * 4 + [[0.5, 0, 0]]))
+ leaf = start.copy()
+ progress = np.tile(np.linspace(0.1, 0.9, 25), 3)
+ camera, path, sink = m.Camera(), m.straight_path(), Sink()
+ feeder = feed.Feeder(32, 32, sink) # ty: ignore[invalid-argument-type]
+ frames = iter(
+ feeder.tween(
+ camera,
+ [leaf],
+ [(leaf, [start, end], path, np.zeros(len(progress), int), progress)],
+ )
+ )
+ assert not sink.resident
+ for number, t in enumerate(progress):
+ _, records = next(frames)
+ if number == 0:
+ assert sum(kind == "points" for kind in sink.kinds.values()) <= 2
+ expected_sink = Sink()
+ expected = feed.Feeder(32, 32, expected_sink) # ty: ignore[invalid-argument-type]
+ alone = start.copy()
+ alone.interpolate(start, end, float(t), path)
+ assert records == expected.frame(camera, [alone])[1]
+ feeder.sweep(pressed=True)
+ keys = {
+ int(row[name])
+ for row in np.frombuffer(records, feed.RECORD)
+ for name in (*feed.KEYS, "texture")
+ if row[name]
+ }
+ assert set(sink.resident) == keys
+ with pytest.raises(StopIteration):
+ next(frames)
+
+
+def test_streaming_still_mixes_whole_keyframe_intervals(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """An interval revisited by a nonmonotone clock is vectorized when it becomes current."""
+ start = m.Square()
+ keys: list[m.Mobject] = [
+ start,
+ start.copy().shift(m.RIGHT),
+ start.copy().shift(m.UP),
+ ]
+ leaf, sink, camera = start.copy(), Sink(), m.Camera()
+ feeder = feed.Feeder(32, 32, sink) # ty: ignore[invalid-argument-type]
+ intervals = np.repeat([0, 1, 0], 30)
+ progress = np.tile(np.linspace(0, 1, 30), 3)
+ batches: list[int] = []
+ mix = feeder.mix
+
+ def measured(*args: object) -> np.ndarray | None:
+ batches.append(len(args[3])) # ty: ignore[invalid-argument-type]
+ return mix(*args) # ty: ignore[invalid-argument-type]
+
+ monkeypatch.setattr(feeder, "mix", measured)
+ frames = feeder.tween(
+ camera, [leaf], [(leaf, keys, m.straight_path(), intervals, progress)]
+ )
+ for f, (_, records) in enumerate(frames):
+ assert batches == [30] * (1 + f // 30)
+ feeder.sweep(pressed=True)
+ assert all(
+ int(row[name]) in feeder.sizes
+ for row in np.frombuffer(records, feed.RECORD)
+ for name in feed.KEYS
+ if row[name]
+ )
+
+
[email protected]("fixed", [False, True])
+def test_a_delayed_tween_can_return_before_its_start_after_eviction(
+ fixed: bool,
+) -> None:
+ from manimgx.scene import _tracks
+
+ points = np.array(
+ [[-1, -1, 0], [1, -1, 0], [1, 1, 0], [-1, 1, 0], [0.25, 0.5, 0]], float
+ )
+ start = m.PMobject().add_points(points)
+ keys = [
+ start.copy().set_points(points + np.array([[0, 0, 0]] * 4 + [[x, x, 0]]))
+ for x in [0, 0.5, 1]
+ ]
+ # The state before the play need not be its first explicit keyframe.
+ leaf = start.copy().shift(0.125 * m.UP)
+ tween = m.Transform(leaf, keys=keys, rate_func=m.linear)
+ clock = m.Succession(m.Wait(1), tween, rate_func=m.there_and_back)
+ clock.begin_all()
+ leaves = _tracks(clock, [(tween, m.straight_path())], np.linspace(0, 1, 4), set())
+ assert leaves[0][3].tolist() == [-1, 1, 1, -1]
+ camera, sink = m.Camera(), Sink()
+ if fixed:
+ camera.fixed_in_frame_mobjects.add(leaf)
+ feeder = feed.Feeder(32, 32, sink) # ty: ignore[invalid-argument-type]
+ original = feeder.frame(camera, [leaf])[1]
+ for number, (_, records) in enumerate(feeder.tween(camera, [leaf], leaves)):
+ if number in (0, 3):
+ assert records == original
+ used = {
+ int(row[name])
+ for row in np.frombuffer(records, feed.RECORD)
+ for name in (*feed.KEYS, "texture")
+ if row[name]
+ }
+ assert used <= set(sink.resident)
+ feeder.sweep(pressed=True)
+ assert set(sink.resident) == used
+
+
+def test_pressure_preserves_pending_current_and_camera_resources() -> None:
+ sink = Sink()
+ feeder = feed.Feeder(32, 32, sink) # ty: ignore[invalid-argument-type]
+ keys = [
+ feeder.path(m.RegularPolygon(n)._geometry.terms[0][1])[0] for n in range(3, 7)
+ ]
+
+ def records(key: int) -> bytes:
+ row = np.zeros(1, feed.RECORD)
+ row["key1"] = key
+ return row.tobytes()
+
+ feeder.frames = 10
+ feeder.latest = [records(keys[0])]
+ feeder.sweep([records(keys[1]), records(keys[2])], pressed=True)
+ assert set(sink.resident) == set(keys[:3])
+ assert set(feeder.sizes) == set(keys[:3])
+
+
PIXELS = [np.full((2, 2, 4), v, np.uint8) for v in (0, 90, 200)]
ROWS = [np.linspace(0, 1, 4 * n).reshape(n, 4) for n in (2, 3, 6)]
FORMS = [