alpha2-eval 0.10.0

Pure alpha2 timeline evaluation.
Documentation
//! Shape geometry queries on project-form JSON; positions normalized, lengths in pixels.

use super::{aspect, canvas, time, to_text};
use alpha2_geometry::kurbo::Point;
use alpha2_geometry::{EvaluatedPath, query};
use alpha2_model::{AnimatedPoint, Path, PathVertex, ShapeGeometry, ShapeItem, Subpath, Vec2};
use alpha2_time::MediaTime;
use serde_json::{Value, json};

const MOTION_SAMPLES_PER_SEGMENT: u32 = 32;

fn items(json: &str) -> Result<Vec<ShapeItem>, String> {
    let items: Vec<ShapeItem> =
        serde_json::from_str(json).map_err(|error| format!("invalid shape items: {error}"))?;
    alpha2_model::validate_shape_items(&items)
        .map_err(|issue| format!("invalid shape items: {} {}", issue.at, issue.problem))?;
    Ok(items)
}

fn path(json: &str) -> Result<EvaluatedPath, String> {
    let path: Path =
        serde_json::from_str(json).map_err(|error| format!("invalid path: {error}"))?;
    let finite = path.subpaths.iter().all(|subpath| {
        subpath.vertices.iter().all(|vertex| {
            [vertex.point, vertex.in_tangent, vertex.out_tangent]
                .iter()
                .all(|value| value.x.is_finite() && value.y.is_finite())
        })
    });
    if !finite {
        return Err("invalid path: a point or tangent is not finite".into());
    }
    Ok(EvaluatedPath::from(&path))
}

#[allow(clippy::cast_possible_truncation)]
fn document_path(path: &EvaluatedPath) -> Path {
    let vector = |x: f64, y: f64| Vec2::new(x as f32, y as f32);
    Path {
        subpaths: path
            .subpaths
            .iter()
            .map(|subpath| Subpath {
                closed: subpath.closed,
                vertices: subpath
                    .vertices
                    .iter()
                    .map(|vertex| PathVertex {
                        point: vector(vertex.point.x, vertex.point.y),
                        in_tangent: vector(vertex.in_tangent.x, vertex.in_tangent.y),
                        out_tangent: vector(vertex.out_tangent.x, vertex.out_tangent.y),
                    })
                    .collect(),
            })
            .collect(),
    }
}

/// Each item's normalized bounds, in document order: `[{ at, bounds }]`, with `bounds`
/// `{ x0, y0, x1, y1 }` or `null` for an item that shows nothing.
///
/// # Errors
/// Refuses items that are not a valid content tree, or a bad size or time.
pub fn shape_bounds(
    items_json: &str,
    ticks: f64,
    width: u32,
    height: u32,
) -> Result<String, String> {
    let size = canvas(width, height)?;
    let evaluated = crate::evaluate_items(&items(items_json)?, time(ticks)?, aspect(size));
    let bounds: Vec<Value> = query::shape_bounds(&evaluated, size)
        .into_iter()
        .map(|(at, bounds)| {
            json!({
                "at": at,
                "bounds": bounds.map(|rect| json!({ "x0": rect.x0, "y0": rect.y0, "x1": rect.x1, "y1": rect.y1 })),
            })
        })
        .collect();
    to_text(&bounds)
}

/// The front-most fill or stroke painting the normalized point `(x, y)`, as a tree path like
/// `items[0].items[2]`.
///
/// # Errors
/// Refuses items that are not a valid content tree, or a bad size or time.
pub fn hit_test(
    items_json: &str,
    ticks: f64,
    (width, height): (u32, u32),
    (x, y): (f64, f64),
) -> Result<Option<String>, String> {
    let size = canvas(width, height)?;
    let evaluated = crate::evaluate_items(&items(items_json)?, time(ticks)?, aspect(size));
    Ok(query::hit_test(&evaluated, size, Point::new(x, y)))
}

