Skip to main content

Path2D

Struct Path2D 

Source
pub struct Path2D { /* private fields */ }
Expand description

A cheaply cloned, checked f64 path with lazily cached geometric bounds.

Chainable mutations retain their first diagnostic for compile-time validation. The try_ methods return failures immediately and leave the snapshot unchanged. Bounds include move positions and curve extrema, not the curve control hull. Empty paths have zero bounds at the origin. SVG path data imports through Self::parse_svg. Arc lengths use cached bounded Gaussian integration; partial curves retain their Bezier representation rather than flattening. crate::Shape::stroke expands bounded curves into fill outlines; Styled trim/dash share the same arc-length parameterization.

use motion_core::prelude::*;
use motion_core::{
    DisplayList, RasterLimits, ResourcePool, ValidatedDisplayList, MAX_PATH_VERBS,
    MAX_STROKE_VERBS, MAX_SVG_PATH_BYTES, sample_offsets,
};
let mut path = Path2D::new();
path.move_to(Point::ORIGIN)
    .quadratic_to(Point::new(10.0, 20.0), Point::new(20.0, 0.0))
    .close();
assert_eq!(path.bounding_box(), Rect::new(0.0, 0.0, 20.0, 10.0));
let node = path
    .fill(Color::from_hex(0x24a49b))
    .fill_rule(FillRule::EvenOdd)
    .at(Point::new(100.0, 80.0));
assert_eq!(
    node.measure(ValidationLimits::default())?,
    Rect::new(90.0, 75.0, 110.0, 85.0)
);
let list = node.compile(
    Size::new(200.0, 160.0),
    PixelSize::new(200, 160),
    ValidationLimits::default(),
)?;
assert_eq!(list.commands.len(), 1);
assert!(matches!(
    list.commands[0],
    DrawCommand::Fill {
        rule: FillRule::EvenOdd,
        ..
    }
));

Implementations§

Source§

impl Path2D

Source

pub fn from_rect(bounds: Rect) -> Result<Self, ValidationError>

Builds a closed rectangle, rejecting invalid bounds before any mutation.

Source

pub fn polyline(points: impl IntoIterator<Item = Point>) -> Self

Builds a bounded polyline, retaining invalid-input diagnostics for compilation.

Source

pub fn parse_svg(path_data: &str) -> Result<Self, ValidationError>

Imports SVG path data, not an XML document, without rasterizing geometry.

Supports absolute/relative M/L/H/V/C/S/Q/T/A/Z, including repeated argument groups and reflected smooth controls. Empty data produces an empty path. A/a arcs become bounded cubic segments; zero radii become lines and coincident endpoints emit nothing. Syntax, nonfinite arithmetic and overflowing control extents return InvalidValue; input beyond MAX_SVG_PATH_BYTES or MAX_PATH_VERBS returns StructuralLimit. Parsed commands and expanded verbs have independent MAX_PATH_VERBS caps. Errors discard the entire result; there is no partial-path recovery, I/O or cache.

use motion_core::prelude::*;
use motion_core::{
    DisplayList, RasterLimits, ResourcePool, ValidatedDisplayList, MAX_PATH_VERBS,
    MAX_STROKE_VERBS, MAX_SVG_PATH_BYTES, sample_offsets,
};
let path = Path2D::parse_svg("M1 1h6v6H1z")?;
assert_eq!(path, Path2D::from_rect(Rect::new(1.0, 1.0, 7.0, 7.0))?);
let frame = Node::from(path.fill(Color::WHITE)).compile(
    Size::new(8.0, 8.0),
    PixelSize::new(8, 8),
    ValidationLimits::default(),
)?;
Source§

impl Path2D

Source

pub fn move_to(&mut self, point: Point) -> &mut Self

Starts a subpath; invalid input is reported when the path is compiled.

Source

pub fn try_move_to(&mut self, point: Point) -> Result<(), ValidationError>

Starts a new subpath.

Source

pub fn line_to(&mut self, point: Point) -> &mut Self

Adds a line, deferring invalid state or coordinates to compilation.

Source

pub fn try_line_to(&mut self, point: Point) -> Result<(), ValidationError>

Adds a line; requires a preceding move.

Source

pub fn quadratic_to(&mut self, control: Point, end: Point) -> &mut Self

Adds a quadratic curve, deferring invalid input to compilation.

Source

pub fn try_quadratic_to( &mut self, control: Point, end: Point, ) -> Result<(), ValidationError>

Adds a quadratic Bezier; requires a preceding move.

Source

pub fn cubic_to(&mut self, first: Point, second: Point, end: Point) -> &mut Self

Adds a cubic curve, deferring invalid input to compilation.

Source

pub fn try_cubic_to( &mut self, first: Point, second: Point, end: Point, ) -> Result<(), ValidationError>

Adds a cubic Bezier; requires a preceding move.

Source

pub fn arc_to( &mut self, center: Point, radii: Vector2, start_angle: f64, sweep_angle: f64, ) -> &mut Self

Appends an arc and retains the first invalid input for compile-time reporting.

Source

pub fn try_arc_to( &mut self, center: Point, radii: Vector2, start_angle: f64, sweep_angle: f64, ) -> Result<(), ValidationError>

