mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-30 18:27:00 +01:00
Merge remote-tracking branch 'origin/main' into res-2985
# Conflicts: # crates/raster3d/src/lib.rs # crates/raster3d/src/raster.rs
This commit is contained in:
commit
18dfdba5ed
29 files changed
+3731
-151
No files matched your search
@@ -106,8 +106,20 @@ pub struct Wheel {
|
||||
/// taker that owns the gesture; another taker's share holds its own `mods`.
|
||||
pub held: Mods,
|
||||
/// A wheel event of the running gesture, or one less than [`GESTURE_GAP`] seconds before it began, arrived while a
|
||||
/// modal layer held the wheel: the turn began or went on under the modal, and it stays marked until it ends.
|
||||
/// modal layer held the wheel: the turn began or went on under the modal, and it stays marked until it ends. An
|
||||
/// app's own modal window marks it too (`CanvasSpace::mark_wheel_modal`).
|
||||
pub modal: bool,
|
||||
/// The owner claimed an earlier share of the running gesture (`CanvasSpace::claim_wheel`): it takes the gesture
|
||||
/// for itself. For the taker that owns the gesture; another taker's share is never claimed.
|
||||
pub claimed: bool,
|
||||
/// The `scroll` of the running gesture's shares the owner claimed before this one. Motion the owner did not
|
||||
/// claim is not counted.
|
||||
pub claimed_gathered: Vec2,
|
||||
/// The `zoom_lines` of the running gesture's shares the owner claimed before this one.
|
||||
pub claimed_zoom_gathered: Vec2,
|
||||
/// The motion the owner said it used up (`spent`) with its claims of the running gesture so far, in its own
|
||||
/// unit: `claimed_gathered` or `claimed_zoom_gathered` less this is what the claimed shares left over.
|
||||
pub claimed_spent: Vec2,
|
||||
}
|
||||
|
||||
/// The eased motion of a canvas's line wheel: notches gather into owed motion that later passes pay out.
|
||||
@@ -256,6 +268,10 @@ impl Wheel {
|
||||
moved: false,
|
||||
held: mods,
|
||||
modal: false,
|
||||
claimed: false,
|
||||
claimed_gathered: Vec2::ZERO,
|
||||
claimed_zoom_gathered: Vec2::ZERO,
|
||||
claimed_spent: Vec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -150,6 +150,9 @@ impl<'de> Deserialize<'de> for BranchIndex {
|
||||
pub struct Header {
|
||||
pub version: Option<u64>,
|
||||
pub images: Option<Vec<String>>,
|
||||
/// Stored dimensions, retained even when a consumer cannot decode an image's codec.
|
||||
/// These are untrusted metadata, not permission to allocate a pixel buffer.
|
||||
pub image_dimensions: std::collections::BTreeMap<String, (u32, u32)>,
|
||||
}
|
||||
|
||||
pub fn read_header(text: &str) -> Result<Header, serde_json::Error> {
|
||||
@@ -170,10 +173,20 @@ impl<'de> Deserialize<'de> for Header {
|
||||
match k.as_str() {
|
||||
"version" => h.version = m.next_value::<Value>()?.as_u64(),
|
||||
"imageIndex" => {
|
||||
h.images = m
|
||||
.next_value::<Value>()?
|
||||
let value = m.next_value::<Value>()?;
|
||||
h.images =
|
||||
value.as_array().map(|a| a.iter().filter_map(|v| v.get("hash").and_then(Value::as_str).map(str::to_owned)).collect());
|
||||
h.image_dimensions = value
|
||||
.as_array()
|
||||
.map(|a| a.iter().filter_map(|v| v.get("hash").and_then(Value::as_str).map(str::to_owned)).collect())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|v| {
|
||||
let hash = v.get("hash")?.as_str()?.to_owned();
|
||||
let width = u32::try_from(v.get("width")?.as_u64()?).ok()?;
|
||||
let height = u32::try_from(v.get("height")?.as_u64()?).ok()?;
|
||||
Some((hash, (width, height)))
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
_ => {
|
||||
m.next_value::<IgnoredAny>()?;
|
||||
@@ -324,6 +337,17 @@ pub fn write_document_json<D: Serialize, W: std::io::Write>(doc: &D, images: &[I
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn image_dimensions_survive_the_native_envelope() {
|
||||
let images = [super::ImageIndexEntry { hash: "original-image".into(), width: 731, height: 419 }];
|
||||
let mut json = Vec::new();
|
||||
super::write_document_json(&serde_json::json!({"name":"original fixture"}), &images, &mut json).unwrap();
|
||||
let header = super::read_header(std::str::from_utf8(&json).unwrap()).unwrap();
|
||||
assert_eq!(header.image_dimensions.get(&images[0].hash), Some(&(images[0].width, images[0].height)));
|
||||
let legacy = super::read_header(r#"{"imageIndex":[{"hash":"legacy"},{"hash":"overflow","width":4294967296,"height":1}]}"#).unwrap();
|
||||
assert_eq!(legacy.images.unwrap().len(), 2);
|
||||
assert!(legacy.image_dimensions.is_empty());
|
||||
}
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
@@ -437,8 +461,8 @@ mod tests {
|
||||
}
|
||||
#[test]
|
||||
fn newer_version_is_reported_before_document_decode() {
|
||||
assert_eq!(check_version(&Header { version: Some(2), images: None }), Err(NewerVersion(2)));
|
||||
assert_eq!(check_version(&Header { version: Some(u64::MAX), images: None }), Err(NewerVersion(u32::MAX)));
|
||||
assert_eq!(check_version(&Header { version: Some(2), ..Header::default() }), Err(NewerVersion(2)));
|
||||
assert_eq!(check_version(&Header { version: Some(u64::MAX), ..Header::default() }), Err(NewerVersion(u32::MAX)));
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Payload {
|
||||
|
||||
@@ -10,6 +10,21 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form
|
||||
- **Normals and tangents.** Smooth normals are area weighted. Tangents come from MikkTSpace, which
|
||||
glTF 2.0 recommends for meshes without tangents
|
||||
(<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>): `w` holds the bitangent sign.
|
||||
`compute_tangents` keeps the indices and the vertex count; a vertex whose triangles have
|
||||
different tangent frames (mirrored UVs) takes the frame of its first corner.
|
||||
`compute_tangents_split` instead splits such a vertex into one copy per frame. Faces with coincident corners stay in the mesh and reuse shared vertex frames when
|
||||
available. MikkTSpace omits those faces. A mesh with more than 2,048 noncollapsed triangles around one vertex, or with non-finite
|
||||
positions or UVs, or whose largest absolute position or UV component is nonzero and outside 1e-6 to 1e6, gets per-corner tangents from f64 UV gradients instead of MikkTSpace.
|
||||
An edge-connected region containing a face whose f32 UV gradients overflow or underflow uses that fallback.
|
||||
Both paths read the stored glTF UVs (v down) with v negated, so an unmirrored mapping gets
|
||||
`w = +1`. The generated corner frames of a triangle with usable UV gradients
|
||||
share one handedness sign. With `compute_tangents`, a vertex shared by mirrored triangles keeps
|
||||
the first triangle's frame, so the stored signs of the other triangle can differ; use
|
||||
`compute_tangents_split` when both sides of a mirrored seam need their own frames. It splits only
|
||||
a mesh whose indices are in range, whose index count is a multiple of 3 and whose colors are
|
||||
empty or one per vertex; any other mesh gets the `compute_tangents` result. Corners whose copy
|
||||
would need an index above `u32::MAX` keep the first frame. Tangents
|
||||
are always finite; a non-finite normal counts as +Y.
|
||||
- **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting
|
||||
vertices where charts meet. It checks the mesh against its size limits and its attribute data
|
||||
first and returns an error without changing the mesh when a check fails. Charts are projected
|
||||
|
||||
+1786
-46
File diff suppressed because it is too large.
Load diff
@@ -701,7 +701,8 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Every triangle's winding agrees with its vertex normals, UVs stay in 0..1 (u in 0..max_u),
|
||||
/// and the UV mapping is not mirrored (tangent handedness +1).
|
||||
/// tangent frames are unit length and perpendicular to their normals, and the UV mapping is
|
||||
/// not mirrored (tangent handedness +1).
|
||||
fn check(m: &Mesh, max_u: f32) {
|
||||
m.validate().unwrap();
|
||||
let mut bad = 0;
|
||||
@@ -720,8 +721,55 @@ mod tests {
|
||||
for uv in &m.uvs {
|
||||
assert!((0.0..=max_u).contains(&uv.x) && (0.0..=1.0).contains(&uv.y), "{uv:?}");
|
||||
}
|
||||
for (index, tangent) in m.tangents.iter().enumerate() {
|
||||
let normal = m.normals[index];
|
||||
assert!(tangent.truncate().is_finite(), "{tangent:?}");
|
||||
assert!((tangent.truncate().length() - 1.0).abs() < 1e-3, "{tangent:?}");
|
||||
assert!(tangent.truncate().dot(normal).abs() < 1e-3, "{tangent:?}, {normal:?}");
|
||||
assert!(tangent.w == 1.0 || tangent.w == -1.0, "{tangent:?}");
|
||||
}
|
||||
let mirrored = m.tangents.iter().filter(|t| t.w < 0.0).count();
|
||||
assert!(mirrored * 50 < m.tangents.len().max(1), "{mirrored} mirrored tangents");
|
||||
// glTF UVs run v down the image, and the bitangent `cross(N, T) * w` points up it.
|
||||
let (mut opposed, mut tested) = (0, 0);
|
||||
for &[a, b, c] in m.indices.as_chunks::<3>().0 {
|
||||
let (a, b, c) = (a as usize, b as usize, c as usize);
|
||||
let (d1, d2) = (m.uvs[b].as_dvec2() - m.uvs[a].as_dvec2(), m.uvs[c].as_dvec2() - m.uvs[a].as_dvec2());
|
||||
let determinant = d1.perp_dot(d2);
|
||||
if determinant == 0.0 {
|
||||
continue;
|
||||
}
|
||||
let (e1, e2) = (m.positions[b].as_dvec3() - m.positions[a].as_dvec3(), m.positions[c].as_dvec3() - m.positions[a].as_dvec3());
|
||||
let Some(increasing_v) = ((e2 * d1.x - e1 * d2.x) / determinant).try_normalize() else { continue };
|
||||
for vertex in [a, b, c] {
|
||||
let tangent = m.tangents[vertex];
|
||||
let reconstructed = m.normals[vertex].as_dvec3().cross(tangent.truncate().as_dvec3()) * tangent.w as f64;
|
||||
tested += 1;
|
||||
let alignment = reconstructed.dot(-increasing_v);
|
||||
assert!(alignment.is_finite(), "vertex {vertex}: {alignment}");
|
||||
opposed += usize::from(alignment < 0.0);
|
||||
}
|
||||
}
|
||||
assert!(tested > 0);
|
||||
assert!(opposed * 50 < tested, "{opposed} bitangents point down the image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_rejects_invalid_tangent_frames() {
|
||||
let mesh = cube(2.0).unwrap();
|
||||
for tangent in [
|
||||
Vec3::ZERO.extend(1.0),
|
||||
(mesh.tangents[0].truncate() * 0.5).extend(mesh.tangents[0].w),
|
||||
mesh.normals[0].extend(mesh.tangents[0].w),
|
||||
Vec3::splat(f32::NAN).extend(1.0),
|
||||
Vec3::splat(f32::INFINITY).extend(1.0),
|
||||
mesh.tangents[0].truncate().extend(0.0),
|
||||
mesh.tangents[0].truncate().extend(f32::NAN),
|
||||
] {
|
||||
let mut invalid = mesh.clone();
|
||||
invalid.tangents[0] = tangent;
|
||||
assert!(std::panic::catch_unwind(|| check(&invalid, 1.0)).is_err(), "{tangent:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -155,7 +155,8 @@ lights' outer cones are over 1.40 radians wide, where resolve blocks hold more t
|
||||
subsamples, where shadows-only materials do not receive shadows, where fragments under discarded
|
||||
opaque pixels leave the depth range, where blended casters have no base texture, where
|
||||
opaque-mode and masked casters have an opacity below 0.5, where casters reach within 1 unit of
|
||||
light-space depth of a spot or point light, where an encoded color is negative, and where a
|
||||
light-space depth of a spot or point light, where an inverse-square point or spot light's radius is
|
||||
between 0 and 1, where an encoded color is negative, and where a
|
||||
texture is sampled between large finite texels of opposite signs. Halfway between red values of
|
||||
`3e38` and `−3e38`, for example, the sampler here returns red 0 and EffectCraft's interpolation
|
||||
overflows `f32`.
|
||||
@@ -212,6 +213,10 @@ Changes from those files:
|
||||
- A spot light whose outer cone's half angle plus 0.05 radians is over 1.45 radians gets six maps,
|
||||
as a point light does. EffectCraft gave it one map 1.45 radians wide, so receivers in the rest
|
||||
of the cone were not shadowed.
|
||||
- An inverse-square point or spot light whose radius is between 0 and 1 takes a radius of 1 for both
|
||||
its full-strength plateau and its falloff, so its distance factor never exceeds 1. EffectCraft kept
|
||||
the plateau at the radius and divided 1 by the distance beyond it, so a fragment between the radius
|
||||
and 1 unit from the light took more than the light's full strength.
|
||||
- A resolve block of more than 256 subsamples is averaged in `f64`. EffectCraft summed every block
|
||||
in `f32`, which dropped the low bits of each sample as the sum grew (a 1024 × 1024 block of 0.7
|
||||
resolved to 0.6927), and its `f32` count of covered subsamples stopped at 2^24, which raised the
|
||||
|
||||
@@ -148,10 +148,10 @@ pub enum RenderError {
|
||||
#[error("the shadow texels do not fit 32-bit offsets")]
|
||||
TooManyShadowTexels,
|
||||
/// Rasterizing or rendering shadow maps would take more coverage or depth tests than
|
||||
/// [`Limits::max_work`]. Preparation stops at the first triangle past the limit. With the
|
||||
/// `parallel` feature, fallback and shadow-map work may be counted on several threads, within
|
||||
/// one triangle per thread, so `needed` is at least
|
||||
/// `limit + 1` and may be below the scene's total.
|
||||
/// [`Limits::max_work`]. Preparation stops at the first triangle past the limit. The search
|
||||
/// under discarded pixels reports `needed` as `limit + 1`. With the `parallel` feature, fallback
|
||||
/// and shadow-map work may be counted on several threads, within one triangle per thread.
|
||||
/// `needed` is at least `limit + 1` and may be below the scene's total.
|
||||
#[error("the render needs at least {needed} tests, over the limit of {limit}")]
|
||||
TooMuchWork { needed: u64, limit: u64 },
|
||||
/// A resolve factor is zero or does not divide both sides of the target.
|
||||
|
||||
+182
-59
@@ -47,6 +47,9 @@ struct STri {
|
||||
/// A polygon corner: clip coordinates and weights over the original triangle's vertices.
|
||||
type Corner = ([f32; 4], [f32; 3]);
|
||||
|
||||
/// A [`Corner`] held in `f64`.
|
||||
type WideCorner = ([f64; 4], [f64; 3]);
|
||||
|
||||
/// A screen-space corner: position, ndc z, 1/w and weights.
|
||||
type ScreenCorner = ([f64; 2], f32, f64, [f32; 3]);
|
||||
|
||||
@@ -108,7 +111,12 @@ pub(crate) fn f32_crossing(da: f32, db: f32) -> (bool, f32) {
|
||||
/// Clip a polygon against `planes` (see [`plane_distance`]), interpolating in `f64` from the
|
||||
/// corner nearer the plane.
|
||||
fn clip_f64(poly: &[Corner], planes: &[usize]) -> Vec<Corner> {
|
||||
let mut p: Vec<([f64; 4], [f64; 3])> = poly.iter().map(|(c, w)| (c.map(f64::from), w.map(f64::from))).collect();
|
||||
clip_wide(poly, planes).iter().map(|(c, w)| (c.map(|v| v as f32), w.map(|v| v as f32))).collect()
|
||||
}
|
||||
|
||||
/// [`clip_f64`] without narrowing the result to `f32`.
|
||||
fn clip_wide(poly: &[Corner], planes: &[usize]) -> Vec<WideCorner> {
|
||||
let mut p: Vec<WideCorner> = poly.iter().map(|(c, w)| (c.map(f64::from), w.map(f64::from))).collect();
|
||||
for &plane in planes {
|
||||
if p.is_empty() {
|
||||
break;
|
||||
@@ -122,44 +130,7 @@ fn clip_f64(poly: &[Corner], planes: &[usize]) -> Vec<Corner> {
|
||||
out.push(a);
|
||||
}
|
||||
if (da >= 0.0) != (db >= 0.0) {
|
||||
let (p, q, t) = if da.abs() <= db.abs() { (a, b, da / (da - db)) } else { (b, a, db / (db - da)) };
|
||||
let c: [f64; 4] = std::array::from_fn(|k| p.0[k] + (q.0[k] - p.0[k]) * t);
|
||||
let w: [f64; 3] = std::array::from_fn(|k| p.1[k] + (q.1[k] - p.1[k]) * t);
|
||||
out.push((c, w));
|
||||
}
|
||||
}
|
||||
p = out;
|
||||
}
|
||||
p.iter().map(|(c, w)| (c.map(|v| v as f32), w.map(|v| v as f32))).collect()
|
||||
}
|
||||
|
||||
/// Clip a polygon (clip coords + original weights) against `0 ≤ z ≤ w`.
|
||||
fn clip_poly(poly: Vec<Corner>) -> Vec<Corner> {
|
||||
let mut p = poly;
|
||||
for plane in 0..2 {
|
||||
if p.is_empty() {
|
||||
break;
|
||||
}
|
||||
let d = |c: &[f32; 4]| if plane == 0 { c[2] } else { c[3] - c[2] };
|
||||
let mut out = Vec::with_capacity(p.len() + 2);
|
||||
for i in 0..p.len() {
|
||||
let (a, b) = (p[i], p[(i + 1) % p.len()]);
|
||||
let (da, db) = (d(&a.0), d(&b.0));
|
||||
if da >= 0.0 {
|
||||
out.push(a);
|
||||
}
|
||||
if (da >= 0.0) != (db >= 0.0) {
|
||||
let (from_b, t) = f32_crossing(da, db);
|
||||
let (p, q) = if from_b { (b, a) } else { (a, b) };
|
||||
let mut c = [0.0; 4];
|
||||
let mut w = [0.0; 3];
|
||||
for k in 0..4 {
|
||||
c[k] = p.0[k] + (q.0[k] - p.0[k]) * t;
|
||||
}
|
||||
for k in 0..3 {
|
||||
w[k] = p.1[k] + (q.1[k] - p.1[k]) * t;
|
||||
}
|
||||
out.push((c, w));
|
||||
out.push(crossing_f64(a, b, da, db));
|
||||
}
|
||||
}
|
||||
p = out;
|
||||
@@ -167,12 +138,89 @@ fn clip_poly(poly: Vec<Corner>) -> Vec<Corner> {
|
||||
p
|
||||
}
|
||||
|
||||
/// Where the edge from `a` (plane distance `da`) to `b` (`db`) crosses the plane, interpolated in
|
||||
/// `f64` from the corner nearer the plane, so both directions of an edge give the same corner.
|
||||
fn crossing_f64(a: ([f64; 4], [f64; 3]), b: ([f64; 4], [f64; 3]), da: f64, db: f64) -> ([f64; 4], [f64; 3]) {
|
||||
let (p, q, t) = if da.abs() <= db.abs() { (a, b, da / (da - db)) } else { (b, a, db / (db - da)) };
|
||||
let c: [f64; 4] = std::array::from_fn(|k| p.0[k] + (q.0[k] - p.0[k]) * t);
|
||||
let w: [f64; 3] = std::array::from_fn(|k| p.1[k] + (q.1[k] - p.1[k]) * t);
|
||||
(c, w)
|
||||
}
|
||||
|
||||
/// Where the edge from `a` (plane distance `da`) to `b` (`db`) crosses the plane, in `f32` (see
|
||||
/// [`f32_crossing`]).
|
||||
fn f32_corner(a: Corner, b: Corner, da: f32, db: f32) -> Corner {
|
||||
let (from_b, t) = f32_crossing(da, db);
|
||||
let (p, q) = if from_b { (b, a) } else { (a, b) };
|
||||
let mut c = [0.0; 4];
|
||||
let mut w = [0.0; 3];
|
||||
for k in 0..4 {
|
||||
c[k] = p.0[k] + (q.0[k] - p.0[k]) * t;
|
||||
}
|
||||
for k in 0..3 {
|
||||
w[k] = p.1[k] + (q.1[k] - p.1[k]) * t;
|
||||
}
|
||||
(c, w)
|
||||
}
|
||||
|
||||
/// Whether a finite clip corner's ndc depth lies further outside `0..=1` than [`ndc_z`] moves back.
|
||||
fn off_plane(c: &[f32; 4]) -> bool {
|
||||
c.iter().all(|v| v.is_finite()) && !(-NDC_ROUNDING..=1.0 + NDC_ROUNDING).contains(&(f64::from(c[2]) / f64::from(c[3])))
|
||||
}
|
||||
|
||||
/// Clip a polygon (clip coords + original weights) against `0 ≤ z ≤ w`.
|
||||
fn clip_poly(poly: Vec<Corner>) -> Option<Vec<Corner>> {
|
||||
if poly.iter().all(|(c, _)| c[2] >= 0.0 && c[2] <= c[3]) {
|
||||
return Some(poly);
|
||||
}
|
||||
// Each corner carries whether it was clipped in f64.
|
||||
let mut p: Vec<(Corner, bool)> = poly.into_iter().map(|c| (c, false)).collect();
|
||||
for plane in 0..2 {
|
||||
if p.is_empty() {
|
||||
break;
|
||||
}
|
||||
let d = |c: &[f32; 4]| if plane == 0 { c[2] } else { c[3] - c[2] };
|
||||
let mut out = Vec::with_capacity(p.len() + 2);
|
||||
for i in 0..p.len() {
|
||||
let ((a, a_wide), (b, b_wide)) = (p[i], p[(i + 1) % p.len()]);
|
||||
let (da, db) = (d(&a.0), d(&b.0));
|
||||
if da >= 0.0 {
|
||||
out.push((a, a_wide));
|
||||
}
|
||||
if (da >= 0.0) != (db >= 0.0) {
|
||||
// A finite crossing whose depth lands further off the plane than `ndc_z` moves
|
||||
// back, in either direction of the edge, is clipped again in f64, and so is an
|
||||
// edge from a corner clipped in f64. The f64 crossing does not depend on the
|
||||
// direction, so the triangles on both sides of the edge get the same corner.
|
||||
let corner = f32_corner(a, b, da, db);
|
||||
if a_wide || b_wide || off_plane(&corner.0) || off_plane(&f32_corner(b, a, db, da).0) {
|
||||
let wide = |x: &Corner| (x.0.map(f64::from), x.1.map(f64::from));
|
||||
let (a, b) = (wide(&a), wide(&b));
|
||||
let dist = |c: &[f64; 4]| plane_distance(c, plane);
|
||||
let (c, w) = crossing_f64(a, b, dist(&a.0), dist(&b.0));
|
||||
if c.iter().any(|v| *v != 0.0 && v.abs() < f64::from(f32::MIN_POSITIVE)) {
|
||||
return None;
|
||||
}
|
||||
out.push(((c.map(|v| v as f32), w.map(|v| v as f32)), true));
|
||||
} else {
|
||||
out.push((corner, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
p = out;
|
||||
}
|
||||
Some(p.into_iter().map(|(c, _)| c).collect())
|
||||
}
|
||||
|
||||
/// How far past 0 or 1 [`ndc_z`] moves an ndc depth back to the end of the range.
|
||||
const NDC_ROUNDING: f64 = 4.0 * f32::EPSILON as f64;
|
||||
|
||||
/// The ndc depth of a corner clipped to `0 ≤ z ≤ w`, moved back to the end of the range when the
|
||||
/// division by `w` rounds past it by a few ulps (a corner on the near plane can give 1 + 2^-23). A
|
||||
/// depth further out is kept, and the depth test rejects it.
|
||||
#[inline]
|
||||
fn ndc_z(z: f32) -> f32 {
|
||||
const ROUNDING: f32 = 4.0 * f32::EPSILON;
|
||||
const ROUNDING: f32 = NDC_ROUNDING as f32;
|
||||
if (1.0..=1.0 + ROUNDING).contains(&z) {
|
||||
1.0
|
||||
} else if (-ROUNDING..0.0).contains(&z) {
|
||||
@@ -190,7 +238,9 @@ fn project(s: &Scene, clip: &[[f32; 4]], t: usize) -> Option<(Vec<ScreenCorner>,
|
||||
let tri = vec![(clip[ids[0]], [1.0, 0.0, 0.0]), (clip[ids[1]], [0.0, 1.0, 0.0]), (clip[ids[2]], [0.0, 0.0, 1.0])];
|
||||
let finite = |p: &[Corner]| p.iter().all(|(c, wt)| c.iter().chain(wt).all(|v| v.is_finite()));
|
||||
// The depth range in f32; when that overflows between far-apart corners, every plane in f64.
|
||||
let poly = clip_poly(tri.clone());
|
||||
let Some(poly) = clip_poly(tri.clone()) else {
|
||||
return project_wide(s, &clip_wide(&tri, &ALL_PLANES));
|
||||
};
|
||||
let poly = if finite(&poly) { clip_guard(poly) } else { clip_f64(&tri, &ALL_PLANES) };
|
||||
if poly.len() < 3 || !finite(&poly) {
|
||||
return None;
|
||||
@@ -210,16 +260,28 @@ fn project(s: &Scene, clip: &[[f32; 4]], t: usize) -> Option<(Vec<ScreenCorner>,
|
||||
// A tiny w overflows 1/w in f32: project in f64, with 1/w scaled by a common factor so the
|
||||
// largest is 1 (the interpolation weights use only their ratios). The scaled values stay in
|
||||
// f64, since a ratio below the f32 range would round to 0 and drop the corner's weight.
|
||||
let iw: Vec<f64> = poly.iter().map(|(c, _)| 1.0 / f64::from(c[3])).collect();
|
||||
let poly: Vec<WideCorner> = poly.iter().map(|(c, wt)| (c.map(f64::from), wt.map(f64::from))).collect();
|
||||
project_wide(s, &poly)
|
||||
}
|
||||
|
||||
/// The screen corners of a clipped polygon projected in `f64`, or `None` when fewer than three
|
||||
/// corners are left or one is not finite.
|
||||
fn project_wide(s: &Scene, poly: &[WideCorner]) -> Option<(Vec<ScreenCorner>, bool)> {
|
||||
if poly.len() < 3 || !poly.iter().all(|(c, wt)| c.iter().chain(wt).all(|v| v.is_finite())) {
|
||||
return None;
|
||||
}
|
||||
let (w, h) = (s.width as f64, s.height as f64);
|
||||
let iw: Vec<f64> = poly.iter().map(|(c, _)| 1.0 / c[3]).collect();
|
||||
let top = iw.iter().fold(0.0f64, |a, &b| a.max(b));
|
||||
let scr: Vec<ScreenCorner> = poly
|
||||
.iter()
|
||||
.zip(&iw)
|
||||
.map(|((c, wt), &iw)| {
|
||||
let (nx, ny) = (f64::from(c[0]) * iw, f64::from(c[1]) * iw);
|
||||
([(nx + 1.0) * 0.5 * w, (1.0 - ny) * 0.5 * h], ndc_z((f64::from(c[2]) * iw) as f32), iw / top, *wt)
|
||||
let (nx, ny) = (c[0] * iw, c[1] * iw);
|
||||
([(nx + 1.0) * 0.5 * w, (1.0 - ny) * 0.5 * h], ndc_z((c[2] * iw) as f32), iw / top, wt.map(|v| v as f32))
|
||||
})
|
||||
.collect();
|
||||
let ok = |s: &ScreenCorner| s.0.iter().all(|v| v.is_finite()) && s.1.is_finite() && s.2.is_finite();
|
||||
scr.iter().all(ok).then_some((scr, true))
|
||||
}
|
||||
|
||||
@@ -512,21 +574,27 @@ impl Band<'_> {
|
||||
/// triangle other than the pixel's visible one, inside the depth range as in
|
||||
/// [`Band::visibility`]. Triangles are
|
||||
/// visited in index order over their bounding boxes, and among fragments at equal depth the
|
||||
/// first triangle's is kept. Coverage tests count toward [`Limits::max_work`].
|
||||
/// first triangle's is kept. Each coverage test counts toward [`Limits::max_work`] next to the
|
||||
/// work `setup` charged. A triangle's candidate pixels are gathered in batches of 256, and each
|
||||
/// batch is charged before its tests run, so a band stops with [`RenderError::TooMuchWork`]
|
||||
/// without testing a batch that passes the limit. A band also stops after any triangle once the
|
||||
/// total of all bands is over the limit. The error reports `needed` as `limit + 1`, so it does
|
||||
/// not depend on the order the bands run in.
|
||||
fn fallback(&self, opaque: Pass, vis: &Visibility, discarded: &[bool]) -> Result<Vec<Option<FallbackFragment>>, RenderError> {
|
||||
let (s, w, y0, rows) = (self.s, self.w, self.y0, self.rows);
|
||||
let over = || RenderError::TooMuchWork { needed: self.limit.saturating_add(1), limit: self.limit };
|
||||
let mut best: Vec<Option<FallbackFragment>> = filled(rows * w, None)?;
|
||||
let mut batch = [(0usize, 0i32, 0i32); 256];
|
||||
for &tj in opaque.bins {
|
||||
let t2 = &opaque.tris[tj as usize];
|
||||
let mut tests = 0u64;
|
||||
for y in t2.bbox[1].max(y0)..t2.bbox[3].min(y0 + rows as i32) {
|
||||
let r = (y - y0) as usize * w;
|
||||
for x in t2.bbox[0]..t2.bbox[2] {
|
||||
let i = r + x as usize;
|
||||
if !discarded[i] || vis[i].0 == tj {
|
||||
continue;
|
||||
}
|
||||
tests += 1;
|
||||
let mut test = |entries: &[(usize, i32, i32)]| -> Result<(), RenderError> {
|
||||
let tests = entries.len() as u64;
|
||||
if self.spent.fetch_add(tests, Ordering::Relaxed).saturating_add(tests) > self.limit {
|
||||
return Err(over());
|
||||
}
|
||||
#[cfg(test)]
|
||||
tests::FALLBACK_TESTS.fetch_add(tests, Ordering::Relaxed);
|
||||
for &(i, x, y) in entries {
|
||||
if let Some((z, l2)) = cover(t2, x as f64 + 0.5, y as f64 + 0.5)
|
||||
&& nearer(z, best[i].map_or(EMPTY, |b| b.ndc_z))
|
||||
{
|
||||
@@ -536,10 +604,29 @@ impl Band<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let mut len = 0;
|
||||
for y in t2.bbox[1].max(y0)..t2.bbox[3].min(y0 + rows as i32) {
|
||||
let r = (y - y0) as usize * w;
|
||||
for x in t2.bbox[0]..t2.bbox[2] {
|
||||
let i = r + x as usize;
|
||||
if !discarded[i] || vis[i].0 == tj {
|
||||
continue;
|
||||
}
|
||||
batch[len] = (i, x, y);
|
||||
len += 1;
|
||||
if len == batch.len() {
|
||||
test(&batch)?;
|
||||
len = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
let needed = self.spent.fetch_add(tests, Ordering::Relaxed).saturating_add(tests);
|
||||
if needed > self.limit {
|
||||
return Err(RenderError::TooMuchWork { needed, limit: self.limit });
|
||||
if len != 0 {
|
||||
test(&batch[..len])?;
|
||||
}
|
||||
if self.spent.load(Ordering::Relaxed) > self.limit {
|
||||
return Err(over());
|
||||
}
|
||||
}
|
||||
Ok(best)
|
||||
@@ -610,8 +697,44 @@ pub fn try_render(s: &Scene, limits: &Limits) -> Result<Target, RenderError> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{cover, f32_crossing, fan, project};
|
||||
use crate::scene::Scene;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use super::{cover, f32_crossing, fan, project, try_render};
|
||||
use crate::scene::{Material, Scene, Vertex};
|
||||
use crate::{Limits, RenderError};
|
||||
|
||||
/// The coverage tests the search under discarded pixels has run.
|
||||
pub(super) static FALLBACK_TESTS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
#[test]
|
||||
fn the_search_under_discarded_pixels_runs_no_batch_past_the_work_limit() {
|
||||
// One band of 32 × 16 pixels covered by a far quad and, nearer, a masked quad whose every
|
||||
// fragment is discarded. Setup charges 4 × (512 + 1); the search tests each pixel three
|
||||
// times (once for each far triangle and once for the near triangle that does not hold it).
|
||||
let (w, h) = (32u32, 16u32);
|
||||
let mut s = Scene { width: w, height: h, ssaa: 1, linear_io: true, ortho: true, cam_fwd: [0.0, 0.0, 1.0], ..Scene::default() };
|
||||
s.clip = [[2.0 / w as f32, 0.0, 0.0, -1.0], [0.0, -2.0 / h as f32, 0.0, 1.0], [0.0, 0.0, -0.001, 1.0], [0.0, 0.0, 0.0, 1.0]];
|
||||
s.view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
|
||||
s.materials = vec![
|
||||
Material { unlit: true, double_sided: true, ..Material::default() },
|
||||
Material { base: [1.0, 1.0, 1.0, 0.0], alpha_mode: 1, unlit: true, double_sided: true, ..Material::default() },
|
||||
];
|
||||
for (m, z) in [(0, 100.0), (1, 50.0)] {
|
||||
let b = s.vertices.len() as u32;
|
||||
for (x, y) in [(0.0, 0.0), (w as f32, 0.0), (w as f32, h as f32), (0.0, h as f32)] {
|
||||
s.vertices.push(Vertex { pos: [x, y, z], normal: [0.0, 0.0, -1.0], uv: [0.0; 2], tangent: [1.0, 0.0, 0.0, 1.0], material: m });
|
||||
}
|
||||
s.indices.extend([b, b + 2, b + 1, b, b + 3, b + 2]);
|
||||
}
|
||||
s.opaque_count = 12;
|
||||
let full = 4 * (32 * 16 + 1) + 3 * 32 * 16;
|
||||
let limit = |max_work| Limits { max_work, ..Limits::default() };
|
||||
assert!(try_render(&s, &limit(full)).is_ok());
|
||||
FALLBACK_TESTS.store(0, Ordering::Relaxed);
|
||||
assert!(matches!(try_render(&s, &limit(full - 1)), Err(RenderError::TooMuchWork { .. })));
|
||||
let ran = FALLBACK_TESTS.load(Ordering::Relaxed);
|
||||
assert!(ran < 3 * 32 * 16, "{ran}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_projection_preserves_subnormal_weights_on_an_included_edge() {
|
||||
|
||||
@@ -124,6 +124,9 @@ pub struct Light {
|
||||
pub cos_outer: f32,
|
||||
/// 0 none, 1 smooth, 2 inverse square clamped. Other values return [`RenderError::BadLight`].
|
||||
pub falloff: u32,
|
||||
/// For point and spot lights with falloff 1 or 2, the distance factor stays at 1 within the radius.
|
||||
/// With falloff 2, a radius below 1 counts as 1; beyond that radius, the distance factor is (radius / distance)².
|
||||
/// Falloff 0 ignores the radius.
|
||||
pub radius: f32,
|
||||
pub falloff_distance: f32,
|
||||
/// First shadow map (point lights, and spot lights whose outer cone's half angle is over 1.40
|
||||
|
||||
@@ -521,11 +521,10 @@ fn attenuation(l: &Light, p: [f32; 3], to_l: [f32; 3], dist: f32) -> f32 {
|
||||
}
|
||||
}
|
||||
2 if l.kind != 0 => {
|
||||
if dist <= l.radius || (l.radius <= 0.0 && dist <= 1.0) {
|
||||
1.0
|
||||
} else {
|
||||
(l.radius.max(1.0) / dist).powi(2)
|
||||
}
|
||||
// The plateau and the inverse square use the same radius, at least 1, so the
|
||||
// factor never exceeds 1.
|
||||
let r = l.radius.max(1.0);
|
||||
if dist <= r { 1.0 } else { (r / dist).powi(2) }
|
||||
}
|
||||
_ => 1.0,
|
||||
};
|
||||
|
||||
@@ -1141,7 +1141,7 @@ fn overflowing_coverage_work_in_the_fallback_is_refused() {
|
||||
let setup = 4 * (4 * u64::from(height) + 1);
|
||||
assert_eq!(try_render(&s, &limits(|l| l.max_work = u64::MAX)).unwrap().color[0], WHITE);
|
||||
assert!(
|
||||
matches!(try_render(&s, &limits(|l| l.max_work = setup)), Err(RenderError::TooMuchWork { limit, needed }) if limit == setup && needed > setup)
|
||||
matches!(try_render(&s, &limits(|l| l.max_work = setup)), Err(RenderError::TooMuchWork { limit, needed }) if limit == setup && needed == setup + 1)
|
||||
);
|
||||
s.materials[1].base[3] = 1.0;
|
||||
assert!(try_render(&s, &limits(|l| l.max_work = setup)).is_ok());
|
||||
@@ -1390,6 +1390,32 @@ fn a_point_light_whose_squared_distance_overflows_f32_still_lights() {
|
||||
assert!((far.data[px][0] - near.data[px][0]).abs() < 1e-3 * near.data[px][0], "{:?} {:?}", far.data[px], near.data[px]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_square_falloff_with_a_radius_below_one_never_brightens_the_light() {
|
||||
// A clamped inverse-square point light 0.75 units from the pixel center (4.5, 4.5) of a quad.
|
||||
// With a radius of 0.5 it lights the pixel as fully as a radius of 1 does, and past 1 unit
|
||||
// both fall off the same.
|
||||
let mut s = quad_scene(8, 8, &[([0.0, 0.0, 8.0, 8.0], 500.0, WHITE)]);
|
||||
s.materials[0].unlit = false;
|
||||
let mut point = spot([4.5, 4.5, 499.25], [0.0, 0.0, 1.0], 1.0, 1.0);
|
||||
(point.kind, point.falloff, point.shadow) = (2, 2, -1);
|
||||
s.lights = vec![point];
|
||||
let px = 4 * 8 + 4;
|
||||
let mut lit = Vec::new();
|
||||
for z in [499.25, 497.0] {
|
||||
s.lights[0].pos[2] = z;
|
||||
s.lights[0].radius = 1.0;
|
||||
let (one, _) = try_render_cpu(&s, &Limits::default()).unwrap();
|
||||
s.lights[0].radius = 0.5;
|
||||
let (half, _) = try_render_cpu(&s, &Limits::default()).unwrap();
|
||||
assert!(one.data[px][0] > 0.01, "{z}: {:?}", one.data[px]);
|
||||
assert_eq!(bits4(&half.data), bits4(&one.data), "{z}");
|
||||
lit.push(one.data[px][0]);
|
||||
}
|
||||
// 3 units away the light falls off to (1 / 3)² of its full intensity.
|
||||
assert!((lit[1] * 9.0 - lit[0]).abs() < 1e-3 * lit[0], "{lit:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coordinates_from_two_to_the_twenty_third_texels_keep_the_half_texel_shift() {
|
||||
let texels = [[0.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0, 1.0]];
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
mod bounds;
|
||||
mod differential;
|
||||
mod moved;
|
||||
mod near_plane;
|
||||
mod opacity;
|
||||
mod work;
|
||||
|
||||
/// A verbatim copy of the app's previous code, run by `differential`.
|
||||
mod reference {
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
//! Triangles that cross the near plane (ndc depth 1), where clipping rounds.
|
||||
|
||||
use craft_raster3d::{Limits, Material, Scene, Vertex, try_render};
|
||||
|
||||
use crate::quad_scene;
|
||||
|
||||
const WHITE: [f32; 4] = [1.0; 4];
|
||||
|
||||
/// A `w` × `h` scene with an identity clip transform and an unlit, double-sided white material
|
||||
/// whose triangles are those of `corners` (clip positions, three per triangle), all opaque.
|
||||
fn identity_scene(w: u32, h: u32, corners: &[[f32; 3]]) -> Scene {
|
||||
let mut s = quad_scene(w, h, &[]);
|
||||
s.materials.push(Material { unlit: true, double_sided: true, ..Material::default() });
|
||||
s.clip = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
|
||||
for &pos in corners {
|
||||
s.vertices.push(Vertex { pos, normal: [0.0, 0.0, -1.0], uv: [0.0; 2], tangent: [1.0, 0.0, 0.0, 1.0], material: 0 });
|
||||
}
|
||||
s.indices = (0..corners.len() as u32).collect();
|
||||
s.opaque_count = corners.len() as u32;
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_near_plane_crossing_that_rounds_far_off_the_plane_is_still_drawn() {
|
||||
// The f32 crossings of the edges to the middle corner land more than 4 ulps past depth 1.
|
||||
let s = identity_scene(5, 5, &[[-1.0, -0.5, 0.264_506_85], [0.0, 8.690_391, 13.783_444], [1.0, -0.5, 0.264_506_85]]);
|
||||
let t = try_render(&s, &Limits::default()).unwrap();
|
||||
// Clipped at depth 1 the triangle spans ndc y -0.5 to 0, whose top edge runs through the
|
||||
// centers of row 2, so rows 2 and 3 are covered.
|
||||
for (i, c) in t.color.iter().enumerate().take(20).skip(10) {
|
||||
assert_eq!(*c, WHITE, "pixel {i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangles_that_share_an_edge_crossing_the_near_plane_leave_no_gap() {
|
||||
// Only the first triangle has a second crossing that lands far off the plane; the shared
|
||||
// edge's crossing is the same in both, so the pixel center beside it stays covered.
|
||||
let (a, b) = ([-0.3, -0.51, 0.0], [12.0, 20.4, 13.783_444]);
|
||||
let s = identity_scene(5, 5, &[a, b, [1.0, -0.5, 0.264_506_85], b, a, [-0.5, 1.0, 1.0]]);
|
||||
let t = try_render(&s, &Limits::default()).unwrap();
|
||||
assert_eq!(t.color[12][3], 1.0, "{:?}", t.color);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangles_that_share_an_edge_crossing_both_depth_planes_leave_no_gap() {
|
||||
let (a, b) = ([-1.0, -0.03, -8.44], [1.0, 0.03, 9.44]);
|
||||
let s = identity_scene(1, 1, &[a, b, [0.0, 1.0, 0.5], b, a, [0.0, -1.0, 0.5]]);
|
||||
let t = try_render(&s, &Limits::default()).unwrap();
|
||||
assert_eq!(t.color[0][3], 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clipped_near_plane_edge_with_rounded_depth_below_one_is_drawn() {
|
||||
// Both generated corners have z = 1 - 2^-24 and lie along screen row 2.
|
||||
let s = identity_scene(5, 5, &[[-1.0, -0.5, 0.0], [0.0, 2623.5002, 5248.0], [1.0, -0.5, 0.0]]);
|
||||
let t = try_render(&s, &Limits::default()).unwrap();
|
||||
for x in 0..5 {
|
||||
assert_eq!(t.color[2 * 5 + x], WHITE, "column {x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_depth_crossing_that_overflows_f32_is_still_clipped_in_f64() {
|
||||
// The edges to the third corner cross the far plane with a depth difference that overflows
|
||||
// f32, so the polygon is clipped again in f64, which keeps the left pixel center inside.
|
||||
let mut s = identity_scene(2, 1, &[[-6.099998e37, 8e37, 5e37], [-6.099998e37, -8e37, 5e37], [2.4799903e37, 0.0, -3.4e38]]);
|
||||
s.clip[3][3] = 1e38;
|
||||
let t = try_render(&s, &Limits::default()).unwrap();
|
||||
assert_eq!(t.color[0][3], 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subnormal_depth_crossing_with_positive_w_is_still_drawn() {
|
||||
let mut s = identity_scene(1, 1, &[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]);
|
||||
let scale = f32::from_bits(1);
|
||||
s.clip = [[-12.0, 10.0, 0.0, 0.0], [-8.0, -9.0, 10.0, 0.0], [8.0, -7.0, 1.0, 0.0], [-7.0, 8.0, 0.0, 0.0]];
|
||||
for row in &mut s.clip {
|
||||
for v in row {
|
||||
*v *= scale;
|
||||
}
|
||||
}
|
||||
let t = try_render(&s, &Limits::default()).unwrap();
|
||||
assert_eq!(t.color[0], WHITE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subnormal_depth_crossing_preserves_projected_edge_coverage() {
|
||||
let mut s = identity_scene(5, 5, &[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]);
|
||||
let scale = f32::from_bits(1);
|
||||
s.clip = [[3.0, -2.0, -2.0, 0.0], [0.0, -6.0, 5.0, 0.0], [8.0, 5.0, 3.0, 0.0], [5.0, 8.0, 4.0, 0.0]];
|
||||
for row in &mut s.clip {
|
||||
for v in row {
|
||||
*v *= scale;
|
||||
}
|
||||
}
|
||||
let t = try_render(&s, &Limits::default()).unwrap();
|
||||
assert_eq!(t.color[3 * 5 + 2], WHITE);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! The work limit of the search under discarded pixels.
|
||||
|
||||
use craft_raster3d::{RenderError, Scene, try_render};
|
||||
|
||||
use crate::{limits, quad_scene};
|
||||
|
||||
const WHITE: [f32; 4] = [1.0; 4];
|
||||
const FAR: [f32; 4] = [0.25, 0.5, 0.75, 1.0];
|
||||
|
||||
/// Two screen-filling quads; the nearer one is a masked material whose alpha fails the cutoff, so
|
||||
/// every pixel is discarded and the search for a surviving fragment visits the farther quad.
|
||||
fn discarding_scene(w: u32, h: u32) -> Scene {
|
||||
let (fw, fh) = (w as f32, h as f32);
|
||||
let mut s = quad_scene(w, h, &[([0.0, 0.0, fw, fh], 100.0, FAR), ([0.0, 0.0, fw, fh], 50.0, WHITE)]);
|
||||
s.materials[1].alpha_mode = 1;
|
||||
s.materials[1].base[3] = 0.0;
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_work_count_of_the_search_under_discarded_pixels_does_not_depend_on_the_bands() {
|
||||
// Two bands of 16 rows; each band's first farther triangle makes 64 tests, so band 0 alone
|
||||
// passes the limit.
|
||||
let s = discarding_scene(4, 32);
|
||||
let setup = 4 * (4 * 32 + 1);
|
||||
assert!(matches!(
|
||||
try_render(&s, &limits(|l| l.max_work = setup)),
|
||||
Err(RenderError::TooMuchWork { limit, needed }) if limit == setup && needed == setup + 1
|
||||
));
|
||||
// The search tests each pixel of a band three times: once for each farther triangle and once
|
||||
// for the nearer triangle that does not hold it. A limit that holds one band's tests but not
|
||||
// both is passed only by the bands together.
|
||||
let per_band = 3 * 4 * 16;
|
||||
let band = discarding_scene(4, 16);
|
||||
let band_setup = 4 * (4 * 16 + 1);
|
||||
assert!(try_render(&band, &limits(|l| l.max_work = band_setup + per_band)).is_ok());
|
||||
assert!(try_render(&band, &limits(|l| l.max_work = band_setup + per_band - 1)).is_err());
|
||||
let limit = setup + per_band;
|
||||
assert!(matches!(
|
||||
try_render(&s, &limits(|l| l.max_work = limit)),
|
||||
Err(RenderError::TooMuchWork { limit: l, needed }) if l == limit && needed == limit + 1
|
||||
));
|
||||
assert!(try_render(&s, &limits(|l| l.max_work = setup + 2 * per_band)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_search_of_several_batches_counts_every_test_once() {
|
||||
// One band of 32 × 16 pixels: each farther triangle's bounding box holds 512 discarded pixels,
|
||||
// so its tests are charged in two full batches of 256. The search tests each pixel three times.
|
||||
let s = discarding_scene(32, 16);
|
||||
let setup = 4 * (32 * 16 + 1);
|
||||
let search = 3 * 32 * 16;
|
||||
let t = try_render(&s, &limits(|l| l.max_work = setup + search)).unwrap();
|
||||
assert!(t.color.iter().all(|&c| c == FAR));
|
||||
assert!(matches!(
|
||||
try_render(&s, &limits(|l| l.max_work = setup + search - 1)),
|
||||
Err(RenderError::TooMuchWork { limit, needed }) if limit == setup + search - 1 && needed == limit + 1
|
||||
));
|
||||
}
|
||||
+177
-1
@@ -27,6 +27,11 @@ pub trait Kind: Clone + Default {
|
||||
/// styles and stylesheets, as well as the presentation properties the reader tracks itself.
|
||||
const PROPERTIES: &'static [&'static str] = &[];
|
||||
|
||||
/// Optional raw attributes to retain on source groups (for example an editor's
|
||||
/// document-local group ID). Unlike computed properties, these do not inherit.
|
||||
/// At most 16 attributes per group, with values bounded by `MAX_GROUP_LABEL`.
|
||||
const GROUP_ATTRIBUTES: &'static [GroupAttribute] = &[];
|
||||
|
||||
/// The tag an element sets, from its computed style and `class` attribute; `None` inherits
|
||||
/// its parent's.
|
||||
fn of(style: &StyleMap, class: &str) -> Option<Self>;
|
||||
@@ -81,18 +86,69 @@ pub struct Shape<K> {
|
||||
/// `inkscape:groupmode="layer"`, named by its `inkscape:label`, else its `id`, else empty.
|
||||
/// `None` outside any layer. At most [`MAX_LAYER_NAME`] characters.
|
||||
pub layer: Option<String>,
|
||||
/// Innermost retained source group, an index into [`Imported::groups`].
|
||||
pub group: Option<usize>,
|
||||
}
|
||||
|
||||
/// Most characters of a layer name kept in [`Shape::layer`].
|
||||
pub const MAX_LAYER_NAME: usize = 256;
|
||||
const INKSCAPE_NS: &str = "http://www.inkscape.org/namespaces/inkscape";
|
||||
|
||||
/// Maximum characters retained for a group's source ID, label or requested attribute.
|
||||
pub const MAX_GROUP_LABEL: usize = 256;
|
||||
const MAX_GROUP_ATTRIBUTES: usize = 16;
|
||||
const MAX_GROUP_METADATA_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
/// An attribute selector for group metadata. Namespace URIs, not document-local
|
||||
/// prefixes, identify namespaced XML attributes.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct GroupAttribute {
|
||||
pub namespace: Option<&'static str>,
|
||||
pub name: &'static str,
|
||||
}
|
||||
|
||||
impl GroupAttribute {
|
||||
pub const fn unqualified(name: &'static str) -> Self {
|
||||
Self { namespace: None, name }
|
||||
}
|
||||
|
||||
pub const fn namespaced(namespace: &'static str, name: &'static str) -> Self {
|
||||
Self { namespace: Some(namespace), name }
|
||||
}
|
||||
}
|
||||
|
||||
/// A requested attribute and its bounded raw value.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct GroupMetadata {
|
||||
pub attribute: GroupAttribute,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
/// A source SVG `<g>` containing imported drawable geometry. Groups are in traversal order
|
||||
/// (parents before children). Each expansion of a reused group has a distinct index even if
|
||||
/// its source ID is the same; a source ID is a label, not a unique imported identity.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Group<K> {
|
||||
pub parent: Option<usize>,
|
||||
/// Raw source ID, if present.
|
||||
pub source_id: Option<String>,
|
||||
/// Inkscape label, when present, otherwise the source ID.
|
||||
pub label: Option<String>,
|
||||
/// Effective caller-defined kind after the normal style cascade.
|
||||
pub kind: K,
|
||||
/// Only attributes explicitly requested by [`Kind::GROUP_ATTRIBUTES`].
|
||||
pub attributes: Vec<GroupMetadata>,
|
||||
}
|
||||
|
||||
/// What [`import`] read. Shapes may lie outside the `width_mm` × `height_mm` viewport.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Imported<K> {
|
||||
pub width_mm: f64,
|
||||
pub height_mm: f64,
|
||||
pub shapes: Vec<Shape<K>>,
|
||||
/// Ancestors of the returned shapes; empty groups are omitted. A caller that drops
|
||||
/// geometries after clipping may prune their groups as part of its model mapping.
|
||||
pub groups: Vec<Group<K>>,
|
||||
pub clips: Vec<Clip>,
|
||||
/// What was skipped or approximated. A caller adding its own goes through [`push_warning`]
|
||||
/// with `dropped_warnings`, to keep the list bounded.
|
||||
@@ -386,6 +442,7 @@ struct ImportState<K> {
|
||||
clips: Vec<usize>,
|
||||
/// The innermost Inkscape layer's name ([`Shape::layer`]).
|
||||
layer: Option<std::rc::Rc<str>>,
|
||||
group: Option<usize>,
|
||||
}
|
||||
|
||||
impl<K: Kind> Default for ImportState<K> {
|
||||
@@ -398,6 +455,7 @@ impl<K: Kind> Default for ImportState<K> {
|
||||
inherited_style: std::collections::HashMap::new(),
|
||||
clips: Vec::new(),
|
||||
layer: None,
|
||||
group: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -424,7 +482,7 @@ pub(crate) const MAX_CSS_SELECTOR_CHECKS: usize = 5_000_000;
|
||||
/// combinators, `:not()`, `:first-child`, `:last-child`, `:root`, selector lists, and a bounded
|
||||
/// presentation-property cascade. Curves stay curves: nothing is flattened.
|
||||
///
|
||||
/// Each shape carries its stroke paint as written and the `clip-path` regions that apply to it;
|
||||
/// Each shape carries its source group ancestry, stroke paint as written and the `clip-path` regions that apply to it;
|
||||
/// [`Imported::clipped_path`] returns its geometry with those clips applied.
|
||||
///
|
||||
/// What cannot be represented is skipped with a line in [`Imported::warnings`]: `<text>` (no
|
||||
@@ -473,6 +531,8 @@ pub fn import<K: Kind>(svg: &str, name: &str) -> Result<Imported<K>, Error> {
|
||||
reference_stack: Vec::new(),
|
||||
instance_count: 0,
|
||||
shapes: Vec::new(),
|
||||
groups: Vec::new(),
|
||||
group_metadata_bytes: 0,
|
||||
clips: Vec::new(),
|
||||
clip_pieces: 0,
|
||||
segments: 0,
|
||||
@@ -482,16 +542,50 @@ pub fn import<K: Kind>(svg: &str, name: &str) -> Result<Imported<K>, Error> {
|
||||
};
|
||||
let base = ImportState { transform: viewport, ..ImportState::default() };
|
||||
import_node(root, base, 0, &mut context)?;
|
||||
let groups = retain_drawable_groups(context.groups, &mut context.shapes);
|
||||
Ok(Imported {
|
||||
width_mm,
|
||||
height_mm,
|
||||
shapes: context.shapes,
|
||||
groups,
|
||||
clips: context.clips,
|
||||
warnings: context.warnings,
|
||||
dropped_warnings: context.dropped_warnings,
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep exactly the groups that own drawable shapes and their ancestors, remapping the
|
||||
/// indices without another XML walk. Parent groups precede their descendants.
|
||||
fn retain_drawable_groups<K>(groups: Vec<Group<K>>, shapes: &mut [Shape<K>]) -> Vec<Group<K>> {
|
||||
let mut used = vec![false; groups.len()];
|
||||
for shape in shapes.iter() {
|
||||
if let Some(index) = shape.group {
|
||||
used[index] = true;
|
||||
}
|
||||
}
|
||||
for (index, group) in groups.iter().enumerate().rev() {
|
||||
if used[index]
|
||||
&& let Some(parent) = group.parent
|
||||
{
|
||||
used[parent] = true;
|
||||
}
|
||||
}
|
||||
let mut remap = vec![None; groups.len()];
|
||||
let mut retained = Vec::new();
|
||||
for (index, mut group) in groups.into_iter().enumerate() {
|
||||
if !used[index] {
|
||||
continue;
|
||||
}
|
||||
group.parent = group.parent.and_then(|parent| remap[parent]);
|
||||
remap[index] = Some(retained.len());
|
||||
retained.push(group);
|
||||
}
|
||||
for shape in shapes {
|
||||
shape.group = shape.group.and_then(|index| remap[index]);
|
||||
}
|
||||
retained
|
||||
}
|
||||
|
||||
struct ImportContext<'a, 'input, K> {
|
||||
visited: usize,
|
||||
path_name: &'a str,
|
||||
@@ -500,6 +594,8 @@ struct ImportContext<'a, 'input, K> {
|
||||
reference_stack: Vec<String>,
|
||||
instance_count: usize,
|
||||
shapes: Vec<Shape<K>>,
|
||||
groups: Vec<Group<K>>,
|
||||
group_metadata_bytes: usize,
|
||||
clips: Vec<Clip>,
|
||||
clip_pieces: usize,
|
||||
segments: usize,
|
||||
@@ -609,6 +705,32 @@ fn import_node<'a, 'input, K: Kind>(
|
||||
state.display_none = true;
|
||||
}
|
||||
}
|
||||
if tag == "g" && !state.display_none {
|
||||
let bounded = |value: &str| value.chars().take(MAX_GROUP_LABEL).collect::<String>();
|
||||
let source_id = node.attribute("id").map(bounded);
|
||||
let label = node.attribute((INKSCAPE_NS, "label")).map(bounded).or_else(|| source_id.clone());
|
||||
let attributes: Vec<GroupMetadata> = K::GROUP_ATTRIBUTES
|
||||
.iter()
|
||||
.take(MAX_GROUP_ATTRIBUTES)
|
||||
.filter_map(|&attribute| {
|
||||
let value = match attribute.namespace {
|
||||
Some(namespace) => node.attribute((namespace, attribute.name)),
|
||||
None => node.attribute(attribute.name),
|
||||
}?;
|
||||
Some(GroupMetadata { attribute, value: bounded(value) })
|
||||
})
|
||||
.collect();
|
||||
let bytes = source_id.as_ref().map_or(0, String::len)
|
||||
+ label.as_ref().map_or(0, String::len)
|
||||
+ attributes.iter().map(|item| item.value.len()).sum::<usize>();
|
||||
context.group_metadata_bytes = context.group_metadata_bytes.saturating_add(bytes);
|
||||
if context.group_metadata_bytes > MAX_GROUP_METADATA_BYTES {
|
||||
return Err(svg_error(context.path_name, "SVG group metadata exceeds the import limit"));
|
||||
}
|
||||
let index = context.groups.len();
|
||||
context.groups.push(Group { parent: state.group, source_id, label, kind: state.kind.clone(), attributes });
|
||||
state.group = Some(index);
|
||||
}
|
||||
if !state.display_none && !state.visibility_hidden {
|
||||
for (property, effect) in [("mask", "the art is imported unmasked"), ("filter", "the art is imported unfiltered")] {
|
||||
if style.get(property).is_some_and(|v| v != "none") {
|
||||
@@ -699,6 +821,7 @@ fn import_node<'a, 'input, K: Kind>(
|
||||
fill_rule: if style.get("fill-rule").is_some_and(|value| value == "evenodd") { FillRule::EvenOdd } else { FillRule::NonZero },
|
||||
clips: state.clips.clone(),
|
||||
layer: state.layer.as_deref().map(str::to_string),
|
||||
group: state.group,
|
||||
}));
|
||||
}
|
||||
for child in node.children().filter(|n| n.is_element()) {
|
||||
@@ -1937,6 +2060,8 @@ mod tests {
|
||||
}
|
||||
|
||||
impl Kind for Tag {
|
||||
const GROUP_ATTRIBUTES: &'static [GroupAttribute] =
|
||||
&[GroupAttribute::unqualified("data-group"), GroupAttribute::namespaced("urn:editor-metadata", "group-id")];
|
||||
const PROPERTIES: &'static [&'static str] = &["data-kind"];
|
||||
|
||||
fn of(style: &StyleMap, class: &str) -> Option<Tag> {
|
||||
@@ -2160,6 +2285,57 @@ mod tests {
|
||||
assert!(near(b.x0, 12.0) && near(b.y0, 24.0) && near(b.width(), 6.0), "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_ancestry_uses_the_geometry_walk_and_keeps_source_metadata() {
|
||||
let got = read(
|
||||
r#"<svg xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape">
|
||||
<style>.hidden { display: none; }</style>
|
||||
<g id="unused"><g/></g>
|
||||
<g id="decor" inkscape:label="Decorative motif" data-group="15" xmlns:meta="urn:editor-metadata" meta:group-id="42">
|
||||
<g class="hidden"><rect width="2" height="2"/></g>
|
||||
<g id="details"><rect width="3" height="4"/></g>
|
||||
<path d="M10 3L12 3"/>
|
||||
</g>
|
||||
<rect x="20" width="5" height="5"/>
|
||||
</svg>"#,
|
||||
);
|
||||
assert_eq!(got.shapes.len(), 3);
|
||||
assert_eq!(got.groups.len(), 2);
|
||||
assert_eq!(got.groups[0].source_id.as_deref(), Some("decor"));
|
||||
assert_eq!(got.groups[0].label.as_deref(), Some("Decorative motif"));
|
||||
assert_eq!(
|
||||
got.groups[0].attributes,
|
||||
vec![
|
||||
GroupMetadata { attribute: GroupAttribute::unqualified("data-group"), value: "15".into() },
|
||||
GroupMetadata { attribute: GroupAttribute::namespaced("urn:editor-metadata", "group-id"), value: "42".into() },
|
||||
]
|
||||
);
|
||||
assert!(got.groups[0].parent.is_none());
|
||||
assert_eq!(got.groups[1].source_id.as_deref(), Some("details"));
|
||||
assert_eq!(got.groups[1].parent, Some(0));
|
||||
assert!(got.groups[1].attributes.is_empty());
|
||||
assert_eq!(got.shapes.iter().map(|s| s.group).collect::<Vec<_>>(), [Some(1), Some(0), None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_use_groups_have_distinct_membership_at_each_site() {
|
||||
let got = read(
|
||||
r##"<svg><defs>
|
||||
<g id="motif"><g id="detail"><rect width="5" height="6"/></g></g>
|
||||
</defs><g id="page">
|
||||
<use href="#motif"/>
|
||||
<use href="#motif" x="20"/>
|
||||
</g>
|
||||
</svg>"##,
|
||||
);
|
||||
assert_eq!(got.shapes.len(), 2);
|
||||
assert_eq!(got.groups.len(), 5);
|
||||
assert_eq!(got.groups.iter().map(|g| g.parent).collect::<Vec<_>>(), [None, Some(0), Some(1), Some(0), Some(3)]);
|
||||
assert_eq!(got.shapes.iter().map(|s| s.group).collect::<Vec<_>>(), [Some(2), Some(4)]);
|
||||
assert_eq!(got.groups[1].source_id, got.groups[3].source_id);
|
||||
assert!(bounds(&got, 1).x0 > bounds(&got, 0).x0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_use_instances_take_x_y_transform_and_symbol_viewboxes() {
|
||||
let got = read(
|
||||
|
||||
@@ -305,6 +305,7 @@ struct Settled {
|
||||
keys: BodyKeys,
|
||||
/// The wheel share the canvas took this pass, handed on to its body.
|
||||
wheel: Option<Wheel>,
|
||||
wheel_token: Option<crate::runtime::wheel::ClaimToken>,
|
||||
/// A middle-button autoscroll or a held middle pan runs.
|
||||
auto_scrolling: bool,
|
||||
/// The mark of a running middle-button autoscroll, in screen points.
|
||||
@@ -480,7 +481,15 @@ impl<'a> Canvas<'a> {
|
||||
let mut zoom_anchor = None;
|
||||
let wheel = cx.take_wheel();
|
||||
let wheeled = wheel.is_some();
|
||||
if let Some(wheel) = &wheel {
|
||||
// A share of a gesture the body claimed (`CanvasSpace::claim_wheel`) goes to the body alone: the view stays, and
|
||||
// the motion the eased wheel and the eased wheel zoom still owe is dropped.
|
||||
if crate::runtime::wheel::claimed(&ctx, id) || wheel.as_ref().is_some_and(|wheel| wheel.claimed) {
|
||||
motion.glide.stop();
|
||||
cx.stop_wheel_ease();
|
||||
motion.wheel_zoom.stop_if(true);
|
||||
motion.wheel = WheelNavigation::default();
|
||||
}
|
||||
if let Some(wheel) = wheel.as_ref().filter(|wheel| !wheel.claimed) {
|
||||
let read = self.read_wheel(cx, &mut motion, &mut view, wheel, now);
|
||||
line_pan = read.line_pan;
|
||||
jumped |= read.jumped;
|
||||
@@ -618,7 +627,8 @@ impl<'a> Canvas<'a> {
|
||||
let easing = motion.animation.running();
|
||||
let mark = motion.autoscroll.mark();
|
||||
motion.restore(&ctx, id);
|
||||
Settled { target, shown, easing, keys, wheel, auto_scrolling, mark, swallowing, zoom_anchor }
|
||||
let wheel_token = crate::runtime::wheel::claim_token(&ctx, id);
|
||||
Settled { target, shown, easing, keys, wheel, wheel_token, auto_scrolling, mark, swallowing, zoom_anchor }
|
||||
}
|
||||
|
||||
/// One pass's wheel on `view`: a pan the eased wheel pays out later, or a pan, zoom or turn applied now, and the
|
||||
@@ -778,6 +788,7 @@ impl<'a> Canvas<'a> {
|
||||
.with_precise(self.precise_cursors != caps_lock)
|
||||
.with_zoom_scheme(scheme)
|
||||
.with_wheel(wheel)
|
||||
.with_wheel_token(self.settled.and_then(|settled| settled.wheel_token))
|
||||
.with_canvas(id);
|
||||
Some(match self.picture {
|
||||
Some(slot) => space.with_picture(slot),
|
||||
|
||||
@@ -163,6 +163,7 @@ impl TouchpadGlide {
|
||||
|
||||
/// Stops a glide (the view hit a limit, a press, a key move, a zoom, a view command).
|
||||
pub(crate) fn stop(&mut self) {
|
||||
self.samples.clear();
|
||||
self.velocity = Vec2::ZERO;
|
||||
}
|
||||
|
||||
@@ -204,7 +205,7 @@ impl TouchpadGlide {
|
||||
/// Reads the pass's wheel share at `now`; any wheel input stops a glide, a touchpad gesture's end may start one.
|
||||
/// `glide` is false where the view must not glide this pass (Touchpad Glide off, a zoom, a dialog).
|
||||
pub(crate) fn read(&mut self, wheel: &Wheel, now: f64, glide: bool) {
|
||||
self.stop();
|
||||
self.velocity = Vec2::ZERO;
|
||||
// Zooming, a mouse wheel and sideways Shift scrolling never glide.
|
||||
if wheel.unit != WheelUnit::Point || wheel.mods.cmd || wheel.mods.ctrl || wheel.mods.shift || wheel.zoom != 1.0 {
|
||||
self.samples.clear();
|
||||
@@ -326,3 +327,29 @@ fn document_bounds(view: &CanvasView, size: Size) -> Option<Rect> {
|
||||
let bounds = quad.iter().skip(1).fold(Rect::from_min_max(quad[0], quad[0]), |r, &p| r.union(Rect::from_min_max(p, p)));
|
||||
(bounds.is_finite() && view.rect.is_finite()).then_some(bounds)
|
||||
}
|
||||
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod trials {
|
||||
use super::TouchpadGlide;
|
||||
use crate::testing::trial;
|
||||
use egui::Vec2;
|
||||
|
||||
/// One sample of a touchpad swipe upward, in points: the glide's input, not a size of anything drawn.
|
||||
const SWIPE: Vec2 = Vec2::new(0.0, -30.0);
|
||||
|
||||
#[trial]
|
||||
fn stopping_a_touchpad_glide_clears_its_lift_samples() {
|
||||
let mut glide = TouchpadGlide::default();
|
||||
glide.push(0.0, SWIPE);
|
||||
glide.push(0.01, SWIPE);
|
||||
assert_ne!(glide.lift_velocity(0.02), Vec2::ZERO);
|
||||
glide.velocity = glide.lift_velocity(0.02);
|
||||
|
||||
glide.stop();
|
||||
|
||||
assert!(!glide.gliding());
|
||||
assert!(glide.samples.is_empty());
|
||||
glide.push(0.03, Vec2::new(0.0, -1.0));
|
||||
assert_eq!(glide.lift_velocity(0.04), Vec2::ZERO);
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ pub struct CanvasSpace {
|
||||
/// The canvas's picture slot for this pass, which [`paint_picture`](Self::paint_picture) appends to; `None` in a
|
||||
/// measuring pass.
|
||||
picture: Option<PaintSlot>,
|
||||
wheel: Option<craft_behavior::Wheel>,
|
||||
wheel: Option<(craft_behavior::Wheel, Option<crate::runtime::wheel::ClaimToken>)>,
|
||||
zoom_anchor: Option<Pos2>,
|
||||
}
|
||||
|
||||
@@ -73,13 +73,21 @@ impl CanvasSpace {
|
||||
|
||||
/// The wheel share the canvas read this pass, for a body that pages by wheel to read once.
|
||||
pub fn wheel(&self) -> Option<craft_behavior::Wheel> {
|
||||
self.wheel
|
||||
self.wheel.map(|(wheel, _)| wheel)
|
||||
}
|
||||
|
||||
/// This space with the wheel share the canvas read this pass.
|
||||
/// This space with the wheel share the canvas read.
|
||||
#[must_use]
|
||||
pub fn with_wheel(mut self, wheel: Option<craft_behavior::Wheel>) -> Self {
|
||||
self.wheel = wheel;
|
||||
self.wheel = wheel.map(|wheel| (wheel, None));
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub(crate) fn with_wheel_token(mut self, token: Option<crate::runtime::wheel::ClaimToken>) -> Self {
|
||||
if let Some((_, claim)) = self.wheel.as_mut() {
|
||||
*claim = token;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -298,6 +306,29 @@ impl CanvasSpace {
|
||||
nudge
|
||||
}
|
||||
|
||||
/// Claims this pass's wheel share ([`wheel`](Self::wheel)) for the canvas's body, recording `spent`, the part of
|
||||
/// the claimed motion the body used up, in its own unit, and returning whether the claim succeeded. The gesture's
|
||||
/// later shares carry `Wheel::claimed` and count only the claimed shares in `claimed_gathered`,
|
||||
/// `claimed_zoom_gathered` and `claimed_spent`, so a body that turns a gesture into steps keeps no state of its
|
||||
/// own. A second claim in the same pass replaces the first.
|
||||
/// The canvas must own the gesture and have a share in the running pass. A share returned by `wheel` can belong
|
||||
/// to a gesture another scroller owns; that share cannot be claimed. A snapshot from another share cannot claim the
|
||||
/// running pass's share, including after a viewport is recreated. The body should act only on an accepted claim.
|
||||
pub fn claim_wheel(&self, ctx: &egui::Context, spent: Vec2) -> bool {
|
||||
if let (Some(canvas), Some((_, Some(token)))) = (self.canvas, self.wheel) {
|
||||
return crate::runtime::wheel::claim(ctx, canvas, token, spent);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Marks the running wheel gesture as begun or gone on under a modal, for one of the app's own modal windows that
|
||||
/// the wheel service does not see. The gesture's later shares carry `Wheel::modal` until it ends.
|
||||
pub fn mark_wheel_modal(&self, ctx: &egui::Context) {
|
||||
if let Some(canvas) = self.canvas {
|
||||
crate::runtime::wheel::mark_modal(ctx, canvas);
|
||||
}
|
||||
}
|
||||
|
||||
/// Device pixels per document unit (1 is 100 %) of the view at this scale.
|
||||
pub fn zoom_device(&self) -> f64 {
|
||||
zoom::device(&self.view, self.pixels_per_point)
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
use craft_behavior::CanvasView;
|
||||
use craft_behavior::kurbo::{Point, Size};
|
||||
use craft_ui::canvas::{Canvas, NavigationOptions};
|
||||
use craft_ui::canvas::{Canvas, CanvasSpace, NavigationOptions, WheelScheme, canvas_space};
|
||||
use craft_ui::contract::{Common, Component, Container, ContainerProps, Cx, Mount, Overlay, Props as _, Role, ShowContainer as _};
|
||||
use craft_ui::style::StyleCx;
|
||||
use craft_ui::testing::{Fixture, pointer, trial};
|
||||
use craft_ui::testing::{Fixture, Frames, pointer, trial};
|
||||
use craft_ui_test_kit::contract::PlainStyle;
|
||||
use egui::{Response, Vec2};
|
||||
use egui::{Response, TouchPhase, Vec2};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
@@ -81,3 +81,529 @@ fn the_wheel_over_a_canvas_under_a_modal_moves_nothing() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A body that claims a wheel gesture (`CanvasSpace::claim_wheel`) reads the rest of it alone: the later shares reach
|
||||
/// the body, and the view does not move by them.
|
||||
#[trial]
|
||||
fn the_rest_of_a_wheel_gesture_the_body_claimed_does_not_move_the_view() {
|
||||
for eased in [false, true] {
|
||||
claimed_gesture_keeps_the_view(eased);
|
||||
}
|
||||
}
|
||||
|
||||
/// The claimed rest of a gesture of point scroll, or with `eased` of eased wheel lines whose first notch still owes
|
||||
/// motion when the body claims the gesture.
|
||||
fn claimed_gesture_keeps_the_view(eased: bool) {
|
||||
let mut options = NavigationOptions::default();
|
||||
options.eased_wheel = eased;
|
||||
let event = move || if eased { pointer::wheel_lines(-1.0) } else { pointer::wheel(-30.0) };
|
||||
let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0)));
|
||||
let claims = Rc::new(Cell::new(false));
|
||||
let read = Rc::new(Cell::new(0_u32));
|
||||
let (shown, claiming, reads) = (Rc::clone(&view), Rc::clone(&claims), Rc::clone(&read));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut given = shown.get();
|
||||
given.rect = ui.available_rect_before_wrap();
|
||||
let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| {
|
||||
if let Some(space) = canvas_space(&body.env)
|
||||
&& space.wheel().is_some()
|
||||
{
|
||||
reads.set(reads.get() + 1);
|
||||
if claiming.get() {
|
||||
assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO), "the canvas owns this gesture");
|
||||
}
|
||||
}
|
||||
});
|
||||
shown.set(canvas.output.view.unwrap_or(given));
|
||||
});
|
||||
fixture.settle();
|
||||
let at = view.get().rect.center() + Vec2::new(0.0, 150.0);
|
||||
fixture.frame(vec![pointer::moved(at)]);
|
||||
let start = view.get();
|
||||
fixture.frame(vec![event()]);
|
||||
fixture.idle(40);
|
||||
assert!(view.get().center.y > start.center.y + 1.0, "eased {eased}: precondition: an unclaimed share scrolls the canvas");
|
||||
|
||||
// The first share of the gesture moves the view before the body claims it; an eased notch still owes motion.
|
||||
claims.set(true);
|
||||
fixture.frame(vec![event()]);
|
||||
let claimed = view.get();
|
||||
// The motion the claimed notch still owed is dropped, with no more wheel input too.
|
||||
fixture.idle(5);
|
||||
let still = view.get();
|
||||
assert!((still.center.y - claimed.center.y).abs() < 1e-3, "eased {eased}: owed motion moved the view: {claimed:?} -> {still:?}");
|
||||
read.set(0);
|
||||
for _ in 0..3 {
|
||||
fixture.frame(vec![event()]);
|
||||
}
|
||||
assert_eq!(read.get(), 3, "eased {eased}: the body reads every share of the claimed gesture");
|
||||
claims.set(false);
|
||||
fixture.idle(40);
|
||||
let after = view.get();
|
||||
assert!(
|
||||
(after.center.y - claimed.center.y).abs() < 1e-3 && after.zoom == claimed.zoom,
|
||||
"eased {eased}: the view moved: {claimed:?} -> {after:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_canvas_space_with_a_supplied_wheel_share_has_no_claim_token() {
|
||||
let read = Rc::new(Cell::new(0_u32));
|
||||
let reads = Rc::clone(&read);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let view = CanvasView::new(ui.available_rect_before_wrap(), Point::new(2000.0, 2000.0), 1.0);
|
||||
Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(view).show(ui, |ui, body| {
|
||||
if let Some(space) = canvas_space(&body.env)
|
||||
&& let Some(wheel) = space.wheel()
|
||||
{
|
||||
let supplied = space.with_wheel(Some(wheel));
|
||||
assert_eq!(supplied.wheel(), Some(wheel));
|
||||
assert!(!supplied.claim_wheel(ui.ctx(), Vec2::ZERO), "a supplied share has no claim token");
|
||||
assert!(supplied.with_wheel(None).wheel().is_none());
|
||||
assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO), "the canvas's original share keeps its token");
|
||||
reads.set(reads.get() + 1);
|
||||
}
|
||||
});
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.frame(vec![pointer::moved(egui::Pos2::new(200.0, 200.0))]);
|
||||
fixture.frame(vec![pointer::wheel(-30.0)]);
|
||||
assert_eq!(read.get(), 1);
|
||||
}
|
||||
|
||||
/// A canvas reports a rejected claim when a nested scroller owns the diagonal gesture.
|
||||
#[trial]
|
||||
fn a_canvas_cannot_claim_the_horizontal_share_of_a_nested_scrollers_gesture() {
|
||||
let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0)));
|
||||
let read = Rc::new(Cell::new(0_u32));
|
||||
let (shown, reads) = (Rc::clone(&view), Rc::clone(&read));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut given = shown.get();
|
||||
given.rect = ui.available_rect_before_wrap();
|
||||
let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| {
|
||||
let scroller = egui::Id::unique("nested_wheel_scroller");
|
||||
let rect = egui::Rect::from_center_size(given.rect.center(), Vec2::splat(200.0));
|
||||
craft_ui::testing::wheel::register(ui.ctx(), craft_behavior::WheelTaker::new(scroller, rect).vertical(true).scrolls(true));
|
||||
if let Some(space) = canvas_space(&body.env)
|
||||
&& let Some(wheel) = space.wheel()
|
||||
{
|
||||
assert!(wheel.scroll.x != 0.0 && wheel.scroll.y == 0.0, "the canvas receives only horizontal motion");
|
||||
let vertical = craft_ui::testing::wheel::take_share(ui.ctx(), scroller).expect("the nested scroller receives vertical motion");
|
||||
assert!(vertical.scroll.y != 0.0 && vertical.scroll.x == 0.0);
|
||||
assert!(!space.claim_wheel(ui.ctx(), Vec2::ZERO), "the nested scroller owns the gesture");
|
||||
reads.set(reads.get() + 1);
|
||||
}
|
||||
});
|
||||
shown.set(canvas.output.view.unwrap_or(given));
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.frame(vec![pointer::moved(view.get().rect.center())]);
|
||||
let diagonal = || egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: Vec2::new(-20.0, -30.0),
|
||||
phase: TouchPhase::Move,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
};
|
||||
fixture.frame(vec![diagonal()]);
|
||||
let first = view.get();
|
||||
fixture.frame(vec![diagonal()]);
|
||||
assert_eq!(read.get(), 2, "the canvas receives both horizontal shares");
|
||||
assert!(view.get().center.x > first.center.x, "a rejected claim leaves later horizontal panning enabled");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_canvas_can_mark_the_horizontal_share_of_a_nested_scrollers_gesture_modal() {
|
||||
let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0)));
|
||||
let read = Rc::new(Cell::new(0_u32));
|
||||
let (shown, reads) = (Rc::clone(&view), Rc::clone(&read));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut given = shown.get();
|
||||
given.rect = ui.available_rect_before_wrap();
|
||||
let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| {
|
||||
let scroller = egui::Id::unique("modal_nested_wheel_scroller");
|
||||
let rect = egui::Rect::from_center_size(given.rect.center(), Vec2::splat(200.0));
|
||||
craft_ui::testing::wheel::register(ui.ctx(), craft_behavior::WheelTaker::new(scroller, rect).vertical(true).scrolls(true));
|
||||
if let Some(space) = canvas_space(&body.env)
|
||||
&& let Some(wheel) = space.wheel()
|
||||
{
|
||||
let vertical = craft_ui::testing::wheel::take_share(ui.ctx(), scroller).expect("the nested scroller receives vertical motion");
|
||||
assert!(wheel.scroll.x != 0.0 && wheel.scroll.y == 0.0);
|
||||
assert!(vertical.scroll.y != 0.0 && vertical.scroll.x == 0.0);
|
||||
assert_eq!(wheel.modal, reads.get() == 1, "only the rest of the marked gesture is modal");
|
||||
assert_eq!(vertical.modal, wheel.modal, "both shares carry the gesture's modal mark");
|
||||
assert!(!space.claim_wheel(ui.ctx(), Vec2::ZERO), "marking does not let the canvas claim the gesture");
|
||||
assert!(craft_ui::runtime::wheel::claim_token(ui.ctx(), scroller).is_some(), "the nested scroller owns the gesture");
|
||||
if reads.get() == 0 {
|
||||
space.mark_wheel_modal(ui.ctx());
|
||||
}
|
||||
reads.set(reads.get() + 1);
|
||||
}
|
||||
});
|
||||
shown.set(canvas.output.view.unwrap_or(given));
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.frame(vec![pointer::moved(view.get().rect.center())]);
|
||||
let diagonal = || egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: Vec2::new(-20.0, -30.0),
|
||||
phase: TouchPhase::Move,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
};
|
||||
fixture.frame(vec![diagonal()]);
|
||||
fixture.frame(vec![diagonal()]);
|
||||
assert_eq!(read.get(), 2, "the canvas receives both horizontal shares");
|
||||
fixture.advance(craft_behavior::GESTURE_GAP);
|
||||
fixture.frame(vec![diagonal()]);
|
||||
assert_eq!(read.get(), 3, "a new gesture starts without the modal mark");
|
||||
}
|
||||
|
||||
/// A body that first claims the device End stops the canvas glide after the gesture closes.
|
||||
#[trial]
|
||||
fn claiming_the_device_end_stops_the_canvas_glide() {
|
||||
for claim_end in [false, true] {
|
||||
let mut options = NavigationOptions::default();
|
||||
options.touchpad_glide = true;
|
||||
let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0)));
|
||||
let claimed = Rc::new(Cell::new(false));
|
||||
let (shown, claims) = (Rc::clone(&view), Rc::clone(&claimed));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut given = shown.get();
|
||||
given.rect = ui.available_rect_before_wrap();
|
||||
let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| {
|
||||
if claim_end
|
||||
&& let Some(space) = canvas_space(&body.env)
|
||||
&& space.wheel().is_some_and(|wheel| wheel.phase == craft_behavior::WheelPhase::End)
|
||||
{
|
||||
space.claim_wheel(ui.ctx(), Vec2::ZERO);
|
||||
claims.set(true);
|
||||
}
|
||||
});
|
||||
shown.set(canvas.output.view.unwrap_or(given));
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.frame(vec![pointer::moved(view.get().rect.center())]);
|
||||
let event = |phase, dy| egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: Vec2::new(0.0, dy),
|
||||
phase,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
source: egui::MouseWheelSource::Trackpad,
|
||||
};
|
||||
fixture.frame(vec![event(TouchPhase::Start, -30.0)]);
|
||||
for _ in 0..4 {
|
||||
fixture.frame(vec![event(TouchPhase::Move, -30.0)]);
|
||||
}
|
||||
fixture.frame(vec![event(TouchPhase::End, 0.0)]);
|
||||
assert_eq!(claimed.get(), claim_end, "the body claims only the device End");
|
||||
let lifted = view.get();
|
||||
fixture.idle(5);
|
||||
let after = view.get();
|
||||
if claim_end {
|
||||
assert!((after.center.y - lifted.center.y).abs() < 1e-3, "the claimed End left a glide: {lifted:?} -> {after:?}");
|
||||
} else {
|
||||
assert!(after.center.y > lifted.center.y + 1.0, "precondition: the unclaimed End starts a glide");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh notch and its eased tail move the view after the body claims the previous device End.
|
||||
#[trial]
|
||||
fn a_fresh_notch_eases_after_a_claimed_device_end() {
|
||||
for zoom in [false, true] {
|
||||
let mut options = NavigationOptions::default();
|
||||
options.eased_wheel = true;
|
||||
options.eased_wheel_zoom = true;
|
||||
options.touchpad_glide = true;
|
||||
options.wheel = WheelScheme::Acrobat;
|
||||
let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0)));
|
||||
let shown = Rc::clone(&view);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut given = shown.get();
|
||||
given.rect = ui.available_rect_before_wrap();
|
||||
let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| {
|
||||
if let Some(space) = canvas_space(&body.env)
|
||||
&& space.wheel().is_some_and(|wheel| wheel.phase == craft_behavior::WheelPhase::End)
|
||||
{
|
||||
space.claim_wheel(ui.ctx(), Vec2::ZERO);
|
||||
}
|
||||
});
|
||||
shown.set(canvas.output.view.unwrap_or(given));
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.frame(vec![pointer::moved(view.get().rect.center())]);
|
||||
let swipe = |phase, dy| egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: Vec2::new(0.0, dy),
|
||||
phase,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
source: egui::MouseWheelSource::Trackpad,
|
||||
};
|
||||
fixture.frame(vec![swipe(TouchPhase::Start, -30.0)]);
|
||||
fixture.frame(vec![swipe(TouchPhase::End, 0.0)]);
|
||||
let before = view.get();
|
||||
fixture.frame(vec![egui::Event::MouseWheel {
|
||||
unit: if zoom { egui::MouseWheelUnit::Point } else { egui::MouseWheelUnit::Line },
|
||||
delta: Vec2::new(0.0, if zoom { -60.0 } else { -1.0 }),
|
||||
phase: TouchPhase::Move,
|
||||
modifiers: if zoom { egui::Modifiers::COMMAND } else { egui::Modifiers::NONE },
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
}]);
|
||||
let first = view.get();
|
||||
fixture.idle(5);
|
||||
let after = view.get();
|
||||
if zoom {
|
||||
assert!(
|
||||
first.zoom < before.zoom && after.zoom < first.zoom,
|
||||
"the fresh zoom notch and its tail move the view: {before:?} -> {first:?} -> {after:?}"
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
first.center.y > before.center.y && after.center.y > first.center.y,
|
||||
"the fresh scroll notch and its tail move the view: {before:?} -> {first:?} -> {after:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A partial zoom notch from a claimed gesture does not combine with the next gesture's first half notch.
|
||||
#[trial]
|
||||
fn claiming_a_gesture_clears_its_partial_zoom_notch() {
|
||||
let mut options = NavigationOptions::default();
|
||||
options.wheel = WheelScheme::Zoom;
|
||||
let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0)));
|
||||
let claim = Rc::new(Cell::new(true));
|
||||
let (shown, claiming) = (Rc::clone(&view), Rc::clone(&claim));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut given = shown.get();
|
||||
given.rect = ui.available_rect_before_wrap();
|
||||
let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| {
|
||||
if let Some(space) = canvas_space(&body.env)
|
||||
&& space.wheel().is_some()
|
||||
&& claiming.replace(false)
|
||||
{
|
||||
space.claim_wheel(ui.ctx(), Vec2::ZERO);
|
||||
}
|
||||
});
|
||||
shown.set(canvas.output.view.unwrap_or(given));
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.frame(vec![pointer::moved(view.get().rect.center())]);
|
||||
let half = || egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Line,
|
||||
delta: Vec2::new(0.0, 0.5),
|
||||
phase: TouchPhase::Move,
|
||||
modifiers: egui::Modifiers::SHIFT,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
};
|
||||
let before = view.get().zoom;
|
||||
fixture.frame(vec![half()]);
|
||||
assert!(!claim.get(), "the body claimed the first half notch");
|
||||
assert_eq!(view.get().zoom, before, "a half notch does not zoom");
|
||||
fixture.frame(vec![egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: Vec2::ZERO,
|
||||
phase: TouchPhase::End,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
source: egui::MouseWheelSource::Trackpad,
|
||||
}]);
|
||||
fixture.frame(vec![half()]);
|
||||
assert_eq!(view.get().zoom, before, "the new gesture has only half a notch");
|
||||
fixture.frame(vec![half()]);
|
||||
assert!(view.get().zoom > before, "the new gesture's two half notches complete a rung");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_claimed_swipes_samples_do_not_glide_after_a_coalesced_start() {
|
||||
let mut options = NavigationOptions::default();
|
||||
options.touchpad_glide = true;
|
||||
let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0)));
|
||||
let claim = Rc::new(Cell::new(false));
|
||||
let last = Rc::new(Cell::new(None));
|
||||
let (shown, claiming, shares) = (Rc::clone(&view), Rc::clone(&claim), Rc::clone(&last));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut given = shown.get();
|
||||
given.rect = ui.available_rect_before_wrap();
|
||||
let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| {
|
||||
if let Some(space) = canvas_space(&body.env)
|
||||
&& let Some(wheel) = space.wheel()
|
||||
{
|
||||
shares.set(Some(wheel));
|
||||
if claiming.get() {
|
||||
assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO));
|
||||
}
|
||||
}
|
||||
});
|
||||
shown.set(canvas.output.view.unwrap_or(given));
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.frame(vec![pointer::moved(view.get().rect.center())]);
|
||||
let event = |phase, dy| egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: Vec2::new(0.0, dy),
|
||||
phase,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
source: egui::MouseWheelSource::Trackpad,
|
||||
};
|
||||
fixture.frame(vec![event(TouchPhase::Start, -30.0)]);
|
||||
claim.set(true);
|
||||
fixture.frame(vec![event(TouchPhase::Move, -30.0)]);
|
||||
fixture.frame(vec![event(TouchPhase::End, 0.0)]);
|
||||
assert!(last.get().expect("the claimed End").claimed);
|
||||
|
||||
claim.set(false);
|
||||
fixture.frame(vec![event(TouchPhase::Move, -1.0)]);
|
||||
let fresh = last.get().expect("the next swipe's Move");
|
||||
assert_eq!(fresh.phase, craft_behavior::WheelPhase::Move);
|
||||
assert!(!fresh.claimed);
|
||||
fixture.frame(vec![event(TouchPhase::End, 0.0)]);
|
||||
let lifted = view.get();
|
||||
fixture.idle(5);
|
||||
assert_eq!(view.get().center, lifted.center, "one small sample cannot start a glide");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_stale_canvas_space_cannot_claim_a_wheel_share_in_a_later_pass() {
|
||||
claim_from_retained_space(false);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_fresh_canvas_space_can_claim_after_a_stale_claim_is_refused() {
|
||||
claim_from_retained_space(true);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_retained_canvas_space_cannot_claim_a_recreated_viewports_share_with_the_same_pass_number() {
|
||||
for claim_fresh in [false, true] {
|
||||
let viewport = egui::ViewportId::from_hash_of("canvas window");
|
||||
let retained: Cell<Option<CanvasSpace>> = Cell::new(None);
|
||||
let issued = Cell::new(None);
|
||||
let owner = egui::Id::unique("moving canvas");
|
||||
let recreated = Cell::new(false);
|
||||
let attempts = Cell::new(0);
|
||||
let last = Cell::new(None);
|
||||
let view = Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0));
|
||||
let mut show = |ui: &mut egui::Ui| {
|
||||
let mut given = view.get();
|
||||
given.rect = ui.available_rect_before_wrap();
|
||||
let canvas = Canvas::new("Document").id(owner).document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| {
|
||||
if let Some(space) = canvas_space(&body.env)
|
||||
&& let Some(wheel) = space.wheel()
|
||||
{
|
||||
last.set(Some(wheel));
|
||||
let pass = craft_ui::runtime::frame::running(ui.ctx()).expect("a running pass");
|
||||
if !recreated.get() {
|
||||
retained.set(Some(space));
|
||||
issued.set(Some(pass.pass_nr));
|
||||
} else if attempts.get() == 0 {
|
||||
assert_eq!(pass.viewport, viewport, "the recreated viewport has the same ID");
|
||||
assert_eq!(Some(pass.pass_nr), issued.get(), "the recreated viewport has the same pass counter");
|
||||
assert!(!retained.get().expect("the earlier snapshot").claim_wheel(ui.ctx(), Vec2::new(0.0, -30.0)));
|
||||
assert!(!craft_ui::runtime::wheel::claimed(ui.ctx(), owner), "the rejected claim leaves the new share unclaimed");
|
||||
if claim_fresh {
|
||||
assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO));
|
||||
}
|
||||
attempts.set(attempts.get() + 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
view.set(canvas.output.view.unwrap_or(given));
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
for reopen in [false, true] {
|
||||
if reopen {
|
||||
frames.close_viewport(viewport);
|
||||
frames.frame(Vec::new(), |_| {});
|
||||
recreated.set(true);
|
||||
}
|
||||
frames.frame_in_viewport(viewport, Vec::new(), &mut show);
|
||||
frames.frame_in_viewport(viewport, Vec::new(), &mut show);
|
||||
frames.frame_in_viewport(viewport, vec![pointer::moved(view.get().rect.center())], &mut show);
|
||||
frames.frame_in_viewport(viewport, vec![pointer::wheel_lines(-1.0)], &mut show);
|
||||
}
|
||||
assert_eq!(attempts.get(), 1);
|
||||
last.set(None);
|
||||
frames.frame_in_viewport(viewport, vec![pointer::wheel(-30.0)], &mut show);
|
||||
let next = last.get().expect("the share after the claim attempt");
|
||||
assert_eq!(next.claimed, claim_fresh);
|
||||
if !claim_fresh {
|
||||
assert_eq!(next.claimed_gathered, Vec2::ZERO, "the rejected claim records no claimed motion");
|
||||
}
|
||||
assert_eq!(next.claimed_spent, Vec2::ZERO, "the rejected claim records no spent motion");
|
||||
}
|
||||
}
|
||||
|
||||
fn claim_from_retained_space(claim_fresh: bool) {
|
||||
let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0)));
|
||||
let retained: Rc<Cell<Option<CanvasSpace>>> = Rc::new(Cell::new(None));
|
||||
let later = Rc::new(Cell::new(false));
|
||||
let read = Rc::new(Cell::new(None));
|
||||
let attempts = Rc::new(Cell::new(0));
|
||||
let (shown, saved, claiming, shares, claims) =
|
||||
(Rc::clone(&view), Rc::clone(&retained), Rc::clone(&later), Rc::clone(&read), Rc::clone(&attempts));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut given = shown.get();
|
||||
given.rect = ui.available_rect_before_wrap();
|
||||
let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| {
|
||||
if let Some(space) = canvas_space(&body.env)
|
||||
&& let Some(wheel) = space.wheel()
|
||||
{
|
||||
shares.set(Some(wheel));
|
||||
if claiming.get() {
|
||||
assert!(!saved.get().expect("the earlier snapshot").claim_wheel(ui.ctx(), Vec2::ZERO));
|
||||
if claim_fresh {
|
||||
assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO));
|
||||
}
|
||||
claims.set(claims.get() + 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
shown.set(canvas.output.view.unwrap_or(given));
|
||||
if !claiming.get() && canvas.output.space.is_some_and(|space| space.wheel().is_some()) {
|
||||
saved.set(canvas.output.space);
|
||||
}
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.frame(vec![pointer::moved(view.get().rect.center())]);
|
||||
fixture.frame(vec![pointer::wheel(-30.0)]);
|
||||
assert!(retained.get().is_some());
|
||||
later.set(true);
|
||||
fixture.frame(vec![pointer::wheel(-30.0)]);
|
||||
assert_eq!(attempts.get(), 1);
|
||||
later.set(false);
|
||||
fixture.frame(vec![pointer::wheel(-30.0)]);
|
||||
let next = read.get().expect("the share after the claim attempt");
|
||||
assert_eq!(next.claimed, claim_fresh);
|
||||
if claim_fresh {
|
||||
assert_eq!(next.claimed_gathered, next.scroll, "only the fresh snapshot's share was claimed");
|
||||
} else {
|
||||
assert_eq!(next.claimed_gathered, Vec2::ZERO, "the stale snapshot left the new share unclaimed");
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_small_reversal_of_a_claimed_gesture_keeps_the_step_count() {
|
||||
let steps = Rc::new(Cell::new(0.0));
|
||||
let count = Rc::clone(&steps);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let view = CanvasView::new(ui.available_rect_before_wrap(), Point::new(2000.0, 2000.0), 1.0);
|
||||
Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(view).show(ui, |ui, body| {
|
||||
if let Some(space) = canvas_space(&body.env)
|
||||
&& let Some(wheel) = space.wheel()
|
||||
{
|
||||
let remaining = wheel.claimed_gathered.y + wheel.scroll.y - wheel.claimed_spent.y;
|
||||
let steps = (remaining / 30.0).trunc();
|
||||
if space.claim_wheel(ui.ctx(), Vec2::new(0.0, steps * 30.0)) {
|
||||
count.set(count.get() + steps);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.frame(vec![pointer::moved(egui::Pos2::new(200.0, 200.0))]);
|
||||
fixture.frame(vec![pointer::wheel(-30.0)]);
|
||||
assert_eq!(steps.get(), -1.0, "the first share takes one step");
|
||||
fixture.frame(vec![pointer::wheel(5.0)]);
|
||||
assert_eq!(steps.get(), -1.0, "a reversal smaller than one step leaves the count unchanged");
|
||||
}
|
||||
@@ -13,6 +13,13 @@ use craft_behavior::{
|
||||
};
|
||||
use craft_keymap::Mods;
|
||||
use egui::{Context, Id, IdMap, Pos2, Vec2};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// The process-unique identity of a wheel share that can be claimed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ClaimToken(u64);
|
||||
|
||||
static NEXT_CLAIM_TOKEN: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
pub(crate) struct State {
|
||||
this: Vec<WheelTaker<Id>>,
|
||||
@@ -23,6 +30,7 @@ pub(crate) struct State {
|
||||
/// The last-pressed gated control while the pointer has stayed inside it since.
|
||||
armed: Option<Id>,
|
||||
shares: Vec<(Id, Wheel)>,
|
||||
recipients: Vec<Id>,
|
||||
/// The wheel gesture the split tracks across passes.
|
||||
gesture: WheelGesture<Id>,
|
||||
/// The running gesture's gathered scroll in its owner's points, reset when the gesture closes.
|
||||
@@ -37,6 +45,14 @@ pub(crate) struct State {
|
||||
modal: bool,
|
||||
/// The time of the last wheel event a modal held; −∞ before the first.
|
||||
modal_last: f64,
|
||||
/// The owner's claims on the running gesture, reset when the gesture closes.
|
||||
claim: Claim,
|
||||
/// The owner, token and motion of the running gesture's last share, which a claim in the same pass takes.
|
||||
last_share: Option<(Id, ClaimToken, Vec2, Vec2)>,
|
||||
/// This pass's claim of the last share, with the motion it spent; it joins `claim` when the next share gathers.
|
||||
pending: Option<(Vec2, Vec2, Vec2)>,
|
||||
/// Each registered owner remains here until it reads the cancellation of its claimed motion.
|
||||
cancellations: IdMap<()>,
|
||||
/// The last gesture the device ended, which a momentum run of the same owner within `GESTURE_GAP` resumes.
|
||||
device_ended: Option<Ended>,
|
||||
/// The wheel ease each owner holds.
|
||||
@@ -52,6 +68,7 @@ impl Default for State {
|
||||
last_layers: IdMap::default(),
|
||||
armed: None,
|
||||
shares: Vec::new(),
|
||||
recipients: Vec::new(),
|
||||
gesture: WheelGesture::default(),
|
||||
gathered: Vec2::ZERO,
|
||||
zoom_gathered: Vec2::ZERO,
|
||||
@@ -59,6 +76,10 @@ impl Default for State {
|
||||
held: Mods::NONE,
|
||||
modal: false,
|
||||
modal_last: f64::NEG_INFINITY,
|
||||
claim: Claim::default(),
|
||||
last_share: None,
|
||||
pending: None,
|
||||
cancellations: IdMap::default(),
|
||||
device_ended: None,
|
||||
eases: IdMap::default(),
|
||||
}
|
||||
@@ -75,6 +96,32 @@ struct Ended {
|
||||
moved: bool,
|
||||
held: Mods,
|
||||
modal: bool,
|
||||
claim: Claim,
|
||||
}
|
||||
|
||||
/// What the owner of a gesture claimed of it: whether it claimed a share, the claimed shares' scroll and zoom lines,
|
||||
/// and the motion it said it spent.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Claim {
|
||||
claimed: bool,
|
||||
gathered: Vec2,
|
||||
zoom_gathered: Vec2,
|
||||
spent: Vec2,
|
||||
}
|
||||
|
||||
impl Claim {
|
||||
/// Gives `share` the claims made before it.
|
||||
fn give(self, share: &mut Wheel) {
|
||||
share.claimed = self.claimed;
|
||||
share.claimed_gathered = self.gathered;
|
||||
share.claimed_zoom_gathered = self.zoom_gathered;
|
||||
share.claimed_spent = self.spent;
|
||||
}
|
||||
|
||||
/// These claims and one more, of a share of `scroll` and `zoom_lines` that spent `spent`.
|
||||
fn with(self, scroll: Vec2, zoom_lines: Vec2, spent: Vec2) -> Self {
|
||||
Claim { claimed: true, gathered: self.gathered + scroll, zoom_gathered: self.zoom_gathered + zoom_lines, spent: self.spent + spent }
|
||||
}
|
||||
}
|
||||
|
||||
/// The modifiers held in `a` or in `b`.
|
||||
@@ -95,6 +142,70 @@ pub(crate) fn mark_moved(ctx: &Context, id: Id) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The token for the share `id` can claim in the running pass, including after it reads the share.
|
||||
pub fn claim_token(ctx: &Context, id: Id) -> Option<ClaimToken> {
|
||||
let running = crate::runtime::frame::running(ctx)?;
|
||||
PerViewport::<State>::with(ctx, running.viewport, |state| state.last_share.filter(|(owner, _, _, _)| *owner == id).map(|share| share.1))
|
||||
}
|
||||
|
||||
/// Claims for `id` this pass's share of the wheel gesture it owns, and records `spent`, the part of the claimed motion
|
||||
/// it used up, in its own unit, returning whether the claim succeeded. The shares that follow in the gesture carry
|
||||
/// `claimed` and the claimed motion (`Wheel::claimed_gathered`, `claimed_zoom_gathered` and `claimed_spent`); a share
|
||||
/// the owner does not claim is not counted in them. A second claim in the same pass replaces the first, so a body
|
||||
/// that runs twice claims once. Without a share for `id` in the running pass, or if `id` does not own the gesture,
|
||||
/// it returns `false` without changing the claims. `token` must identify the share being claimed.
|
||||
pub fn claim(ctx: &Context, id: Id, token: ClaimToken, spent: Vec2) -> bool {
|
||||
if !spent.is_finite() {
|
||||
return false;
|
||||
}
|
||||
let Some(running) = crate::runtime::frame::running(ctx) else { return false };
|
||||
PerViewport::<State>::with(ctx, running.viewport, |state| {
|
||||
let Some((owner, shared_token, scroll, zoom_lines)) = state.last_share else { return false };
|
||||
if owner != id || shared_token != token {
|
||||
return false;
|
||||
}
|
||||
if state.gesture.owner != Some(id) {
|
||||
return false;
|
||||
}
|
||||
state.pending = Some((scroll, zoom_lines, spent));
|
||||
state.cancellations.insert(id, ());
|
||||
// The eased wheel's owed motion stops with the claim: the owner's view moves no further by the gesture.
|
||||
state.eases.remove(&id);
|
||||
let now = crate::runtime::frame::clock(ctx);
|
||||
// The swipe the device ended in this pass goes on in its momentum run, which must see the claim too.
|
||||
let claimed = state.claim.with(scroll, zoom_lines, spent);
|
||||
if let Some(ended) = state.device_ended.as_mut().filter(|ended| ended.owner == id && ended.at == now) {
|
||||
ended.claim = claimed;
|
||||
}
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns whether `id` claimed the running gesture or has an unread cancellation from a claim, and consumes that
|
||||
/// cancellation. A cancellation persists after the gesture closes until the owner reads it or stops registering.
|
||||
pub fn claimed(ctx: &Context, id: Id) -> bool {
|
||||
PerViewport::<State>::with(ctx, pass::current_viewport(ctx), |state| {
|
||||
let canceled = state.cancellations.remove(&id).is_some();
|
||||
canceled || (state.gesture.owner == Some(id) && (state.claim.claimed || state.pending.is_some()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Marks the wheel gesture `id` owns or received a share of in this pass as begun or gone on under an app's own
|
||||
/// modal window that the wheel service does not see as a modal layer. The gesture's later shares carry
|
||||
/// `Wheel::modal` until it ends.
|
||||
pub fn mark_modal(ctx: &Context, id: Id) {
|
||||
PerViewport::<State>::with(ctx, pass::current_viewport(ctx), |state| {
|
||||
let received = state.recipients.contains(&id);
|
||||
if state.gesture.owner == Some(id) || received {
|
||||
state.modal = true;
|
||||
}
|
||||
let now = crate::runtime::frame::clock(ctx);
|
||||
if let Some(ended) = state.device_ended.as_mut().filter(|ended| ended.owner == id || (received && ended.at == now)) {
|
||||
ended.modal = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Feeds `pan` to the wheel ease of `id` and returns this pass's eased step. The step is paid by the clock, so a
|
||||
/// later pass of the same frame pays zero.
|
||||
pub(crate) fn ease(ctx: &Context, id: Id, pan: Vec2) -> Vec2 {
|
||||
@@ -142,6 +253,7 @@ impl State {
|
||||
}
|
||||
let last = &self.last;
|
||||
self.eases.retain(|id, _| last.iter().any(|taker| taker.owner == *id));
|
||||
self.cancellations.retain(|id, _| last.iter().any(|taker| taker.owner == *id));
|
||||
let open = self.gesture.last.is_finite();
|
||||
let ended = self.gesture.end(if pressed { f64::INFINITY } else { now });
|
||||
if open && !self.gesture.last.is_finite() {
|
||||
@@ -150,6 +262,7 @@ impl State {
|
||||
self.moved = false;
|
||||
self.held = Mods::NONE;
|
||||
self.modal = false;
|
||||
self.clear_claim(Claim::default());
|
||||
}
|
||||
ended
|
||||
}
|
||||
@@ -166,9 +279,25 @@ impl State {
|
||||
swipe.map_or((Vec2::ZERO, Vec2::ZERO, false, Mods::NONE), |ended| (ended.gathered, ended.zoom_gathered, ended.moved, ended.held));
|
||||
// A turn that went on under a modal until just now goes on under it after the modal closes.
|
||||
self.modal = swipe.is_some_and(|ended| ended.modal) || now - self.modal_last < GESTURE_GAP;
|
||||
self.clear_claim(swipe.map_or(Claim::default(), |ended| ended.claim));
|
||||
swipe.map(|ended| ended.owner)
|
||||
}
|
||||
|
||||
/// Starts the running gesture's claims at `claim`, with no claim pending.
|
||||
fn clear_claim(&mut self, claim: Claim) {
|
||||
self.claim = claim;
|
||||
self.last_share = None;
|
||||
self.pending = None;
|
||||
}
|
||||
|
||||
/// Adds this pass's claim, if any, to the running gesture's claims.
|
||||
fn settle_claim(&mut self) {
|
||||
if let Some((scroll, zoom_lines, spent)) = self.pending.take() {
|
||||
self.claim = self.claim.with(scroll, zoom_lines, spent);
|
||||
}
|
||||
self.last_share = None;
|
||||
}
|
||||
|
||||
/// Adds `share`, in its owner's points, to the gesture it belongs to and gives it the gesture's gathered scroll,
|
||||
/// mark and held modifiers; a share of another owner than the gesture's gathers only itself. Every share carries
|
||||
/// whether the gesture went on under a modal. A point share cancels its owner's
|
||||
@@ -181,6 +310,12 @@ impl State {
|
||||
}
|
||||
share.modal = self.modal;
|
||||
if self.gesture.owner == Some(owner) {
|
||||
self.claim.give(share);
|
||||
if self.last_share.is_none()
|
||||
&& let Ok(token) = NEXT_CLAIM_TOKEN.try_update(Ordering::Relaxed, Ordering::Relaxed, |next| next.checked_add(1))
|
||||
{
|
||||
self.last_share = Some((owner, ClaimToken(token), share.scroll, share.zoom_lines));
|
||||
}
|
||||
self.gathered += share.scroll;
|
||||
self.zoom_gathered += share.zoom_lines;
|
||||
share.gathered = self.gathered;
|
||||
@@ -290,6 +425,8 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) {
|
||||
state.last = std::mem::take(&mut state.this);
|
||||
state.last_layers = std::mem::take(&mut state.this_layers);
|
||||
state.shares.clear();
|
||||
// Last pass's claim joins the gesture's; a claim in this pass takes only a share of this pass.
|
||||
state.settle_claim();
|
||||
if let Some(winner) = pressed_on {
|
||||
state.armed = winner.filter(|id| state.last.iter().any(|taker| taker.gated && taker.owner == *id));
|
||||
}
|
||||
@@ -312,6 +449,7 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) {
|
||||
let held_before = if closing_press { either(state.held, press_mods) } else { state.held };
|
||||
// A wheel a modal held in the pass before that press arrived during the gesture too.
|
||||
let modal_before = state.modal || (closing_press && wheel_before_press && (blocked || modal_family.is_some()));
|
||||
let claim_before = state.claim;
|
||||
let ended = state.close_gesture(pressed_on.is_some(), now);
|
||||
let ended = ended.filter(|owner| state.last.iter().any(|taker| taker.owner == *owner && taker.value));
|
||||
// A key tapped between the running gesture's wheel events counts as held for the rest of it, and one tapped
|
||||
@@ -331,6 +469,7 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) {
|
||||
// The end carries the metadata of the gesture it ends.
|
||||
let mut end = Wheel::new(Vec2::ZERO, mods, WheelUnit::Point, WheelPhase::End);
|
||||
(end.held, end.modal) = (held_before, modal_before);
|
||||
claim_before.give(&mut end);
|
||||
state.shares.push((owner, end));
|
||||
}
|
||||
if let (Some(frame), Some(at)) = (&frame, hover)
|
||||
@@ -384,12 +523,17 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) {
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let (previous_owner, held, modal) = (state.gesture.owner, state.held, state.modal);
|
||||
let (previous_owner, held, modal, claimed) = (state.gesture.owner, state.held, state.modal, state.claim);
|
||||
let shares = split(&eligible, at, share, focus, state.armed, &mut state.gesture, now);
|
||||
// A momentum run resumes its swipe only on the swipe's owner; any split drops the ended swipe.
|
||||
if swipe.is_some() && state.gesture.owner != swipe {
|
||||
(state.gathered, state.zoom_gathered, state.moved, state.held) = (Vec2::ZERO, Vec2::ZERO, false, Mods::NONE);
|
||||
state.modal = now - state.modal_last < GESTURE_GAP;
|
||||
state.clear_claim(Claim::default());
|
||||
}
|
||||
// A running gesture the split hands to another owner starts its claims again: the new owner claimed none.
|
||||
if previous_owner.is_some() && state.gesture.owner != previous_owner {
|
||||
state.clear_claim(Claim::default());
|
||||
}
|
||||
state.held = either(state.held, either(mods, held_mods));
|
||||
state.device_ended = None;
|
||||
@@ -405,12 +549,15 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) {
|
||||
state.gather(owner, &mut share);
|
||||
if share.phase == WheelPhase::End && Some(owner) == previous_owner && state.gesture.owner != previous_owner {
|
||||
(share.held, share.modal) = (held, modal);
|
||||
claimed.give(&mut share);
|
||||
}
|
||||
state.shares.push((owner, share));
|
||||
}
|
||||
if device_end {
|
||||
let (gathered, zoom_gathered, moved, held, modal) = (state.gathered, state.zoom_gathered, state.moved, state.held, state.modal);
|
||||
state.device_ended = state.gesture.owner.map(|owner| Ended { owner, at: now, gathered, zoom_gathered, moved, held, modal });
|
||||
let (gathered, zoom_gathered, moved, held, modal, claim) =
|
||||
(state.gathered, state.zoom_gathered, state.moved, state.held, state.modal, state.claim);
|
||||
state.device_ended =
|
||||
state.gesture.owner.map(|owner| Ended { owner, at: now, gathered, zoom_gathered, moved, held, modal, claim });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -422,6 +569,8 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) {
|
||||
state.shares.remove(0);
|
||||
state.shares[at].1.phase = WheelPhase::Start;
|
||||
}
|
||||
state.recipients.clear();
|
||||
state.recipients.extend(state.shares.iter().map(|(owner, _)| *owner));
|
||||
// A value control that owns the running gesture hears its end without a timer of its own: a pass at the gap.
|
||||
// An owed ease pays in the passes that follow.
|
||||
state.wake(now)
|
||||
|
||||
@@ -558,6 +558,118 @@ fn a_wheel_gesture_carries_the_keys_held_during_it_and_whether_it_began_under_a_
|
||||
assert!(!fresh.modal, "a turn begun after the gap: {fresh:?}");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_wheel_gesture_counts_only_the_shares_its_owner_claimed_and_an_app_modal_marks_it() {
|
||||
let canvas = Id::unique("claim_canvas");
|
||||
let rect = Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0));
|
||||
// What the body does with this pass's share: claim it with this much spent, and mark the turn modal.
|
||||
let claim: Cell<Option<Vec2>> = Cell::new(None);
|
||||
let modal = Cell::new(false);
|
||||
let last: Cell<Option<Wheel>> = Cell::new(None);
|
||||
let last_token = Cell::new(None);
|
||||
let mut show_frame = |ui: &mut Ui| {
|
||||
register(ui.ctx(), WheelTaker::new(canvas, rect).vertical(true).scrolls(true));
|
||||
if let Some(share) = take_share(ui.ctx(), canvas) {
|
||||
last.set(Some(share));
|
||||
let token = craft_ui::runtime::wheel::claim_token(ui.ctx(), canvas).expect("a claimable share");
|
||||
last_token.set(Some(token));
|
||||
for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
for spent in [Vec2::new(invalid, 0.0), Vec2::new(0.0, invalid)] {
|
||||
assert!(!craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, spent), "a claim of {spent:?} is refused");
|
||||
}
|
||||
}
|
||||
if let Some(spent) = claim.get() {
|
||||
// A body that runs twice in a pass claims once.
|
||||
assert!(craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, spent));
|
||||
assert!(craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, spent));
|
||||
}
|
||||
if modal.get() {
|
||||
craft_ui::runtime::wheel::mark_modal(ui.ctx(), canvas);
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(2, &mut show_frame);
|
||||
frames.frame(vec![pointer::moved(Pos2::new(200.0, 200.0))], &mut show_frame);
|
||||
let turn = |frames: &mut Frames, show_frame: &mut dyn FnMut(&mut Ui), take: Option<Vec2>| {
|
||||
claim.set(take);
|
||||
last.set(None);
|
||||
frames.frame(vec![pointer::wheel(-30.0)], &mut *show_frame);
|
||||
last.take().expect("the canvas takes the wheel")
|
||||
};
|
||||
|
||||
// The first share is not claimed: the claims count nothing of it.
|
||||
let first = turn(&mut frames, &mut show_frame, None);
|
||||
assert!(!first.claimed && first.claimed_gathered == Vec2::ZERO, "nothing claimed yet: {first:?}");
|
||||
assert!(
|
||||
!craft_ui::runtime::wheel::claim(&frames.ctx, canvas, last_token.get().expect("the last share's token"), Vec2::new(0.0, 10.0)),
|
||||
"a share cannot be claimed between passes"
|
||||
);
|
||||
assert!(!craft_ui::runtime::wheel::claimed(&frames.ctx, canvas), "a rejected claim does not cancel navigation");
|
||||
let second = turn(&mut frames, &mut show_frame, Some(Vec2::new(0.0, 1.0)));
|
||||
assert!(!second.claimed && second.claimed_gathered == Vec2::ZERO, "the first share was left unclaimed: {second:?}");
|
||||
assert!(
|
||||
!craft_ui::runtime::wheel::claim(&frames.ctx, canvas, last_token.get().expect("the last share's token"), Vec2::new(0.0, 10.0)),
|
||||
"a late claim cannot replace the body's spent motion"
|
||||
);
|
||||
let third = turn(&mut frames, &mut show_frame, Some(Vec2::new(0.0, -1.0)));
|
||||
assert!(third.claimed, "the second share was claimed: {third:?}");
|
||||
assert_eq!((third.claimed_gathered, third.claimed_spent), (second.scroll, Vec2::new(0.0, 1.0)), "one claim of the second share: {third:?}");
|
||||
assert_eq!(third.gathered, first.scroll + second.scroll + third.scroll, "the gesture still gathers every share: {third:?}");
|
||||
let fourth = turn(&mut frames, &mut show_frame, None);
|
||||
assert_eq!((fourth.claimed_gathered, fourth.claimed_spent), (second.scroll + third.scroll, Vec2::ZERO), "{fourth:?}");
|
||||
|
||||
// An app's own modal marks the rest of the turn, and a new turn starts with no claims and no mark.
|
||||
modal.set(true);
|
||||
let marked = turn(&mut frames, &mut show_frame, None);
|
||||
assert!(!marked.modal, "the mark comes after the share: {marked:?}");
|
||||
modal.set(false);
|
||||
let after = turn(&mut frames, &mut show_frame, None);
|
||||
assert!(after.modal && after.claimed, "the rest of the turn is marked: {after:?}");
|
||||
frames.advance(GESTURE_GAP);
|
||||
frames.idle(2, &mut show_frame);
|
||||
let fresh = turn(&mut frames, &mut show_frame, None);
|
||||
assert!(!fresh.modal && !fresh.claimed && fresh.claimed_gathered == Vec2::ZERO && fresh.claimed_spent == Vec2::ZERO, "{fresh:?}");
|
||||
}
|
||||
|
||||
/// An unread cancellation survives gesture close while its owner registers and is released when that owner leaves.
|
||||
#[trial]
|
||||
fn unread_claim_cancellations_follow_registered_owners() {
|
||||
for discarded in [false, true] {
|
||||
let canvas = Id::unique("discarded_claim_canvas");
|
||||
let rect = Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0));
|
||||
let registered = Cell::new(true);
|
||||
let consume = Cell::new(false);
|
||||
let claimed = Cell::new(false);
|
||||
let canceled = Cell::new(None);
|
||||
let mut show_frame = |ui: &mut Ui| {
|
||||
if registered.get() {
|
||||
register(ui.ctx(), WheelTaker::new(canvas, rect).vertical(true).scrolls(true));
|
||||
if take_share(ui.ctx(), canvas).is_some() {
|
||||
let token = craft_ui::runtime::wheel::claim_token(ui.ctx(), canvas).expect("a claimable share");
|
||||
craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, Vec2::ZERO);
|
||||
claimed.set(true);
|
||||
}
|
||||
if consume.take() {
|
||||
canceled.set(Some(craft_ui::runtime::wheel::claimed(ui.ctx(), canvas)));
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(2, &mut show_frame);
|
||||
frames.frame(vec![pointer::moved(rect.center())], &mut show_frame);
|
||||
frames.frame(vec![pointer::wheel(-30.0)], &mut show_frame);
|
||||
assert!(claimed.get(), "the owner claimed its share");
|
||||
frames.advance(GESTURE_GAP);
|
||||
registered.set(!discarded);
|
||||
frames.idle(2, &mut show_frame);
|
||||
registered.set(true);
|
||||
consume.set(true);
|
||||
frames.frame(Vec::new(), &mut show_frame);
|
||||
assert_eq!(canceled.get(), Some(!discarded), "discarded {discarded}: only a registered owner retains its cancellation");
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_end_share_of_a_pressed_wheel_gesture_carries_a_key_tapped_before_the_press_in_its_pass() {
|
||||
let slider = Id::unique("press_held_slider");
|
||||
|
||||
+12
-1
@@ -1842,7 +1842,7 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev
|
||||
Wheel gesture values, as craft-behavior's copy of egui's types so the wheel split is egui-free.
|
||||
|
||||
- `craft_behavior::wheel::GESTURE_GAP`: `pub const GESTURE_GAP: f64`. The seconds between wheel events that still belong to one gesture.
|
||||
- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub zoom_lines: Vec2, pub zoom_gathered: Vec2, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option<Pos2>, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2, pub gathered: Vec2, pub moved: bool, pub held: Mods, pub modal: bool }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`.
|
||||
- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub zoom_lines: Vec2, pub zoom_gathered: Vec2, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option<Pos2>, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2, pub gathered: Vec2, pub moved: bool, pub held: Mods, pub modal: bool, pub claimed: bool, pub claimed_gathered: Vec2, pub claimed_zoom_gathered: Vec2, pub claimed_spent: Vec2 }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`.
|
||||
- `pub const fn new(scroll: Vec2, mods: Mods, unit: WheelUnit, phase: WheelPhase) -> Self`. A scroll of `scroll` points with no zoom.
|
||||
- `pub const fn zoom(mut self, zoom: f32) -> Self`. The same gesture with zoom factor `zoom`.
|
||||
- `pub const fn zoom_lines(mut self, lines: Vec2) -> Self`. The same gesture with `lines` wheel lines of motion that zoom (`Wheel::zoom_lines`).
|
||||
@@ -4604,6 +4604,17 @@ The toast queues: one per window (`WindowKey`), filled from any code with a `Con
|
||||
- `craft_ui::runtime::toast::shown`: `pub fn shown(ctx: &Context, id: ToastId, text: &str, held: bool)`. The host shows `id` in this pass; `held` says the pointer or focus is on it.
|
||||
- `craft_ui::runtime::toast::snapshot`: `pub fn snapshot(ctx: &Context) -> Vec<(WindowKey, Card)>`. Every live viewport's cards with their windows, oldest first, for `ui.inspect`; `cards` is the running viewport's.
|
||||
|
||||
## `craft_ui::runtime::wheel`
|
||||
|
||||
The wheel service (8.6): takers register their view rects, the begin hook splits the pass's wheel input among them from last pass's registrations, and each taker reads its share once.
|
||||
|
||||
- `craft_ui::runtime::wheel::ClaimToken`: `pub struct ClaimToken(/* private fields */)`. A small `Copy` token that identifies a claimable wheel share and never repeats in the process.
|
||||
- `craft_ui::runtime::wheel::claim_token`: `pub fn claim_token(ctx: &Context, id: Id) -> Option<ClaimToken>`. Returns the token for the share `id` can claim in the running pass, including after it reads the share.
|
||||
- `craft_ui::runtime::wheel::claim`: `pub fn claim(ctx: &Context, id: Id, token: ClaimToken, spent: Vec2) -> bool`. Claims for `id` this pass's share of the wheel gesture it owns, and records `spent`, the part of the claimed motion it used up, in its own unit, returning whether the claim succeeded. The token must match the share being claimed, including when a viewport is recreated with the same ID and pass counter.
|
||||
- `craft_ui::canvas::CanvasSpace::with_wheel`: `pub fn with_wheel(mut self, wheel: Option<craft_behavior::Wheel>) -> Self`. Sets the wheel share without a claim token. `CanvasSpace::claim_wheel` refuses a snapshot from another share.
|
||||
- `craft_ui::runtime::wheel::claimed`: `pub fn claimed(ctx: &Context, id: Id) -> bool`. Returns whether `id` claimed the running gesture or has an unread cancellation from a claim, and consumes that cancellation.
|
||||
- `craft_ui::runtime::wheel::mark_modal`: `pub fn mark_modal(ctx: &Context, id: Id)`. Marks the wheel gesture `id` owns or received a share of in this pass as begun or gone on under a modal: an app's own modal window that the wheel service does not see as a modal layer.
|
||||
|
||||
## `craft_ui::runtime::windows`
|
||||
|
||||
`WindowHost`: the one multi-window driver.
|
||||
|
||||
Vendored
+9
@@ -95,6 +95,15 @@ colorants paint through their alternate space (`Plate::spots_as_process`) and no
|
||||
overprints. Masks in other color spaces are unchanged. A test in
|
||||
`crates/pdf/tests/plates.rs` checks process, spot, RGB and backdrop colors.
|
||||
|
||||
The self-draw check of hayro-interpret patch 89 runs a soft mask's group, a tiling pattern's
|
||||
cell and a Type 3 glyph's procedure inside the forms being drawn where the mask or pattern was
|
||||
set or the glyph was shown (`context::forms_drawing`, `context::drawing_within`), not inside the
|
||||
forms the device is drawing when it calls `SoftMask::interpret`, `SoftMask::interpret_plate`,
|
||||
`TilingPattern::interpret` or `Type3Glyph::interpret`. A tiling pattern or Type 3 glyph set on
|
||||
the page and interpreted by a device while it draws a form draws that form; before, its copy of
|
||||
the form was skipped. A form that draws itself through a soft mask, tiling pattern or Type 3
|
||||
glyph set inside it is still skipped. Tests: `self_draw_tests.rs` in hayro-interpret.
|
||||
|
||||
The output-intent conversion of patch 36 goes through a `color::CmykConversion` trait, so
|
||||
that callers can convert with their own color management. `CmykSimulation::new` keeps
|
||||
#2770's moxcms conversion as the default, and `CmykSimulation::with_conversion` takes a
|
||||
|
||||
Vendored
+10
-4
@@ -188,7 +188,7 @@
|
||||
"path": "src/context.rs",
|
||||
"source_sha256": "dc2be553958ee3f5e5e644a77a0301723bae9ca027a352c13b9caaf549cc0e56",
|
||||
"source_git_blob": "d6772baa15ebb95d3ba2d1f54ce5c250ad1e8137",
|
||||
"sha256": "b8c530ff091a231fba36af17c89e38705b848e5c614a3f3888def871ffb5b597"
|
||||
"sha256": "af6fd93f8b8b271e88ed254970dc789c0b7dff914b5e51bffcf4fdd7b47978b2"
|
||||
},
|
||||
{
|
||||
"path": "src/convert.rs",
|
||||
@@ -290,7 +290,7 @@
|
||||
"path": "src/font/mod.rs",
|
||||
"source_sha256": "7e6411927d91205ca76c6b59f9d737cd1104d066f8cfcc0a87f481016ef30313",
|
||||
"source_git_blob": "7c8c8d086d59139df791cdb6952506473ec4b5a7",
|
||||
"sha256": "b58ee45b8c4a4d1de36eadc11363a8620ac56202646c937c1a012539372883bc"
|
||||
"sha256": "e239a2def9915d4df38eaed4deccc0ffc57ccfb6a3c9d5955a02f50db681d155"
|
||||
},
|
||||
{
|
||||
"path": "src/font/outline.rs",
|
||||
@@ -386,7 +386,7 @@
|
||||
"path": "src/lib.rs",
|
||||
"source_sha256": "ea3fa23b74f99b5382798f90b7e9f0e3edca354ee26ea92fe26a91ee5c0195c9",
|
||||
"source_git_blob": "24c3be295783d7a53ac6bc39d93e539883480cd4",
|
||||
"sha256": "3473d9640da637f95252611d1edb601efa9327c117d5580913c670dda696dd6e"
|
||||
"sha256": "777f78daa1c2dbcb945bc2061bfd5748f3ee07a0efbe53de7fa7de29d2880f5f"
|
||||
},
|
||||
{
|
||||
"path": "src/log.rs",
|
||||
@@ -404,7 +404,13 @@
|
||||
"path": "src/pattern.rs",
|
||||
"source_sha256": "17b49a465275c20e6645dea9443f2cb3a64c594925fd860e74b80b44d5344e37",
|
||||
"source_git_blob": "9295f51709f8915951d7b9afca9411651d65a1f8",
|
||||
"sha256": "1ee9705afa285ddeb4c287e83e86906bdcc525a738b41d17164d1f751e2c01b6"
|
||||
"sha256": "4621fe8b85f472e731e2c01d0f92ec1662c7d9d0f0e20f520fd9c926201af8d5"
|
||||
},
|
||||
{
|
||||
"path": "src/self_draw_tests.rs",
|
||||
"source_sha256": null,
|
||||
"source_git_blob": null,
|
||||
"sha256": "1f0a93fb387d3ba51c1348ed69fe567fdb2be88ee57506400cd66644dadadb85"
|
||||
},
|
||||
{
|
||||
"path": "src/shading.rs",
|
||||
|
||||
+10
-6
@@ -38,10 +38,11 @@ std::thread_local! {
|
||||
// `InterpreterWarning::ContentTruncated`.
|
||||
static CONTENT_TRUNCATED: core::cell::Cell<bool> = const { core::cell::Cell::new(false) };
|
||||
// PdfCraft patch (89): the form XObjects being drawn on this page, outermost first, across
|
||||
// the contexts of the tiling patterns, Type 3 glyphs and groups painted while they draw; a
|
||||
// soft mask's group draws within the forms where the mask was set (`drawing_within`). A form
|
||||
// already on it draws itself and is skipped. Its length is bounded by the nesting limits:
|
||||
// every form on it is nested in the ones before it.
|
||||
// the contexts of the groups painted while they draw; a soft mask's group, a tiling pattern's
|
||||
// cell and a Type 3 glyph's procedure draw within the forms where the mask or pattern was set
|
||||
// or the glyph was shown (`drawing_within`). A form already on it draws itself and is
|
||||
// skipped. Its length is bounded by the nesting limits: every form on it is nested in the
|
||||
// ones before it.
|
||||
static FORMS_DRAWING: RefCell<Vec<hayro_syntax::object::ObjectIdentifier>> =
|
||||
const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
@@ -146,7 +147,9 @@ pub(crate) fn forms_drawing() -> Vec<hayro_syntax::object::ObjectIdentifier> {
|
||||
|
||||
/// PdfCraft patch (89): runs `draw` with `forms` as the forms being drawn, then puts back the
|
||||
/// ones it replaced. A soft mask draws its group where the masked content paints, inside forms
|
||||
/// that only use the mask; it is nested in the forms drawing where it was set.
|
||||
/// that only use the mask; it is nested in the forms drawing where it was set. A tiling pattern's
|
||||
/// cell and a Type 3 glyph's procedure are likewise nested in the forms drawing where the pattern
|
||||
/// was set or the glyph was shown, wherever the device interprets them.
|
||||
pub(crate) fn drawing_within<R>(
|
||||
forms: &[hayro_syntax::object::ObjectIdentifier],
|
||||
draw: impl FnOnce() -> R,
|
||||
@@ -402,7 +405,8 @@ impl<'a> Context<'a> {
|
||||
/// The forms being drawn are those of this page's context and of every context painting
|
||||
/// inside it (a tiling pattern, a Type 3 glyph, a soft mask or a group), so a form that
|
||||
/// reaches itself through one of those is skipped too, while a form drawn again after it
|
||||
/// has finished draws as usual.
|
||||
/// has finished draws as usual. A soft mask, tiling pattern or Type 3 glyph draws inside
|
||||
/// the forms it was set in, wherever the device interprets it ([`drawing_within`]).
|
||||
pub(crate) fn enter_form(
|
||||
&mut self,
|
||||
id: Option<hayro_syntax::object::ObjectIdentifier>,
|
||||
|
||||
+12
-2
@@ -14,6 +14,7 @@ use crate::interpret::state::State;
|
||||
use crate::{CMapResolverFn, CacheKey, FontResolverFn, InterpreterSettings, Paint};
|
||||
use bitflags::bitflags;
|
||||
use hayro_syntax::object::Name;
|
||||
use hayro_syntax::object::ObjectIdentifier;
|
||||
use hayro_syntax::object::dict::keys::SUBTYPE;
|
||||
use hayro_syntax::object::dict::keys::*;
|
||||
use hayro_syntax::object::{Dict, Stream};
|
||||
@@ -222,11 +223,17 @@ pub struct Type3Glyph<'a> {
|
||||
pub(crate) settings: InterpreterSettings,
|
||||
pub(crate) nesting_depth: u32,
|
||||
pub(crate) char_code: u32,
|
||||
/// PdfCraft patch (89): the forms being drawn where the glyph was shown; its procedure is
|
||||
/// drawn nested in them, not in the forms the device is drawing when it interprets it.
|
||||
pub(crate) forms_drawing: Vec<ObjectIdentifier>,
|
||||
}
|
||||
|
||||
/// A glyph defined by PDF drawing instructions.
|
||||
impl<'a> Type3Glyph<'a> {
|
||||
/// Draw the type3 glyph to the given device.
|
||||
///
|
||||
/// PdfCraft patch (89): the glyph procedure draws inside the forms the glyph was shown in,
|
||||
/// wherever the device interprets it.
|
||||
pub fn interpret(
|
||||
&self,
|
||||
device: &mut impl Device<'a>,
|
||||
@@ -234,8 +241,10 @@ impl<'a> Type3Glyph<'a> {
|
||||
glyph_transform: Affine,
|
||||
paint: &Paint<'a>,
|
||||
) {
|
||||
self.font
|
||||
.render_glyph(self, transform, glyph_transform, paint, device);
|
||||
crate::context::drawing_within(&self.forms_drawing, || {
|
||||
self.font
|
||||
.render_glyph(self, transform, glyph_transform, paint, device)
|
||||
});
|
||||
}
|
||||
|
||||
/// Returns the Unicode code point for this glyph, if available: the `ToUnicode` cmap, then
|
||||
@@ -386,6 +395,7 @@ impl<'a> Font<'a> {
|
||||
settings: ctx.settings.clone(),
|
||||
nesting_depth,
|
||||
char_code,
|
||||
forms_drawing: crate::context::forms_drawing(),
|
||||
};
|
||||
|
||||
Glyph::Type3(Box::new(shape_glyph))
|
||||
|
||||
Vendored
+2
@@ -40,6 +40,8 @@ mod device;
|
||||
mod function;
|
||||
mod interpret;
|
||||
mod ocg;
|
||||
#[cfg(test)]
|
||||
mod self_draw_tests;
|
||||
mod soft_mask;
|
||||
mod types;
|
||||
mod x_object;
|
||||
|
||||
+20
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::cache::Cache;
|
||||
use crate::color::{Color, ColorSpace, DefaultColorSpaces, Plate};
|
||||
use crate::context::{Context, InterpreterCache};
|
||||
use crate::context::{Context, InterpreterCache, drawing_within, forms_drawing};
|
||||
use crate::device::Device;
|
||||
use crate::font::Glyph;
|
||||
use crate::interpret::state::{ActiveTransferFunction, State};
|
||||
@@ -13,6 +13,7 @@ use crate::{BlendMode, CacheKey, ClipPath, GlyphDrawMode, Image, PathDrawMode};
|
||||
use crate::{FillRule, InterpreterSettings, Paint, interpret};
|
||||
use hayro_syntax::content::TypedIter;
|
||||
use hayro_syntax::object::Dict;
|
||||
use hayro_syntax::object::ObjectIdentifier;
|
||||
use hayro_syntax::object::Stream;
|
||||
use hayro_syntax::object::dict::keys::{
|
||||
BBOX, EXT_G_STATE, MATRIX, PAINT_TYPE, RESOURCES, SHADING, X_STEP, Y_STEP,
|
||||
@@ -182,6 +183,9 @@ pub struct TilingPattern<'a> {
|
||||
pub(crate) settings: InterpreterSettings,
|
||||
pub(crate) xref: &'a XRef,
|
||||
nesting_depth: u32,
|
||||
/// PdfCraft patch (89): the forms being drawn where the pattern was set; its cell is drawn
|
||||
/// nested in them, not in the forms that paint with it.
|
||||
forms_drawing: Vec<ObjectIdentifier>,
|
||||
}
|
||||
|
||||
impl TilingPattern<'_> {
|
||||
@@ -280,15 +284,30 @@ impl<'a> TilingPattern<'a> {
|
||||
cache: ctx.interpreter_cache.clone(),
|
||||
xref: ctx.xref,
|
||||
nesting_depth,
|
||||
forms_drawing: forms_drawing(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Interpret the contents of the pattern into the given device.
|
||||
///
|
||||
/// PdfCraft patch (89): the cell draws inside the forms the pattern was set in, wherever the
|
||||
/// device interprets it.
|
||||
pub fn interpret(
|
||||
&self,
|
||||
device: &mut impl Device<'a>,
|
||||
initial_transform: Affine,
|
||||
is_stroke: bool,
|
||||
) -> Option<()> {
|
||||
drawing_within(&self.forms_drawing, || {
|
||||
self.interpret_cell(device, initial_transform, is_stroke)
|
||||
})
|
||||
}
|
||||
|
||||
fn interpret_cell(
|
||||
&self,
|
||||
device: &mut impl Device<'a>,
|
||||
initial_transform: Affine,
|
||||
is_stroke: bool,
|
||||
) -> Option<()> {
|
||||
// PdfCraft patch: a tiling pattern can paint itself (directly, or through resources it
|
||||
// inherits when its own are missing), which recursed until the stack overflowed. Bound
|
||||
|
||||
+328
@@ -0,0 +1,328 @@
|
||||
//! PdfCraft patch (89) tests: a form that draws itself through a soft mask, a tiling pattern or
|
||||
//! a Type 3 glyph set inside it is skipped, and the page is not reported truncated. A soft mask,
|
||||
//! tiling pattern or Type 3 glyph set outside a form draws that form in full when the device
|
||||
//! interprets it while drawing the form. The tests of a form that draws itself directly or
|
||||
//! through another form are in `context.rs`.
|
||||
|
||||
use crate::context::content_was_truncated;
|
||||
use crate::font::{Glyph, Type3Glyph};
|
||||
use crate::pattern::Pattern;
|
||||
use crate::{
|
||||
BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache,
|
||||
InterpreterSettings, InterpreterWarning, Paint, PathDrawMode, SoftMask, interpret_page,
|
||||
};
|
||||
use hayro_syntax::Pdf;
|
||||
use kurbo::{Affine, BezPath, Rect};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// A PDF with one 100 by 100 page whose resources are `resources` and whose content is
|
||||
/// `content`, followed by `objects` as objects 5, 6 and so on.
|
||||
fn pdf(resources: &str, content: &str, objects: &[String]) -> Pdf {
|
||||
let mut bodies = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Count 1 /Kids [3 0 R] >>".to_string(),
|
||||
format!(
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources {resources} >>"
|
||||
),
|
||||
stream("", content),
|
||||
];
|
||||
bodies.extend_from_slice(objects);
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, body) in bodies.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(
|
||||
format!("xref\n0 {}\n0000000000 65535 f \n", bodies.len() + 1).as_bytes(),
|
||||
);
|
||||
for offset in offsets {
|
||||
out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(
|
||||
format!(
|
||||
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n",
|
||||
bodies.len() + 1
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
Pdf::new(out).expect("synthetic pdf")
|
||||
}
|
||||
|
||||
fn stream(entries: &str, content: &str) -> String {
|
||||
format!(
|
||||
"<< /Length {} {entries} >>\nstream\n{content}\nendstream",
|
||||
content.len()
|
||||
)
|
||||
}
|
||||
|
||||
/// A form 10 by 10 that draws `content` with the resources of whatever draws it.
|
||||
fn form(content: &str) -> String {
|
||||
stream("/Type /XObject /Subtype /Form /BBox [0 0 10 10]", content)
|
||||
}
|
||||
|
||||
/// A soft mask group that draws `content` with `resources`.
|
||||
fn mask_group(resources: &str, content: &str) -> String {
|
||||
stream(
|
||||
&format!(
|
||||
"/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency >> /Resources {resources}"
|
||||
),
|
||||
content,
|
||||
)
|
||||
}
|
||||
|
||||
/// A colored tiling pattern whose cell draws `content` with `resources`.
|
||||
fn tiling(resources: &str, content: &str) -> String {
|
||||
stream(
|
||||
&format!(
|
||||
"/Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources {resources}"
|
||||
),
|
||||
content,
|
||||
)
|
||||
}
|
||||
|
||||
/// A Type 3 font whose glyph `a` is drawn by the procedure in object `proc`, with `resources`.
|
||||
fn type3(resources: &str, proc: usize) -> String {
|
||||
format!(
|
||||
"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << /a {proc} 0 R >> /Encoding << /Type /Encoding /Differences [97 /a] >> /FirstChar 97 /LastChar 97 /Widths [1000] /Resources {resources} >>"
|
||||
)
|
||||
}
|
||||
|
||||
/// The paths a device was given, by where they were drawn.
|
||||
#[derive(Default, Debug, PartialEq)]
|
||||
struct Drawn {
|
||||
paths: usize,
|
||||
in_masks: usize,
|
||||
in_patterns: usize,
|
||||
in_glyphs: usize,
|
||||
}
|
||||
|
||||
/// A device that interprets every soft mask it is given, every tiling pattern it fills with and
|
||||
/// every Type 3 glyph it draws, each into a device of its own, at the time it is given them. With
|
||||
/// `defer_glyphs`, it keeps the first Type 3 glyph and interprets it at the next path instead.
|
||||
#[derive(Default)]
|
||||
struct Recorder<'a> {
|
||||
drawn: Drawn,
|
||||
defer_glyphs: bool,
|
||||
deferred: Option<Box<Type3Glyph<'a>>>,
|
||||
}
|
||||
|
||||
impl Recorder<'_> {
|
||||
fn absorb(&mut self, inner: &Recorder<'_>) -> usize {
|
||||
let d = &inner.drawn;
|
||||
self.drawn.in_masks += d.in_masks;
|
||||
self.drawn.in_patterns += d.in_patterns;
|
||||
self.drawn.in_glyphs += d.in_glyphs;
|
||||
d.paths
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Device<'a> for Recorder<'a> {
|
||||
fn set_soft_mask(&mut self, mask: Option<SoftMask<'a>>) {
|
||||
if let Some(mask) = mask {
|
||||
let mut inner = Recorder::default();
|
||||
mask.interpret(&mut inner);
|
||||
self.drawn.in_masks += self.absorb(&inner);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_blend_mode(&mut self, _: BlendMode) {}
|
||||
|
||||
fn draw_path(&mut self, _: &BezPath, transform: Affine, paint: &Paint<'a>, _: &PathDrawMode) {
|
||||
self.drawn.paths += 1;
|
||||
if let Paint::Pattern(pattern) = paint
|
||||
&& let Pattern::Tiling(tiling) = &**pattern
|
||||
{
|
||||
let mut inner = Recorder::default();
|
||||
tiling.interpret(&mut inner, transform, false);
|
||||
self.drawn.in_patterns += self.absorb(&inner);
|
||||
}
|
||||
if let Some(glyph) = self.deferred.take() {
|
||||
let mut inner = Recorder::default();
|
||||
glyph.interpret(&mut inner, Affine::IDENTITY, Affine::IDENTITY, paint);
|
||||
self.drawn.in_glyphs += self.absorb(&inner);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_clip_path(&mut self, _: &ClipPath) {}
|
||||
|
||||
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'a>>, _: BlendMode) {}
|
||||
|
||||
fn draw_glyph(
|
||||
&mut self,
|
||||
glyph: &Glyph<'a>,
|
||||
transform: Affine,
|
||||
glyph_transform: Affine,
|
||||
paint: &Paint<'a>,
|
||||
_: &GlyphDrawMode,
|
||||
) {
|
||||
let Glyph::Type3(glyph) = glyph else {
|
||||
return;
|
||||
};
|
||||
if self.defer_glyphs {
|
||||
self.deferred = Some(glyph.clone());
|
||||
return;
|
||||
}
|
||||
let mut inner = Recorder::default();
|
||||
glyph.interpret(&mut inner, transform, glyph_transform, paint);
|
||||
self.drawn.in_glyphs += self.absorb(&inner);
|
||||
}
|
||||
|
||||
fn draw_image(&mut self, _: Image<'a, '_>, _: Affine) {}
|
||||
|
||||
fn pop_clip_path(&mut self) {}
|
||||
|
||||
fn pop_transparency_group(&mut self) {}
|
||||
}
|
||||
|
||||
/// Draws the page of `pdf` and returns what was drawn and whether the page was reported
|
||||
/// truncated.
|
||||
fn draw(pdf: &Pdf, defer_glyphs: bool) -> (Drawn, bool) {
|
||||
let cache = InterpreterCache::new();
|
||||
let warnings = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = warnings.clone();
|
||||
let settings = InterpreterSettings {
|
||||
warning_sink: Arc::new(move |warning| sink.lock().expect("warnings").push(warning)),
|
||||
..InterpreterSettings::default()
|
||||
};
|
||||
let mut ctx = Context::new(
|
||||
Affine::IDENTITY,
|
||||
Rect::new(0.0, 0.0, 100.0, 100.0),
|
||||
&cache,
|
||||
pdf.xref(),
|
||||
settings,
|
||||
);
|
||||
let mut device = Recorder {
|
||||
defer_glyphs,
|
||||
..Recorder::default()
|
||||
};
|
||||
let page = &pdf.pages()[0];
|
||||
interpret_page(page, &mut ctx, &mut device);
|
||||
let warnings = warnings.lock().expect("warnings");
|
||||
let truncated = warnings
|
||||
.iter()
|
||||
.any(|w| matches!(w, InterpreterWarning::ContentTruncated));
|
||||
assert_eq!(truncated, content_was_truncated());
|
||||
(device.drawn, truncated)
|
||||
}
|
||||
|
||||
const SQUARE: &str = "0 0 10 10 re f";
|
||||
|
||||
// A form that names itself in its own resources is a reference cycle, which hayro-syntax reads
|
||||
// as a missing object. The forms below have no resources of their own and reach themselves
|
||||
// through the page's.
|
||||
|
||||
#[test]
|
||||
fn a_soft_mask_set_outside_a_form_draws_that_form() {
|
||||
// The mask is set on the page and draws the form the page then draws; the device interprets
|
||||
// it while it draws that form.
|
||||
let pdf = pdf(
|
||||
"<< /XObject << /F 5 0 R >> /ExtGState << /GS << /SMask << /S /Alpha /G 6 0 R >> >> >> >>",
|
||||
"/GS gs /F Do",
|
||||
&[
|
||||
form(SQUARE),
|
||||
mask_group("<< /XObject << /F 5 0 R >> >>", "/F Do"),
|
||||
],
|
||||
);
|
||||
let (drawn, truncated) = draw(&pdf, false);
|
||||
assert!(drawn.in_masks > 0, "{drawn:?}");
|
||||
assert_eq!(drawn.paths, 1);
|
||||
assert!(!truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_soft_mask_set_inside_a_form_that_it_draws_skips_that_form() {
|
||||
let pdf = pdf(
|
||||
"<< /XObject << /F 5 0 R >> /ExtGState << /GS << /SMask << /S /Alpha /G 6 0 R >> >> >> >>",
|
||||
"/F Do",
|
||||
&[
|
||||
form("/GS gs 0 0 10 10 re f"),
|
||||
mask_group("<< /XObject << /F 5 0 R >> >>", "/F Do"),
|
||||
],
|
||||
);
|
||||
let (drawn, truncated) = draw(&pdf, false);
|
||||
assert_eq!(
|
||||
drawn,
|
||||
Drawn {
|
||||
paths: 1,
|
||||
..Drawn::default()
|
||||
}
|
||||
);
|
||||
assert!(!truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tiling_pattern_set_outside_a_form_draws_that_form() {
|
||||
let pdf = pdf(
|
||||
"<< /XObject << /F 5 0 R >> /Pattern << /P 6 0 R >> >>",
|
||||
"/Pattern cs /P scn /F Do",
|
||||
&[
|
||||
form(SQUARE),
|
||||
tiling("<< /XObject << /F 5 0 R >> >>", "/F Do"),
|
||||
],
|
||||
);
|
||||
let (drawn, truncated) = draw(&pdf, false);
|
||||
assert!(drawn.in_patterns > 0, "{drawn:?}");
|
||||
assert!(!truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tiling_pattern_set_inside_a_form_that_it_draws_skips_that_form() {
|
||||
let pdf = pdf(
|
||||
"<< /XObject << /F 5 0 R >> /Pattern << /P 6 0 R >> >>",
|
||||
"/F Do",
|
||||
&[
|
||||
form("/Pattern cs /P scn 0 0 10 10 re f"),
|
||||
tiling("<< /XObject << /F 5 0 R >> >>", "/F Do"),
|
||||
],
|
||||
);
|
||||
let (drawn, truncated) = draw(&pdf, false);
|
||||
assert_eq!(
|
||||
drawn,
|
||||
Drawn {
|
||||
paths: 1,
|
||||
..Drawn::default()
|
||||
}
|
||||
);
|
||||
assert!(!truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_type3_glyph_shown_outside_a_form_draws_that_form() {
|
||||
// The device keeps the glyph shown on the page and interprets it while it draws the form.
|
||||
let pdf = pdf(
|
||||
"<< /XObject << /F 5 0 R >> /Font << /T 6 0 R >> >>",
|
||||
"BT /T 10 Tf (a) Tj ET /F Do",
|
||||
&[
|
||||
form(SQUARE),
|
||||
type3("<< /XObject << /F 5 0 R >> >>", 7),
|
||||
stream("", "1000 0 d0 /F Do"),
|
||||
],
|
||||
);
|
||||
let (drawn, truncated) = draw(&pdf, true);
|
||||
assert!(drawn.in_glyphs > 0, "{drawn:?}");
|
||||
assert!(!truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_type3_glyph_shown_inside_a_form_that_it_draws_skips_that_form() {
|
||||
let pdf = pdf(
|
||||
"<< /XObject << /F 5 0 R >> /Font << /T 6 0 R >> >>",
|
||||
"/F Do",
|
||||
&[
|
||||
form("BT /T 10 Tf (a) Tj ET 0 0 10 10 re f"),
|
||||
type3("<< /XObject << /F 5 0 R >> >>", 7),
|
||||
stream("", "1000 0 d0 /F Do"),
|
||||
],
|
||||
);
|
||||
let (drawn, truncated) = draw(&pdf, false);
|
||||
assert_eq!(
|
||||
drawn,
|
||||
Drawn {
|
||||
paths: 1,
|
||||
..Drawn::default()
|
||||
}
|
||||
);
|
||||
assert!(!truncated);
|
||||
}
|
||||
Reference in new issue
Block a user