/// The point of a path nearest `(x, y)`: `{ subpath, segment, t, point, distance }`
/// (`distance` in pixels), or `null` for an empty path.
///
/// # Errors
/// Refuses an invalid path or size.
pub fn nearest_point(
    path_json: &str,
    (width, height): (u32, u32),
    (x, y): (f64, f64),
) -> Result<String, String> {
    let size = canvas(width, height)?;
    let nearest = query::nearest_point(&path(path_json)?, size, Point::new(x, y)).map(|found| {
        json!({
            "subpath": found.subpath,
            "segment": found.segment,
            "t": found.t,
            "point": { "x": found.point.x, "y": found.point.y },
            "distance": found.distance,
        })
    });
    to_text(&nearest)
}

/// Each subpath's length in pixels, as a JSON array.
///
/// # Errors
/// Refuses an invalid path or size.
pub fn path_length(path_json: &str, width: u32, height: u32) -> Result<String, String> {
    to_text(&query::path_lengths(
        &path(path_json)?,
        canvas(width, height)?,
    ))
}

/// The part of `path` a trim keeps: `start` to `end` as fractions of its total pixel length,
/// shifted by `offset` turns.
///
/// # Errors
/// Refuses an invalid path, size, or span.
pub fn trim_path(
    path_json: &str,
    (width, height): (u32, u32),
    (start, end, offset): (f64, f64, f64),
) -> Result<String, String> {
    if ![start, end, offset].iter().all(|value| value.is_finite()) {
        return Err("a trim's start, end, and offset are finite".into());
    }
    let trimmed = query::trim_path(
        &path(path_json)?,
        canvas(width, height)?,
        start.clamp(0.0, 1.0),
        end.clamp(0.0, 1.0),
        offset,
    );
    to_text(&document_path(&trimmed))
}

/// `path` with `counts[i]` vertices on subpath `i`, evenly along its length.
///
/// # Errors
/// Refuses an invalid path or size, or a count past the vertex limit.
pub fn resample_path(
    path_json: &str,
    (width, height): (u32, u32),
    counts: &[u32],
) -> Result<String, String> {
    if counts
        .iter()
        .any(|count| *count as usize > alpha2_model::MAX_PATH_VERTICES)
    {
        return Err(format!(
            "a subpath has at most {} vertices",
            alpha2_model::MAX_PATH_VERTICES
        ));
    }
    let counts: Vec<usize> = counts.iter().map(|count| *count as usize).collect();
    let resampled = query::resample_path(&path(path_json)?, canvas(width, height)?, &counts);
    to_text(&document_path(&resampled))
}

/// A rectangle, ellipse, or polystar at `ticks` as a path with the same outline.
///
/// # Errors
/// Refuses an invalid geometry, size, or time.
pub fn to_path(geometry_json: &str, ticks: f64, width: u32, height: u32) -> Result<String, String> {
    let geometry: ShapeGeometry = serde_json::from_str(geometry_json)
        .map_err(|error| format!("invalid geometry: {error}"))?;
    geometry
        .validate("geometry")
        .map_err(|issue| format!("invalid geometry: {} {}", issue.at, issue.problem))?;
    let size = canvas(width, height)?;
    let evaluated = crate::evaluate_geometry(
        &geometry,
        time(ticks)?,
        aspect(size),
        &crate::SampleContext::NONE,
    );
    to_text(&document_path(&query::to_path(&evaluated, size)))
}