Appends a clockwise elliptical arc in radians, connecting to its start. Radii must be finite and nonnegative. Cubics span at most pi/8 radians; errors, including exhausted verb limits, leave the path unchanged. Circular arcs use a cubic approximation, not rational/exact circle verbs.

use motion_core::{Path2D, Point, Vector2};
let mut path = Path2D::new();
path.arc_to(
    Point::ORIGIN,
    Vector2::new(4.0, 4.0),
    0.0,
    std::f64::consts::FRAC_PI_2,
);
assert!((path.length() - 2.0 * std::f64::consts::PI).abs() < 1e-6);
let middle = path.trim(0.25, 0.75);
assert!((middle.length() - path.length() * 0.5).abs() < 1e-7);
Source

pub fn close(&mut self) -> &mut Self

Closes the current contour, deferring invalid state to compilation.

Source

pub fn try_close(&mut self) -> Result<(), ValidationError>

Closes the current subpath; requires a preceding move.

Source

pub fn closed(self) -> Self

Closes and returns this path for direct styling.

Source§

impl Path2D

Source

pub fn cubic_breakpoints(&self) -> Result<Vec<f64>, ValidationError>

Returns normalized arc-length boundaries for curve morphing.

Source

pub fn cubic_intervals( &self, fractions: &[f64], ) -> Result<Vec<[Point; 4]>, ValidationError>

Extracts cubic representations of checked normalized arc-length intervals.

Source

pub fn length(&self) -> f64

Returns cached total contour length, including explicit closing edges. Panics if integration overflows or exhausts its bounded precision/work.

Source

pub fn try_length(&self) -> Result<f64, ValidationError>

Checked arc length with bounded adaptive eight-point Gaussian integration.

Source

pub fn point_at(&self, progress: f64) -> (Point, Vector2)

Samples normalized arc distance and its unit forward tangent. Progress clamps to 0..=1; nonfinite inputs or metric failures panic.

Source

pub fn try_point_at( &self, progress: f64, ) -> Result<(Point, Vector2), ValidationError>

Checked sampling. Empty/move-only paths have a zero tangent. At a cusp, uses the forward one-sided direction, or backward direction at the end.

Source

pub fn trim(&self, start: f64, end: f64) -> Self

Extracts a normalized arc-length interval, preserving Bezier segments. Clamps finite endpoints; empty/reversed intervals produce an empty path. Panics on invalid inputs or numerical/resource failure; see try_trim.

Source

pub fn try_trim(&self, start: f64, end: f64) -> Result<Self, ValidationError>

Checked de Casteljau extraction. Full range preserves all original verbs.

Source

pub fn dashed( &self, pattern: &[f64], offset: f64, ) -> Result<Self, ValidationError>

Cuts positive finite dash/gap lengths in logical units. Odd patterns repeat twice; phase restarts per contour and positive offsets advance it. Empty patterns retain the path. At most 256 entries and 8192 visible intervals per contour are admitted; generated verbs remain bounded.

Source§

impl Path2D

Source

pub fn new() -> Self

Creates an empty chainable path without paint.

Source

pub fn verbs(&self) -> &[PathVerb]

Returns the immutable absolute f64 verbs.

Source

pub fn bounding_box(&self) -> Rect

Returns cached f64 geometric bounds, retaining zero-area geometry.

Source

pub fn transformed( &self, transform: &Transform, ) -> Result<Self, ValidationError>

Maps all endpoints and controls without flattening or modifying this path.

Source

pub fn shared_verbs(&self) -> Arc<Vec<PathVerb>> ⓘ

Shares only the immutable verb snapshot, without retaining metric caches. Arc::make_mut on a returned handle cannot edit this path’s snapshot.

Source

pub fn axis_aligned_rectangle(&self) -> Option<Rect>

Bounds of a single nondegenerate four-edge axis-aligned closed contour. Curves, extra contours, retraced edges and nonrectangular paths return None.

Source

pub fn fingerprint(&self) -> u64

Stable content fingerprint shared by clones and invalidated by successful edits. This is a lookup hint, not a collision-free geometry identity.

Trait Implementations§

Source§

impl Clone for Path2D

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Path2D

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Path2D

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl From<Path2D> for PathClip

Source§

fn from(path: Path2D) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for Path2D

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Shape for Path2D

Source§

fn validate(&self) -> Result<(), ValidationError>

Reports retained authoring errors before measuring or drawing.
Source§

fn path(&self) -> Path2D

Returns a checked path snapshot without f32 narrowing.
Source§

fn bounding_box(&self) -> Rect

Geometric bounds; defaults to the path’s cached curve bounds.
Source§

fn as_rect(&self) -> Option<Rect>

Exact rectangle equivalent, when available, for a rule-independent fast path.
Source§

fn fill(self, paint: impl Into<Paint>) -> Styled<Self>
where Self: Sized,

Adds floating fill paint, using the nonzero rule by default.
Source§

fn stroke(self, width: f64, paint: impl Into<Paint>) -> Styled<Self>
where Self: Sized,

Adds a bounded curve/path stroke without an implicit fill.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.