/// The polyline a position travels between its keyframes, as JSON `[{ x, y }]`.
///
/// # Errors
/// Refuses an invalid position or size.
pub fn motion_path(point_json: &str, width: u32, height: u32) -> Result<String, String> {
    let point: AnimatedPoint =
        serde_json::from_str(point_json).map_err(|error| format!("invalid position: {error}"))?;
    let size = canvas(width, height)?;
    let scale = size.scale();
    let pixel = |value: Vec2| {
        alpha2_geometry::kurbo::Vec2::new(
            f64::from(value.x) * scale.x,
            f64::from(value.y) * scale.y,
        )
    };
    if let AnimatedPoint::Split { channels } = &point {
        let polyline: Vec<Value> = split_motion_times(channels)
            .into_iter()
            .map(|time| {
                let at =
                    crate::sample_point(&point, time, aspect(size), &crate::SampleContext::NONE);
                json!({ "x": at.x, "y": at.y })
            })
            .collect();
        return to_text(&polyline);
    }
    let keys: Vec<_> = match &point {
        AnimatedPoint::Constant { value } => vec![(
            pixel(*value).to_point(),
            alpha2_geometry::kurbo::Vec2::ZERO,
            alpha2_geometry::kurbo::Vec2::ZERO,
        )],
        AnimatedPoint::Keyframes { keyframes, .. } => keyframes
            .iter()
            .map(|keyframe| {
                (
                    pixel(keyframe.value).to_point(),
                    pixel(keyframe.out_tangent),
                    pixel(keyframe.in_tangent),
                )
            })
            .collect(),
        AnimatedPoint::Path(motion) => motion
            .path
            .subpaths
            .first()
            .map(|subpath| {
                let closing = subpath.vertices.first().filter(|_| subpath.closed);
                subpath
                    .vertices
                    .iter()
                    .chain(closing)
                    .map(|vertex| {
                        (
                            pixel(vertex.point).to_point(),
                            pixel(vertex.out_tangent),
                            pixel(vertex.in_tangent),
                        )
                    })
                    .collect()
            })
            .unwrap_or_default(),
        AnimatedPoint::Data(_) | AnimatedPoint::Split { .. } => Vec::new(),
    };
    let polyline: Vec<Value> =
        alpha2_geometry::spatial::motion_polyline(&keys, MOTION_SAMPLES_PER_SEGMENT)
            .into_iter()
            .map(|at| json!({ "x": at.x / scale.x, "y": at.y / scale.y }))
            .collect();
    to_text(&polyline)
}

fn split_motion_times(channels: &[alpha2_model::Animated<f32>]) -> Vec<MediaTime> {
    let mut keys: Vec<i64> = channels
        .iter()
        .filter_map(|channel| match channel {
            alpha2_model::Animated::Keyframes { keyframes, .. } => Some(keyframes),
            _ => None,
        })
        .flatten()
        .map(|keyframe| keyframe.time.ticks())
        .collect();
    keys.sort_unstable();
    keys.dedup();
    let Some(last) = keys.last().copied() else {
        return vec![MediaTime::ZERO];
    };
    let mut times = Vec::new();
    for pair in keys.windows(2) {
        let span = i128::from(pair[1]) - i128::from(pair[0]);
        for step in 0..MOTION_SAMPLES_PER_SEGMENT {
            let offset = span * i128::from(step) / i128::from(MOTION_SAMPLES_PER_SEGMENT);
            times.push(MediaTime(
                i64::try_from(i128::from(pair[0]) + offset).unwrap_or(pair[0]),
            ));
        }
    }
    times.push(MediaTime(last));
    times.dedup();
    times
}

/// Answers on fixed inputs that every surface gives byte for byte
/// (`tests/golden/geometry_queries.json`), by service name.
///
/// # Panics
/// Panics if a fixed input is refused.
#[must_use]
pub fn parity_cases() -> Vec<(&'static str, String)> {
    let star = r#"{ "type": "polystar", "kind": "star",
        "center": { "mode": "constant", "value": { "x": 0.5, "y": 0.5 } },
        "points": { "mode": "constant", "value": 5 },
        "outer_radius": { "mode": "constant", "value": 0.4 },
        "inner_radius": { "mode": "constant", "value": 0.2 },
        "outer_roundness": { "mode": "constant", "value": 0.3 },
        "rotation_degrees": { "mode": "constant", "value": 12 } }"#;
    let curve = r#"{ "subpaths": [ { "closed": false, "vertices": [
        { "point": { "x": 0.1, "y": 0.8 }, "out_tangent": { "x": 0.2, "y": -0.6 } },
        { "point": { "x": 0.9, "y": 0.2 }, "in_tangent": { "x": -0.3, "y": 0.1 } } ] } ] }"#;
    let tree = format!(
        r#"[ {{ "type": "group", "transform": {{
                "position": {{ "mode": "constant", "value": {{ "x": 0.5, "y": 0.5 }} }},
                "rotation_degrees": {{ "mode": "keyframes", "keyframes": [
                  {{ "time": 0, "value": 0, "interpolation": {{ "type": "linear" }} }},
                  {{ "time": 120000, "value": 90, "interpolation": {{ "type": "hold" }} }} ] }} }},
              "items": [ {star_at_origin}, {{ "type": "stroke", "width": {{ "mode": "constant", "value": 0.02 }},
                "paint": {{ "mode": "constant", "value": {{ "type": "solid",
                  "color": {{ "red": 1, "green": 1, "blue": 1, "alpha": 1 }} }} }} }} ] }},
             {{ "type": "path", "path": {{ "mode": "constant", "value": {curve} }} }},
             {{ "type": "trim", "start": {{ "mode": "constant", "value": 0.2 }},
               "end": {{ "mode": "constant", "value": 0.7 }} }},
             {{ "type": "fill", "rule": "evenodd", "paint": {{ "mode": "constant", "value": {{ "type": "solid",
                "color": {{ "red": 1, "green": 0, "blue": 0, "alpha": 1 }} }} }} }} ]"#,
        star_at_origin = star.replace(r#"{ "x": 0.5, "y": 0.5 }"#, r#"{ "x": 0, "y": 0 }"#),
    );
    let size = (320, 180);
    let on_a_path = r#"{ "mode": "path",
        "path": { "subpaths": [ { "closed": false, "vertices": [
            { "point": { "x": 0.25, "y": 0.25 }, "out_tangent": { "x": 0.15, "y": 0 } },
            { "point": { "x": 0.75, "y": 0.75 }, "in_tangent": { "x": 0, "y": -0.3 } } ] } ] },
        "distance": { "mode": "keyframes", "after": "ping_pong", "keyframes": [
            { "time": 0, "value": 0, "interpolation": { "type": "cubic_bezier", "x1": 0.42, "y1": 0, "x2": 0.58, "y2": 1 } },
            { "time": 1000, "value": 1, "interpolation": { "type": "linear" } } ] } }"#;
    vec![
        (
            "motionPathOnAPath",
            motion_path(on_a_path, size.0, size.1).expect("motion"),
        ),
        (
            "pathAngle",
            format!(
                "{:?}",
                [0.0, 250.0, 500.0, 1000.0, 1400.0].map(|ticks| {
                    super::curves::path_angle(on_a_path, ticks, size.0, size.1).expect("angle")
                })
            ),
        ),
        ("shapeBounds", shape_bounds(&tree, 60_000.0, size.0, size.1).expect("bounds")),
        (
            "hitTest",
            format!(
                "{:?}",
                [(0.5, 0.5), (0.3, 0.45), (0.9, 0.9)]
                    .map(|point| hit_test(&tree, 60_000.0, size, point).expect("hit"))
            ),
        ),
        ("nearestPoint", nearest_point(curve, size, (0.4, 0.3)).expect("nearest")),
        ("pathLength", path_length(curve, size.0, size.1).expect("length")),
        ("trimPath", trim_path(curve, size, (0.25, 0.75, 0.1)).expect("trim")),
        ("resamplePath", resample_path(curve, size, &[5]).expect("resample")),
        ("toPath", to_path(star, 0.0, size.0, size.1).expect("path")),
        (
            "motionPath",
            motion_path(
                r#"{ "mode": "keyframes", "keyframes": [
                    { "time": 0, "value": { "x": 0.2, "y": 0.5 }, "interpolation": { "type": "linear" },
                      "out_tangent": { "x": 0.1, "y": -0.3 } },
                    { "time": 1000, "value": { "x": 0.8, "y": 0.5 }, "interpolation": { "type": "hold" },
                      "in_tangent": { "x": -0.1, "y": -0.3 } } ] }"#,
                size.0,
                size.1,
            )
            .expect("motion"),
        ),
    ]
}

#[cfg(test)]
#[path = "geometry_tests.rs"]
mod tests;