repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/vector-types/src/vector/algorithms/bezpath_algorithms.rs | node-graph/libraries/vector-types/src/vector/algorithms/bezpath_algorithms.rs | use super::intersection::bezpath_intersections;
use super::poisson_disk::poisson_disk_sample;
use super::util::pathseg_tangent;
use crate::vector::algorithms::offset_subpath::MAX_ABSOLUTE_DIFFERENCE;
use crate::vector::misc::{PointSpacingType, dvec2_to_point, point_to_dvec2};
use core_types::math::polynomial::pathseg_to_parametric_polynomial;
use glam::{DMat2, DVec2};
use kurbo::common::{solve_cubic, solve_quadratic};
use kurbo::{BezPath, CubicBez, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Point, QuadBez, Rect, Shape, Vec2};
use std::f64::consts::{FRAC_PI_2, PI};
/// Splits the [`BezPath`] at segment index at `t` value which lie in the range of [0, 1].
/// Returns [`None`] if the given [`BezPath`] has no segments or `t` is within f64::EPSILON of 0 or 1.
pub fn split_bezpath_at_segment(bezpath: &BezPath, segment_index: usize, t: f64) -> Option<(BezPath, BezPath)> {
if t <= f64::EPSILON || (1. - t) <= f64::EPSILON || bezpath.segments().count() == 0 {
return None;
}
// Get the segment which lies at the split.
let segment = bezpath.get_seg(segment_index + 1).unwrap();
// Divide the segment.
let first_segment = segment.subsegment(0.0..t);
let second_segment = segment.subsegment(t..1.);
let mut first_bezpath = BezPath::new();
let mut second_bezpath = BezPath::new();
// Append the segments up to the subdividing segment from original bezpath to first bezpath.
for segment in bezpath.segments().take(segment_index) {
if first_bezpath.elements().is_empty() {
first_bezpath.move_to(segment.start());
}
first_bezpath.push(segment.as_path_el());
}
// Append the first segment of the subdivided segment.
if first_bezpath.elements().is_empty() {
first_bezpath.move_to(first_segment.start());
}
first_bezpath.push(first_segment.as_path_el());
// Append the second segment of the subdivided segment in the second bezpath.
if second_bezpath.elements().is_empty() {
second_bezpath.move_to(second_segment.start());
}
second_bezpath.push(second_segment.as_path_el());
// Append the segments after the subdividing segment from original bezpath to second bezpath.
for segment in bezpath.segments().skip(segment_index + 1) {
if second_bezpath.elements().is_empty() {
second_bezpath.move_to(segment.start());
}
second_bezpath.push(segment.as_path_el());
}
Some((first_bezpath, second_bezpath))
}
/// Splits the [`BezPath`] at a `t` value which lies in the range of [0, 1].
/// Returns [`None`] if the given [`BezPath`] has no segments.
pub fn split_bezpath(bezpath: &BezPath, t_value: TValue) -> Option<(BezPath, BezPath)> {
if bezpath.segments().count() == 0 {
return None;
}
// Get the segment which lies at the split.
let (segment_index, t) = eval_bezpath(bezpath, t_value, None);
split_bezpath_at_segment(bezpath, segment_index, t)
}
pub fn evaluate_bezpath(bezpath: &BezPath, t_value: TValue, segments_length: Option<&[f64]>) -> Point {
let (segment_index, t) = eval_bezpath(bezpath, t_value, segments_length);
bezpath.get_seg(segment_index + 1).unwrap().eval(t)
}
pub fn tangent_on_bezpath(bezpath: &BezPath, t_value: TValue, segments_length: Option<&[f64]>) -> Point {
let (segment_index, t) = eval_bezpath(bezpath, t_value, segments_length);
let segment = bezpath.get_seg(segment_index + 1).unwrap();
match segment {
PathSeg::Line(line) => line.deriv().eval(t),
PathSeg::Quad(quad_bez) => quad_bez.deriv().eval(t),
PathSeg::Cubic(cubic_bez) => cubic_bez.deriv().eval(t),
}
}
pub fn sample_polyline_on_bezpath(
bezpath: BezPath,
point_spacing_type: PointSpacingType,
amount: f64,
start_offset: f64,
stop_offset: f64,
adaptive_spacing: bool,
segments_length: &[f64],
) -> Option<BezPath> {
let mut sample_bezpath = BezPath::new();
let was_closed = matches!(bezpath.elements().last(), Some(PathEl::ClosePath));
// Calculate the total length of the collected segments.
let total_length: f64 = segments_length.iter().sum();
// Adjust the usable length by subtracting start and stop offsets.
let mut used_length = total_length - start_offset - stop_offset;
// Sanity check that the usable length is positive.
if used_length <= 0. {
return None;
}
const SAFETY_MAX_COUNT: f64 = 10_000. - 1.;
// Determine the number of points to generate along the path.
let sample_count = match point_spacing_type {
PointSpacingType::Separation => {
let spacing = amount.min(used_length - f64::EPSILON);
if adaptive_spacing {
// Calculate point count to evenly distribute points while covering the entire path.
// With adaptive spacing, we widen or narrow the points as necessary to ensure the last point is always at the end of the path.
(used_length / spacing).round().min(SAFETY_MAX_COUNT)
} else {
// Calculate point count based on exact spacing, which may not cover the entire path.
// Without adaptive spacing, we just evenly space the points at the exact specified spacing, usually falling short before the end of the path.
let count = (used_length / spacing + f64::EPSILON).floor().min(SAFETY_MAX_COUNT);
if count != SAFETY_MAX_COUNT {
used_length -= used_length % spacing;
}
count
}
}
PointSpacingType::Quantity => (amount - 1.).floor().clamp(1., SAFETY_MAX_COUNT),
};
// Skip if there are no points to generate.
if sample_count < 1. {
return None;
}
// Decide how many loop-iterations: if closed, skip the last duplicate point
let sample_count_usize = sample_count as usize;
let max_i = if was_closed { sample_count_usize } else { sample_count_usize + 1 };
// Generate points along the path based on calculated intervals.
let mut length_up_to_previous_segment = 0.;
let mut next_segment_index = 0;
for count in 0..max_i {
let fraction = count as f64 / sample_count;
let length_up_to_next_sample_point = fraction * used_length + start_offset;
let mut next_length = length_up_to_next_sample_point - length_up_to_previous_segment;
let mut next_segment_length = segments_length[next_segment_index];
// Keep moving to the next segment while the length up to the next sample point is greater than the length up to the current segment.
while next_length > next_segment_length {
if next_segment_index == segments_length.len() - 1 {
break;
}
length_up_to_previous_segment += next_segment_length;
next_length = length_up_to_next_sample_point - length_up_to_previous_segment;
next_segment_index += 1;
next_segment_length = segments_length[next_segment_index];
}
let t = (next_length / next_segment_length).clamp(0., 1.);
let segment = bezpath.get_seg(next_segment_index + 1).unwrap();
let t = eval_pathseg_euclidean(segment, t, DEFAULT_ACCURACY);
let point = segment.eval(t);
if sample_bezpath.elements().is_empty() {
sample_bezpath.move_to(point)
} else {
sample_bezpath.line_to(point)
}
}
if was_closed {
sample_bezpath.close_path();
}
Some(sample_bezpath)
}
#[derive(Debug, Clone, Copy)]
pub enum TValue {
Parametric(f64),
Euclidean(f64),
}
/// Default LUT step size in `compute_lookup_table` function.
pub const DEFAULT_LUT_STEP_SIZE: usize = 10;
/// Return a selection of equidistant points on the bezier curve.
/// If no value is provided for `steps`, then the function will default `steps` to be 10.
pub fn pathseg_compute_lookup_table(segment: PathSeg, steps: Option<usize>, eucliean: bool) -> impl Iterator<Item = DVec2> {
let steps = steps.unwrap_or(DEFAULT_LUT_STEP_SIZE);
(0..=steps).map(move |t| {
let tvalue = if eucliean {
TValue::Euclidean(t as f64 / steps as f64)
} else {
TValue::Parametric(t as f64 / steps as f64)
};
let t = eval_pathseg(segment, tvalue);
point_to_dvec2(segment.eval(t))
})
}
/// Returns an `Iterator` containing all possible parametric `t`-values at the given `x`-coordinate.
pub fn pathseg_find_tvalues_for_x(segment: PathSeg, x: f64) -> impl Iterator<Item = f64> + use<> {
match segment {
PathSeg::Line(Line { p0, p1 }) => {
// If the transformed linear bezier is on the x-axis, `a` and `b` will both be zero and `solve_linear` will return no roots
let a = p1.x - p0.x;
let b = p0.x - x;
// Find the roots of the linear equation `ax + b`.
// There exist roots when `a` is not 0
if a.abs() > MAX_ABSOLUTE_DIFFERENCE { [Some(-b / a), None, None] } else { [None; 3] }
}
PathSeg::Quad(QuadBez { p0, p1, p2 }) => {
let a = p2.x - 2.0 * p1.x + p0.x;
let b = 2.0 * (p1.x - p0.x);
let c = p0.x - x;
let r = solve_quadratic(c, b, a);
[r.first().copied(), r.get(1).copied(), None]
}
PathSeg::Cubic(CubicBez { p0, p1, p2, p3 }) => {
let a = p3.x - 3.0 * p2.x + 3.0 * p1.x - p0.x;
let b = 3.0 * (p2.x - 2.0 * p1.x + p0.x);
let c = 3.0 * (p1.x - p0.x);
let d = p0.x - x;
let r = solve_cubic(d, c, b, a);
[r.first().copied(), r.get(1).copied(), r.get(2).copied()]
}
}
.into_iter()
.flatten()
.filter(|&t| (0.0..1.).contains(&t))
}
/// Find the `t`-value(s) such that the normal(s) at `t` pass through the specified point.
pub fn pathseg_normals_to_point(segment: PathSeg, point: Point) -> Vec<f64> {
// We solve deriv(t) dot (self(t) - point) = 0.
let (mut x, mut y) = pathseg_to_parametric_polynomial(segment);
let x = x.coefficients_mut();
let y = y.coefficients_mut();
x[0] -= point.x;
y[0] -= point.y;
let poly = polycool::Poly::new([
x[0] * x[1] + y[0] * y[1],
x[1] * x[1] + y[1] * y[1] + 2. * (x[0] * x[2] + y[0] * y[2]),
3. * (x[2] * x[1] + y[2] * y[1]) + 3. * (x[0] * x[3] + y[0] * y[3]),
4. * (x[3] * x[1] + y[3] * y[1]) + 2. * (x[2] * x[2] + y[2] * y[2]),
5. * (x[3] * x[2] + y[3] * y[2]),
3. * (x[3] * x[3] + y[3] * y[3]),
]);
poly.roots_between(0., 1., 1e-8).to_vec()
}
/// Find the `t`-value(s) such that the tangent(s) at `t` pass through the given point.
pub fn pathseg_tangents_to_point(segment: PathSeg, point: Point) -> Vec<f64> {
segment.to_cubic().tangents_to_point(point).to_vec()
}
/// Return the subsegment for the given [TValue] range. Returns None if parametric value of `t1` is greater than `t2`.
pub fn trim_pathseg(segment: PathSeg, t1: TValue, t2: TValue) -> Option<PathSeg> {
let t1 = eval_pathseg(segment, t1);
let t2 = eval_pathseg(segment, t2);
if t1 > t2 { None } else { Some(segment.subsegment(t1..t2)) }
}
pub fn eval_pathseg(segment: PathSeg, t_value: TValue) -> f64 {
match t_value {
TValue::Parametric(t) => t,
TValue::Euclidean(t) => eval_pathseg_euclidean(segment, t, DEFAULT_ACCURACY),
}
}
/// Return an approximation of the length centroid, together with the length, of the bezier curve.
///
/// The length centroid is the center of mass for the arc length of the Bezier segment.
/// An infinitely thin wire forming the Bezier segment's shape would balance at this point.
///
/// - `accuracy` is used to approximate the curve.
pub(crate) fn pathseg_length_centroid_and_length(segment: PathSeg, accuracy: Option<f64>) -> (Vec2, f64) {
match segment {
PathSeg::Line(line) => ((line.start().to_vec2() + line.end().to_vec2()) / 2., (line.start().to_vec2() - line.end().to_vec2()).length()),
PathSeg::Quad(quad_bez) => {
let QuadBez { p0, p1, p2 } = quad_bez;
// Use Casteljau subdivision, noting that the length is more than the straight line distance from start to end but less than the straight line distance through the handles
fn recurse(a0: Vec2, a1: Vec2, a2: Vec2, accuracy: f64, level: u8) -> (f64, Vec2) {
let lower = (a2 - a1).length();
let upper = (a1 - a0).length() + (a2 - a1).length();
if upper - lower <= 2. * accuracy || level >= 8 {
let length = (lower + upper) / 2.;
return (length, length * (a0 + a1 + a2) / 3.);
}
let b1 = 0.5 * (a0 + a1);
let c1 = 0.5 * (a1 + a2);
let b2 = 0.5 * (b1 + c1);
let (length1, centroid_part1) = recurse(a0, b1, b2, 0.5 * accuracy, level + 1);
let (length2, centroid_part2) = recurse(b2, c1, a2, 0.5 * accuracy, level + 1);
(length1 + length2, centroid_part1 + centroid_part2)
}
let (length, centroid_parts) = recurse(p0.to_vec2(), p1.to_vec2(), p2.to_vec2(), accuracy.unwrap_or_default(), 0);
(centroid_parts / length, length)
}
PathSeg::Cubic(cubic_bez) => {
let CubicBez { p0, p1, p2, p3 } = cubic_bez;
// Use Casteljau subdivision, noting that the length is more than the straight line distance from start to end but less than the straight line distance through the handles
fn recurse(a0: Vec2, a1: Vec2, a2: Vec2, a3: Vec2, accuracy: f64, level: u8) -> (f64, Vec2) {
let lower = (a3 - a0).length();
let upper = (a1 - a0).length() + (a2 - a1).length() + (a3 - a2).length();
if upper - lower <= 2. * accuracy || level >= 8 {
let length = (lower + upper) / 2.;
return (length, length * (a0 + a1 + a2 + a3) / 4.);
}
let b1 = 0.5 * (a0 + a1);
let t0 = 0.5 * (a1 + a2);
let c1 = 0.5 * (a2 + a3);
let b2 = 0.5 * (b1 + t0);
let c2 = 0.5 * (t0 + c1);
let b3 = 0.5 * (b2 + c2);
let (length1, centroid_part1) = recurse(a0, b1, b2, b3, 0.5 * accuracy, level + 1);
let (length2, centroid_part2) = recurse(b3, c2, c1, a3, 0.5 * accuracy, level + 1);
(length1 + length2, centroid_part1 + centroid_part2)
}
let (length, centroid_parts) = recurse(p0.to_vec2(), p1.to_vec2(), p2.to_vec2(), p3.to_vec2(), accuracy.unwrap_or_default(), 0);
(centroid_parts / length, length)
}
}
}
/// Finds the t value of point on the given path segment i.e fractional distance along the segment's total length.
/// It uses a binary search to find the value `t` such that the ratio `length_up_to_t / total_length` approximates the input `distance`.
pub fn eval_pathseg_euclidean(segment: PathSeg, distance: f64, accuracy: f64) -> f64 {
let mut low_t = 0.;
let mut mid_t = 0.5;
let mut high_t = 1.;
let total_length = segment.perimeter(accuracy);
if !total_length.is_finite() || total_length <= f64::EPSILON {
return 0.;
}
let distance = distance.clamp(0., 1.);
while high_t - low_t > accuracy {
let current_length = segment.subsegment(0.0..mid_t).perimeter(accuracy);
let current_distance = current_length / total_length;
if current_distance > distance {
high_t = mid_t;
} else {
low_t = mid_t;
}
mid_t = (high_t + low_t) / 2.;
}
mid_t
}
/// Converts from a bezpath (composed of multiple segments) to a point along a certain segment represented.
/// The returned tuple represents the segment index and the `t` value along that segment.
/// Both the input global `t` value and the output `t` value are in euclidean space, meaning there is a constant rate of change along the arc length.
fn eval_bazpath_to_euclidean(bezpath: &BezPath, global_t: f64, lengths: &[f64], total_length: f64) -> (usize, f64) {
let mut accumulator = 0.;
for (index, length) in lengths.iter().enumerate() {
let length_ratio = length / total_length;
if (index == 0 || accumulator <= global_t) && global_t <= accumulator + length_ratio {
return (index, ((global_t - accumulator) / length_ratio).clamp(0., 1.));
}
accumulator += length_ratio;
}
(bezpath.segments().count() - 1, 1.)
}
/// Convert a [TValue] to a parametric `(segment_index, t)` tuple.
/// - Asserts that `t` values contained within the `TValue` argument lie in the range [0, 1].
fn eval_bezpath(bezpath: &BezPath, t: TValue, precomputed_segments_length: Option<&[f64]>) -> (usize, f64) {
let segment_count = bezpath.segments().count();
assert!(segment_count >= 1);
match t {
TValue::Euclidean(t) => {
let computed_segments_length;
let segments_length = if let Some(segments_length) = precomputed_segments_length {
segments_length
} else {
computed_segments_length = bezpath.segments().map(|segment| segment.perimeter(DEFAULT_ACCURACY)).collect::<Vec<f64>>();
computed_segments_length.as_slice()
};
let total_length = segments_length.iter().sum();
let (segment_index, t) = eval_bazpath_to_euclidean(bezpath, t, segments_length, total_length);
let segment = bezpath.get_seg(segment_index + 1).unwrap();
(segment_index, eval_pathseg_euclidean(segment, t, DEFAULT_ACCURACY))
}
TValue::Parametric(t) => {
assert!((0.0..=1.).contains(&t));
if t == 1. {
return (segment_count - 1, 1.);
}
let scaled_t = t * segment_count as f64;
let segment_index = scaled_t.floor() as usize;
let t = scaled_t - segment_index as f64;
(segment_index, t)
}
}
}
/// Randomly places points across the filled surface of this subpath (which is assumed to be closed).
/// The `separation_disk_diameter` determines the minimum distance between all points from one another.
/// Conceptually, this works by "throwing a dart" at the subpath's bounding box and keeping the dart only if:
/// - It's inside the shape
/// - It's not closer than `separation_disk_diameter` to any other point from a previous accepted dart throw
///
/// This repeats until accepted darts fill all possible areas between one another.
///
/// While the conceptual process described above asymptotically slows down and is never guaranteed to produce a maximal set in finite time,
/// this is implemented with an algorithm that produces a maximal set in O(n) time. The slowest part is actually checking if points are inside the subpath shape.
pub fn poisson_disk_points(bezpath_index: usize, bezpaths: &[(BezPath, Rect)], separation_disk_diameter: f64, rng: impl FnMut() -> f64) -> Vec<DVec2> {
let (this_bezpath, this_bbox) = bezpaths[bezpath_index].clone();
if this_bezpath.elements().is_empty() {
return Vec::new();
}
let point_in_shape_checker = |point: DVec2| {
// Check against all paths the point is contained in to compute the correct winding number
let mut number = 0;
for (i, (shape, bbox)) in bezpaths.iter().enumerate() {
if bbox.x0 > point.x || bbox.y0 > point.y || bbox.x1 < point.x || bbox.y1 < point.y {
continue;
}
let winding = shape.winding(dvec2_to_point(point));
if winding == 0 && i == bezpath_index {
return false;
}
number += winding;
}
// Non-zero fill rule
number != 0
};
let line_intersect_shape_checker = |p0: (f64, f64), p1: (f64, f64)| {
for segment in this_bezpath.segments() {
if !segment.intersect_line(Line::new(p0, p1)).is_empty() {
return true;
}
}
false
};
let offset = DVec2::new(this_bbox.x0, this_bbox.y0);
let width = this_bbox.width();
let height = this_bbox.height();
poisson_disk_sample(offset, width, height, separation_disk_diameter, point_in_shape_checker, line_intersect_shape_checker, rng)
}
/// Returns true if the Bezier curve is equivalent to a line.
///
/// **NOTE**: This is different from simply checking if the segment is [`PathSeg::Line`] or [`PathSeg::Quad`] or [`PathSeg::Cubic`]. Bezier curve can also be a line if the control points are colinear to the start and end points. Therefore if the handles exceed the start and end point, it will still be considered as a line.
pub fn is_linear(segment: &PathSeg) -> bool {
let is_colinear = |a: Point, b: Point, c: Point| -> bool { ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)).abs() < MAX_ABSOLUTE_DIFFERENCE };
match *segment {
PathSeg::Line(_) => true,
PathSeg::Quad(QuadBez { p0, p1, p2 }) => is_colinear(p0, p1, p2),
PathSeg::Cubic(CubicBez { p0, p1, p2, p3 }) => is_colinear(p0, p1, p3) && is_colinear(p0, p2, p3),
}
}
// TODO: If a segment curls back on itself tightly enough it could intersect again at the portion that should be trimmed. This could cause the Subpaths to be clipped
// TODO: at the incorrect location. This can be avoided by first trimming the two Subpaths at any extrema, effectively ignoring loopbacks.
/// Helper function to clip overlap of two intersecting open BezPaths. Returns an Option because intersections may not exist for certain arrangements and distances.
/// Assumes that the BezPaths represents simple Bezier segments, and clips the BezPaths at the last intersection of the first BezPath, and first intersection of the last BezPath.
pub fn clip_simple_bezpaths(bezpath1: &BezPath, bezpath2: &BezPath) -> Option<(BezPath, BezPath)> {
// Split the first subpath at its last intersection
let subpath_1_intersections = bezpath_intersections(bezpath1, bezpath2, None, None);
if subpath_1_intersections.is_empty() {
return None;
}
let (segment_index, t) = *subpath_1_intersections.last()?;
let (clipped_subpath1, _) = split_bezpath_at_segment(bezpath1, segment_index, t)?;
// Split the second subpath at its first intersection
let subpath_2_intersections = bezpath_intersections(bezpath2, bezpath1, None, None);
if subpath_2_intersections.is_empty() {
return None;
}
let (segment_index, t) = subpath_2_intersections[0];
let (_, clipped_subpath2) = split_bezpath_at_segment(bezpath2, segment_index, t)?;
Some((clipped_subpath1, clipped_subpath2))
}
/// Returns the [`PathEl`] that is needed for a miter join if it is possible.
///
/// `miter_limit` defines a limit for the ratio between the miter length and the stroke width.
/// Alternatively, this can be interpreted as limiting the angle that the miter can form.
/// When the limit is exceeded, no [`PathEl`] will be returned.
/// This value should be greater than 0. If not, the default of 4 will be used.
pub fn miter_line_join(bezpath1: &BezPath, bezpath2: &BezPath, miter_limit: Option<f64>) -> Option<[PathEl; 2]> {
let miter_limit = match miter_limit {
Some(miter_limit) if miter_limit > f64::EPSILON => miter_limit,
_ => 4.,
};
// TODO: Besides returning None using the `?` operator, is there a more appropriate way to handle a `None` result from `get_segment`?
let in_segment = bezpath1.segments().last()?;
let out_segment = bezpath2.segments().next()?;
let in_tangent = pathseg_tangent(in_segment, 1.);
let out_tangent = pathseg_tangent(out_segment, 0.);
if in_tangent == DVec2::ZERO || out_tangent == DVec2::ZERO {
// Avoid panic from normalizing zero vectors
// TODO: Besides returning None, is there a more appropriate way to handle this?
return None;
}
let angle = (in_tangent * -1.).angle_to(out_tangent).abs();
if angle.to_degrees() < miter_limit {
return None;
}
let p1 = in_segment.end();
let p2 = point_to_dvec2(p1) + in_tangent.normalize();
let line1 = Line::new(p1, dvec2_to_point(p2));
let p1 = out_segment.start();
let p2 = point_to_dvec2(p1) + out_tangent.normalize();
let line2 = Line::new(p1, dvec2_to_point(p2));
// If we don't find the intersection point to draw the miter join, we instead default to a bevel join.
// Otherwise, we return the element to create the join.
let intersection = line1.crossing_point(line2)?;
Some([PathEl::LineTo(intersection), PathEl::LineTo(out_segment.start())])
}
/// Computes the [`PathEl`] to form a circular join from `left` to `right`, along a circle around `center`.
/// By default, the angle is assumed to be 180 degrees.
pub fn compute_circular_subpath_details(left: DVec2, arc_point: DVec2, right: DVec2, center: DVec2, angle: Option<f64>) -> [PathEl; 2] {
let center_to_arc_point = arc_point - center;
// Based on https://pomax.github.io/bezierinfo/#circles_cubic
let handle_offset_factor = if let Some(angle) = angle { 4. / 3. * (angle / 4.).tan() } else { 0.551784777779014 };
let p1 = dvec2_to_point(left - (left - center).perp() * handle_offset_factor);
let p2 = dvec2_to_point(arc_point + center_to_arc_point.perp() * handle_offset_factor);
let p3 = dvec2_to_point(arc_point);
let first_half = PathEl::CurveTo(p1, p2, p3);
let p1 = dvec2_to_point(arc_point - center_to_arc_point.perp() * handle_offset_factor);
let p2 = dvec2_to_point(right + (right - center).perp() * handle_offset_factor);
let p3 = dvec2_to_point(right);
let second_half = PathEl::CurveTo(p1, p2, p3);
[first_half, second_half]
}
/// Returns two [`PathEl`] to create a round join with the provided center.
pub fn round_line_join(bezpath1: &BezPath, bezpath2: &BezPath, center: DVec2) -> [PathEl; 2] {
let left = point_to_dvec2(bezpath1.segments().last().unwrap().end());
let right = point_to_dvec2(bezpath2.segments().next().unwrap().start());
let center_to_right = right - center;
let center_to_left = left - center;
let in_segment = bezpath1.segments().last();
let in_tangent = in_segment.map(|in_segment| pathseg_tangent(in_segment, 1.));
let mut angle = center_to_right.angle_to(center_to_left) / 2.;
let mut arc_point = center + DMat2::from_angle(angle).mul_vec2(center_to_right);
if in_tangent.map(|in_tangent| (arc_point - left).angle_to(in_tangent).abs()).unwrap_or_default() > FRAC_PI_2 {
angle = angle - PI * (if angle < 0. { -1. } else { 1. });
arc_point = center + DMat2::from_angle(angle).mul_vec2(center_to_right);
}
compute_circular_subpath_details(left, arc_point, right, center, Some(angle))
}
/// Returns `true` if the `bezpath1` is completely inside the `bezpath2`.
/// NOTE: `bezpath2` must be a closed path to get correct results.
pub fn bezpath_is_inside_bezpath(bezpath1: &BezPath, bezpath2: &BezPath, accuracy: Option<f64>, minimum_separation: Option<f64>) -> bool {
// Eliminate any possibility of one being inside the other, if either of them are empty
if bezpath1.is_empty() || bezpath2.is_empty() {
return false;
}
let inner_bbox = bezpath1.bounding_box();
let outer_bbox = bezpath2.bounding_box();
// Eliminate bezpath1 if its bounding box is not completely inside the bezpath2's bounding box.
// Reasoning:
// If the inner bezpath bounding box is larger than the outer bezpath bounding box in any direction
// then the inner bezpath is intersecting with or outside the outer bezpath.
if !outer_bbox.contains_rect(inner_bbox) && outer_bbox.intersect(inner_bbox).is_zero_area() {
return false;
}
// Eliminate bezpath1 if any of its anchor points are outside the bezpath2.
if !bezpath1.elements().iter().filter_map(|el| el.end_point()).all(|point| bezpath2.contains(point)) {
return false;
}
// Eliminate this subpath if it intersects with the other subpath.
if !bezpath_intersections(bezpath1, bezpath2, accuracy, minimum_separation).is_empty() {
return false;
}
// At this point:
// (1) This subpath's bounding box is inside the other subpath's bounding box,
// (2) Its anchors are inside the other subpath, and
// (3) It is not intersecting with the other subpath.
// Hence, this subpath is completely inside the given other subpath.
true
}
#[cfg(test)]
mod tests {
// TODO: add more intersection tests
use super::bezpath_is_inside_bezpath;
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, Point, Rect, Shape};
#[test]
fn is_inside_subpath() {
let boundary_polygon = Rect::new(100., 100., 500., 500.).to_path(DEFAULT_ACCURACY);
let mut curve_intersection = BezPath::new();
curve_intersection.move_to(Point::new(189., 289.));
curve_intersection.quad_to(Point::new(9., 286.), Point::new(45., 410.));
assert!(!bezpath_is_inside_bezpath(&curve_intersection, &boundary_polygon, None, None));
let mut curve_outside = BezPath::new();
curve_outside.move_to(Point::new(115., 37.));
curve_outside.quad_to(Point::new(51.4, 91.8), Point::new(76.5, 242.));
assert!(!bezpath_is_inside_bezpath(&curve_outside, &boundary_polygon, None, None));
let mut curve_inside = BezPath::new();
curve_inside.move_to(Point::new(210.1, 133.5));
curve_inside.curve_to(Point::new(150.2, 436.9), Point::new(436., 285.), Point::new(247.6, 240.7));
assert!(bezpath_is_inside_bezpath(&curve_inside, &boundary_polygon, None, None));
let line_inside = Line::new(Point::new(101., 101.5), Point::new(150.2, 499.)).to_path(DEFAULT_ACCURACY);
assert!(bezpath_is_inside_bezpath(&line_inside, &boundary_polygon, None, None));
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/vector-types/src/vector/algorithms/merge_by_distance.rs | node-graph/libraries/vector-types/src/vector/algorithms/merge_by_distance.rs | use crate::vector::{PointDomain, PointId, SegmentDomain, SegmentId, Vector};
use glam::{DAffine2, DVec2};
use petgraph::graph::{EdgeIndex, NodeIndex, UnGraph};
use petgraph::prelude::UnGraphMap;
use rustc_hash::FxHashMap;
use rustc_hash::FxHashSet;
pub trait MergeByDistanceExt {
/// Collapse all points with edges shorter than the specified distance
fn merge_by_distance_topological(&mut self, distance: f64);
fn merge_by_distance_spatial(&mut self, transform: DAffine2, distance: f64);
}
impl<Upstream: 'static> MergeByDistanceExt for Vector<Upstream> {
fn merge_by_distance_topological(&mut self, distance: f64) {
// Treat self as an undirected graph
let indices = VectorIndex::build_from(self);
// TODO: We lose information on the winding order by using an undirected graph. Switch to a directed graph and fix the algorithm to handle that.
// Graph containing only short edges, referencing the data graph
let mut short_edges = UnGraphMap::new();
for segment_id in self.segment_ids().iter().copied() {
let length = indices.segment_chord_length(segment_id);
if length < distance {
let [start, end] = indices.segment_ends(segment_id);
let start = indices.point_graph.node_weight(start).unwrap().id;
let end = indices.point_graph.node_weight(end).unwrap().id;
short_edges.add_node(start);
short_edges.add_node(end);
short_edges.add_edge(start, end, segment_id);
}
}
// Group connected segments to collapse them into a single point
// TODO: there are a few possible algorithms for this - perhaps test empirically to find fastest
let collapse: Vec<FxHashSet<PointId>> = petgraph::algo::tarjan_scc(&short_edges).into_iter().map(|connected| connected.into_iter().collect()).collect();
let average_position = collapse
.iter()
.map(|collapse_set| {
let sum: DVec2 = collapse_set.iter().map(|&id| indices.point_position(id, self)).sum();
sum / collapse_set.len() as f64
})
.collect::<Vec<_>>();
// Collect points and segments to delete at the end to avoid invalidating indices
let mut points_to_delete = FxHashSet::default();
let mut segments_to_delete = FxHashSet::default();
for (mut collapse_set, average_pos) in collapse.into_iter().zip(average_position.into_iter()) {
// Remove any segments where both endpoints are in the collapse set
segments_to_delete.extend(self.segment_domain.iter().filter_map(|(id, start_offset, end_offset, _)| {
let start = self.point_domain.ids()[start_offset];
let end = self.point_domain.ids()[end_offset];
if collapse_set.contains(&start) && collapse_set.contains(&end) { Some(id) } else { None }
}));
// Delete all points but the first, set its position to the average, and update segments
let first_id = collapse_set.iter().copied().next().unwrap();
collapse_set.remove(&first_id);
let first_offset = indices.point_to_offset[&first_id];
// Look for segments with endpoints in `collapse_set` and replace them with the point we are collapsing to
for (_, start_offset, end_offset, handles) in self.segment_domain.iter_mut() {
let start_id = self.point_domain.ids()[*start_offset];
let end_id = self.point_domain.ids()[*end_offset];
// Update Bezier handles for moved points
if start_id == first_id {
let point_position = self.point_domain.position[*start_offset];
handles.move_start(average_pos - point_position);
}
if end_id == first_id {
let point_position = self.point_domain.position[*end_offset];
handles.move_end(average_pos - point_position);
}
// Replace removed points with the collapsed point
if collapse_set.contains(&start_id) {
let point_position = self.point_domain.position[*start_offset];
*start_offset = first_offset;
handles.move_start(average_pos - point_position);
}
if collapse_set.contains(&end_id) {
let point_position = self.point_domain.position[*end_offset];
*end_offset = first_offset;
handles.move_end(average_pos - point_position);
}
}
// Update the position of the collapsed point
self.point_domain.position[first_offset] = average_pos;
points_to_delete.extend(collapse_set)
}
// Remove faces whose start or end segments are removed
// TODO: Adjust faces and only delete if all (or all but one) segments are removed
self.region_domain
.retain_with_region(|_, segment_range| segments_to_delete.contains(segment_range.start()) || segments_to_delete.contains(segment_range.end()));
self.segment_domain.retain(|id| !segments_to_delete.contains(id), usize::MAX);
self.point_domain.retain(&mut self.segment_domain, |id| !points_to_delete.contains(id));
}
fn merge_by_distance_spatial(&mut self, transform: DAffine2, distance: f64) {
let point_count = self.point_domain.positions().len();
// Find min x and y for grid cell normalization
let mut min_x = f64::MAX;
let mut min_y = f64::MAX;
// Calculate mins without collecting all positions
for &pos in self.point_domain.positions() {
let transformed_pos = transform.transform_point2(pos);
min_x = min_x.min(transformed_pos.x);
min_y = min_y.min(transformed_pos.y);
}
// Create a spatial grid with cell size of 'distance'
use std::collections::HashMap;
let mut grid: HashMap<(i32, i32), Vec<usize>> = HashMap::new();
// Add points to grid cells without collecting all positions first
for i in 0..point_count {
let pos = transform.transform_point2(self.point_domain.positions()[i]);
let grid_x = ((pos.x - min_x) / distance).floor() as i32;
let grid_y = ((pos.y - min_y) / distance).floor() as i32;
grid.entry((grid_x, grid_y)).or_default().push(i);
}
// Create point index mapping for merged points
let mut point_index_map = vec![None; point_count];
let mut merged_positions = Vec::new();
let mut merged_indices = Vec::new();
// Process each point
for i in 0..point_count {
// Skip points that have already been processed
if point_index_map[i].is_some() {
continue;
}
let pos_i = transform.transform_point2(self.point_domain.positions()[i]);
let grid_x = ((pos_i.x - min_x) / distance).floor() as i32;
let grid_y = ((pos_i.y - min_y) / distance).floor() as i32;
let mut group = vec![i];
// Check only neighboring cells (3x3 grid around current cell)
for dx in -1..=1 {
for dy in -1..=1 {
let neighbor_cell = (grid_x + dx, grid_y + dy);
if let Some(indices) = grid.get(&neighbor_cell) {
for &j in indices {
if j > i && point_index_map[j].is_none() {
let pos_j = transform.transform_point2(self.point_domain.positions()[j]);
if pos_i.distance(pos_j) <= distance {
group.push(j);
}
}
}
}
}
}
// Create merged point - calculate positions as needed
let merged_position = group
.iter()
.map(|&idx| transform.transform_point2(self.point_domain.positions()[idx]))
.fold(DVec2::ZERO, |sum, pos| sum + pos)
/ group.len() as f64;
let merged_position = transform.inverse().transform_point2(merged_position);
let merged_index = merged_positions.len();
merged_positions.push(merged_position);
merged_indices.push(self.point_domain.ids()[group[0]]);
// Update mapping for all points in the group
for &idx in &group {
point_index_map[idx] = Some(merged_index);
}
}
// Create new point domain with merged points
let mut new_point_domain = PointDomain::new();
for (idx, pos) in merged_indices.into_iter().zip(merged_positions) {
new_point_domain.push(idx, pos);
}
// Update segment domain
let mut new_segment_domain = SegmentDomain::new();
for segment_idx in 0..self.segment_domain.ids().len() {
let id = self.segment_domain.ids()[segment_idx];
let start = self.segment_domain.start_point()[segment_idx];
let end = self.segment_domain.end_point()[segment_idx];
let handles = self.segment_domain.handles()[segment_idx];
let stroke = self.segment_domain.stroke()[segment_idx];
// Get new indices for start and end points
let new_start = point_index_map[start].unwrap();
let new_end = point_index_map[end].unwrap();
// Skip segments where start and end points were merged
if new_start != new_end {
new_segment_domain.push(id, new_start, new_end, handles, stroke);
}
}
// Create new vector geometry
self.point_domain = new_point_domain;
self.segment_domain = new_segment_domain;
}
}
/// All the fixed fields of a point from the point domain.
pub(crate) struct Point {
pub id: PointId,
pub position: DVec2,
}
/// Useful indexes to speed up various operations on [`Vector`].
///
/// Important: It is the user's responsibility to ensure the indexes remain valid after mutations to the data.
pub struct VectorIndex {
/// Points and segments form a graph. Store it here in a form amenable to graph algorithms.
///
/// Currently, segment data is not stored as it is not used, but it could easily be added.
pub(crate) point_graph: UnGraph<Point, ()>,
pub(crate) segment_to_edge: FxHashMap<SegmentId, EdgeIndex>,
/// Get the offset from the point ID.
pub(crate) point_to_offset: FxHashMap<PointId, usize>,
// TODO: faces
}
impl VectorIndex {
/// Construct a [`VectorIndex`] by building indexes from the given [`Vector`]. Takes `O(n)` time.
pub fn build_from<Upstream: 'static>(data: &Vector<Upstream>) -> Self {
let point_to_offset = data.point_domain.ids().iter().copied().enumerate().map(|(a, b)| (b, a)).collect::<FxHashMap<_, _>>();
let mut point_to_node = FxHashMap::default();
let mut segment_to_edge = FxHashMap::default();
let mut graph = UnGraph::new_undirected();
for (point_id, position) in data.point_domain.iter() {
let idx = graph.add_node(Point { id: point_id, position });
point_to_node.insert(point_id, idx);
}
for (segment_id, start_offset, end_offset, ..) in data.segment_domain.iter() {
let start_id = data.point_domain.ids()[start_offset];
let end_id = data.point_domain.ids()[end_offset];
let edge = graph.add_edge(point_to_node[&start_id], point_to_node[&end_id], ());
segment_to_edge.insert(segment_id, edge);
}
Self {
point_graph: graph,
segment_to_edge,
point_to_offset,
}
}
/// Fetch the length of given segment's chord. Takes `O(1)` time.
///
/// # Panics
///
/// Will panic if no segment with the given ID is found.
pub fn segment_chord_length(&self, id: SegmentId) -> f64 {
let edge_idx = self.segment_to_edge[&id];
let (start, end) = self.point_graph.edge_endpoints(edge_idx).unwrap();
let start_position = self.point_graph.node_weight(start).unwrap().position;
let end_position = self.point_graph.node_weight(end).unwrap().position;
(start_position - end_position).length()
}
/// Get the ends of a segment. Takes `O(1)` time.
///
/// The IDs will be ordered [smallest, largest] so they can be used to find other segments with the same endpoints, regardless of direction.
///
/// # Panics
///
/// This function will panic if the ID is not present.
pub fn segment_ends(&self, id: SegmentId) -> [NodeIndex; 2] {
let (start, end) = self.point_graph.edge_endpoints(self.segment_to_edge[&id]).unwrap();
if start < end { [start, end] } else { [end, start] }
}
/// Get the physical location of a point. Takes `O(1)` time.
///
/// # Panics
///
/// Will panic if `id` isn't in the data.
pub fn point_position<Upstream: 'static>(&self, id: PointId, data: &Vector<Upstream>) -> DVec2 {
let offset = self.point_to_offset[&id];
data.point_domain.positions()[offset]
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/raster-types/src/lib.rs | node-graph/libraries/raster-types/src/lib.rs | pub mod image;
pub mod raster_types;
// Re-exports for convenience
pub use image::Image;
pub use raster_types::*;
// Re-export color types from no-std-types
pub use core_types::color::*;
/// as to not yet rename all references
pub mod color {
pub use super::*;
}
use std::fmt::Debug;
pub trait Bitmap {
type Pixel: Pixel;
fn width(&self) -> u32;
fn height(&self) -> u32;
fn dimensions(&self) -> (u32, u32) {
(self.width(), self.height())
}
fn dim(&self) -> (u32, u32) {
self.dimensions()
}
fn get_pixel(&self, x: u32, y: u32) -> Option<Self::Pixel>;
}
impl<T: Bitmap> Bitmap for &T {
type Pixel = T::Pixel;
fn width(&self) -> u32 {
(**self).width()
}
fn height(&self) -> u32 {
(**self).height()
}
fn get_pixel(&self, x: u32, y: u32) -> Option<Self::Pixel> {
(**self).get_pixel(x, y)
}
}
impl<T: Bitmap> Bitmap for &mut T {
type Pixel = T::Pixel;
fn width(&self) -> u32 {
(**self).width()
}
fn height(&self) -> u32 {
(**self).height()
}
fn get_pixel(&self, x: u32, y: u32) -> Option<Self::Pixel> {
(**self).get_pixel(x, y)
}
}
pub trait BitmapMut: Bitmap {
fn get_pixel_mut(&mut self, x: u32, y: u32) -> Option<&mut Self::Pixel>;
fn set_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
*self.get_pixel_mut(x, y).unwrap() = pixel;
}
fn map_pixels<F: Fn(Self::Pixel) -> Self::Pixel>(&mut self, map_fn: F) {
for y in 0..self.height() {
for x in 0..self.width() {
let pixel = self.get_pixel(x, y).unwrap();
self.set_pixel(x, y, map_fn(pixel));
}
}
}
}
impl<T: BitmapMut + Bitmap> BitmapMut for &mut T {
fn get_pixel_mut(&mut self, x: u32, y: u32) -> Option<&mut Self::Pixel> {
(*self).get_pixel_mut(x, y)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/raster-types/src/image.rs | node-graph/libraries/raster-types/src/image.rs | use crate::raster_types::{CPU, Raster};
use crate::{Bitmap, BitmapMut};
use core_types::AlphaBlending;
use core_types::Color;
use core_types::color::float_to_srgb_u8;
use core_types::table::{Table, TableRow};
// use crate::vector::Vector; // TODO: Check if Vector is actually used, if so handle differently
use core::hash::{Hash, Hasher};
use core_types::color::*;
use dyn_any::{DynAny, StaticType};
use glam::{DAffine2, DVec2};
use std::vec::Vec;
mod base64_serde {
//! Basic wrapper for [`serde`] to perform [`base64`] encoding
use base64::Engine;
use core_types::color::*;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn as_base64<S: Serializer, P: Pixel>(key: &[P], serializer: S) -> Result<S::Ok, S::Error> {
let u8_data = bytemuck::cast_slice(key);
let string = base64::engine::general_purpose::STANDARD.encode(u8_data);
(key.len() as u64, string).serialize(serializer)
}
pub fn from_base64<'a, D: Deserializer<'a>, P: Pixel>(deserializer: D) -> Result<Vec<P>, D::Error> {
use serde::de::Error;
<(u64, &[u8])>::deserialize(deserializer)
.and_then(|(len, str)| {
let mut output: Vec<P> = vec![P::zeroed(); len as usize];
base64::engine::general_purpose::STANDARD
.decode_slice(str, bytemuck::cast_slice_mut(output.as_mut_slice()))
.map_err(|err| Error::custom(err.to_string()))?;
Ok(output)
})
.map_err(serde::de::Error::custom)
}
}
#[derive(Clone, Eq, Default, specta::Type, serde::Serialize, serde::Deserialize)]
pub struct Image<P: Pixel> {
pub width: u32,
pub height: u32,
#[serde(serialize_with = "base64_serde::as_base64", deserialize_with = "base64_serde::from_base64")]
pub data: Vec<P>,
/// Optional: Stores a base64 string representation of the image which can be used to speed up the conversion
/// to an svg string. This is used as a cache in order to not have to encode the data on every graph evaluation.
#[serde(skip)]
pub base64_string: Option<String>,
// TODO: Add an `origin` field to store where in the local space the image is anchored.
// TODO: Currently it is always anchored at the top left corner at (0, 0). The bottom right corner of the new origin field would correspond to (1, 1).
}
impl<P: Pixel + PartialEq> PartialEq for Image<P> {
fn eq(&self, other: &Self) -> bool {
self.width == other.width && self.height == other.height && self.data == other.data
}
}
#[derive(Debug, Clone, dyn_any::DynAny, Default, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct TransformImage(pub DAffine2);
impl Hash for TransformImage {
fn hash<H: std::hash::Hasher>(&self, _: &mut H) {}
}
impl<P: Pixel + std::fmt::Debug> std::fmt::Debug for Image<P> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let length = self.data.len();
f.debug_struct("Image")
.field("width", &self.width)
.field("height", &self.height)
.field("data", if length < 100 { &self.data } else { &length })
.finish()
}
}
unsafe impl<P> StaticType for Image<P>
where
P: dyn_any::StaticTypeSized + Pixel,
P::Static: Pixel,
{
type Static = Image<P::Static>;
}
impl<P: Copy + Pixel> Bitmap for Image<P> {
type Pixel = P;
#[inline(always)]
fn get_pixel(&self, x: u32, y: u32) -> Option<P> {
self.data.get((x + y * self.width) as usize).copied()
}
#[inline(always)]
fn width(&self) -> u32 {
self.width
}
#[inline(always)]
fn height(&self) -> u32 {
self.height
}
}
impl<P: Copy + Pixel> BitmapMut for Image<P> {
fn get_pixel_mut(&mut self, x: u32, y: u32) -> Option<&mut P> {
self.data.get_mut((x + y * self.width) as usize)
}
}
// TODO: Evaluate if this will be a problem for our use case.
/// Warning: This is an approximation of a hash, and is not guaranteed to not collide.
impl<P: Hash + Pixel> Hash for Image<P> {
fn hash<H: Hasher>(&self, state: &mut H) {
const HASH_SAMPLES: u64 = 1000;
let data_length = self.data.len() as u64;
self.width.hash(state);
self.height.hash(state);
for i in 0..HASH_SAMPLES.min(data_length) {
self.data[(i * data_length / HASH_SAMPLES) as usize].hash(state);
}
}
}
impl<P: Pixel> Image<P> {
pub fn new(width: u32, height: u32, color: P) -> Self {
Self {
width,
height,
data: vec![color; (width * height) as usize],
base64_string: None,
}
}
}
impl Image<Color> {
/// Generate Image from some frontend image data (the canvas pixels as u8s in a flat array)
pub fn from_image_data(image_data: &[u8], width: u32, height: u32) -> Self {
let data = image_data.chunks_exact(4).map(|v| Color::from_rgba8_srgb(v[0], v[1], v[2], v[3])).collect();
Image {
width,
height,
data,
base64_string: None,
}
}
pub fn to_png(&self) -> Vec<u8> {
use ::image::ImageEncoder;
let (data, width, height) = self.to_flat_u8();
let mut png = Vec::new();
let encoder = ::image::codecs::png::PngEncoder::new(&mut png);
encoder.write_image(&data, width, height, ::image::ExtendedColorType::Rgba8).expect("failed to encode image as png");
png
}
}
use super::*;
impl<P: Alpha + RGB + AssociatedAlpha> Image<P>
where
P::ColorChannel: Linear,
<P as Alpha>::AlphaChannel: Linear,
{
/// Flattens each channel cast to a u8
pub fn to_flat_u8(&self) -> (Vec<u8>, u32, u32) {
let Image { width, height, data, .. } = self;
assert_eq!(data.len(), *width as usize * *height as usize);
// Cache the last sRGB value we computed, speeds up fills.
let mut last_r = 0.;
let mut last_r_srgb = 0u8;
let mut last_g = 0.;
let mut last_g_srgb = 0u8;
let mut last_b = 0.;
let mut last_b_srgb = 0u8;
let mut result = vec![0; data.len() * 4];
let mut i = 0;
for color in data {
let a = color.a().to_f32();
// Smaller alpha values than this would map to fully transparent
// anyway, avoid expensive encoding.
if a >= 0.5 / 255. {
let undo_premultiply = 1. / a;
let r = color.r().to_f32() * undo_premultiply;
let g = color.g().to_f32() * undo_premultiply;
let b = color.b().to_f32() * undo_premultiply;
// Compute new sRGB value if necessary.
if r != last_r {
last_r = r;
last_r_srgb = float_to_srgb_u8(r);
}
if g != last_g {
last_g = g;
last_g_srgb = float_to_srgb_u8(g);
}
if b != last_b {
last_b = b;
last_b_srgb = float_to_srgb_u8(b);
}
result[i] = last_r_srgb;
result[i + 1] = last_g_srgb;
result[i + 2] = last_b_srgb;
result[i + 3] = (a * 255. + 0.5) as u8;
}
i += 4;
}
(result, *width, *height)
}
}
impl<P: Pixel> IntoIterator for Image<P> {
type Item = P;
type IntoIter = std::vec::IntoIter<P>;
fn into_iter(self) -> Self::IntoIter {
self.data.into_iter()
}
}
// TODO: Eventually remove this migration document upgrade code
pub fn migrate_image_frame<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Table<Raster<CPU>>, D::Error> {
use serde::Deserialize;
#[derive(Clone, Debug, Hash, PartialEq, DynAny)]
enum RasterFrame {
ImageFrame(Table<Image<Color>>),
}
impl<'de> serde::Deserialize<'de> for RasterFrame {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(RasterFrame::ImageFrame(Table::new_from_element(Image::deserialize(deserializer)?)))
}
}
impl serde::Serialize for RasterFrame {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
RasterFrame::ImageFrame(table) => table.serialize(serializer),
}
}
}
#[derive(Clone, Debug, Hash, PartialEq, DynAny, serde::Serialize, serde::Deserialize)]
pub enum GraphicElement {
GraphicGroup(Table<GraphicElement>),
RasterFrame(RasterFrame),
}
#[derive(Clone, Default, Debug, PartialEq, specta::Type, serde::Serialize, serde::Deserialize)]
pub struct ImageFrame<P: Pixel> {
pub image: Image<P>,
}
impl From<ImageFrame<Color>> for GraphicElement {
fn from(image_frame: ImageFrame<Color>) -> Self {
GraphicElement::RasterFrame(RasterFrame::ImageFrame(Table::new_from_element(image_frame.image)))
}
}
impl From<GraphicElement> for ImageFrame<Color> {
fn from(element: GraphicElement) -> Self {
match element {
GraphicElement::RasterFrame(RasterFrame::ImageFrame(image)) => Self {
image: image.iter().next().unwrap().element.clone(),
},
_ => panic!("Expected Image, found {element:?}"),
}
}
}
unsafe impl<P> StaticType for ImageFrame<P>
where
P: dyn_any::StaticTypeSized + Pixel,
P::Static: Pixel,
{
type Static = ImageFrame<P::Static>;
}
#[derive(Clone, Default, Debug, PartialEq, specta::Type, serde::Serialize, serde::Deserialize)]
pub struct OldImageFrame<P: Pixel> {
image: Image<P>,
transform: DAffine2,
alpha_blending: AlphaBlending,
}
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
enum FormatVersions {
Image(Image<Color>),
OldImageFrame(OldImageFrame<Color>),
OlderImageFrameTable(OlderTable<ImageFrame<Color>>),
OldImageFrameTable(OldTable<ImageFrame<Color>>),
OldImageTable(OldTable<Image<Color>>),
OldRasterTable(OldTable<Raster<CPU>>),
ImageFrameTable(Table<ImageFrame<Color>>),
ImageTable(Table<Image<Color>>),
RasterTable(Table<Raster<CPU>>),
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct OldTable<T> {
#[serde(alias = "instances", alias = "instance")]
element: Vec<T>,
transform: Vec<DAffine2>,
alpha_blending: Vec<AlphaBlending>,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct OlderTable<T> {
id: Vec<u64>,
#[serde(alias = "instances", alias = "instance")]
element: Vec<T>,
}
fn from_image_table(table: Table<Image<Color>>) -> Table<Raster<CPU>> {
Table::new_from_element(Raster::new_cpu(table.iter().next().unwrap().element.clone()))
}
fn old_table_to_new_table<T>(old_table: OldTable<T>) -> Table<T> {
old_table
.element
.into_iter()
.zip(old_table.transform.into_iter().zip(old_table.alpha_blending))
.map(|(element, (transform, alpha_blending))| TableRow {
element,
transform,
alpha_blending,
source_node_id: None,
})
.collect()
}
fn older_table_to_new_table<T>(old_table: OlderTable<T>) -> Table<T> {
old_table
.element
.into_iter()
.map(|element| TableRow {
element,
transform: DAffine2::IDENTITY,
alpha_blending: AlphaBlending::default(),
source_node_id: None,
})
.collect()
}
fn from_image_frame_table(image_frame: Table<ImageFrame<Color>>) -> Table<Raster<CPU>> {
Table::new_from_element(Raster::new_cpu(
image_frame
.iter()
.next()
.unwrap_or(Table::new_from_element(ImageFrame::default()).iter().next().unwrap())
.element
.image
.clone(),
))
}
Ok(match FormatVersions::deserialize(deserializer)? {
FormatVersions::Image(image) => Table::new_from_element(Raster::new_cpu(image)),
FormatVersions::OldImageFrame(OldImageFrame { image, transform, alpha_blending }) => {
let mut image_frame_table = Table::new_from_element(Raster::new_cpu(image));
*image_frame_table.iter_mut().next().unwrap().transform = transform;
*image_frame_table.iter_mut().next().unwrap().alpha_blending = alpha_blending;
image_frame_table
}
FormatVersions::OlderImageFrameTable(old_table) => from_image_frame_table(older_table_to_new_table(old_table)),
FormatVersions::OldImageFrameTable(old_table) => from_image_frame_table(old_table_to_new_table(old_table)),
FormatVersions::OldImageTable(old_table) => from_image_table(old_table_to_new_table(old_table)),
FormatVersions::OldRasterTable(old_table) => old_table_to_new_table(old_table),
FormatVersions::ImageFrameTable(image_frame) => from_image_frame_table(image_frame),
FormatVersions::ImageTable(table) => from_image_table(table),
FormatVersions::RasterTable(table) => table,
})
}
// TODO: Eventually remove this migration document upgrade code
pub fn migrate_image_frame_row<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<TableRow<Raster<CPU>>, D::Error> {
use serde::Deserialize;
#[derive(Clone, Debug, Hash, PartialEq, DynAny)]
enum RasterFrame {
/// A CPU-based bitmap image with a finite position and extent, equivalent to the SVG <image> tag: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image
ImageFrame(Table<Image<Color>>),
}
impl<'de> serde::Deserialize<'de> for RasterFrame {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(RasterFrame::ImageFrame(Table::new_from_element(Image::deserialize(deserializer)?)))
}
}
impl serde::Serialize for RasterFrame {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
RasterFrame::ImageFrame(table) => table.serialize(serializer),
}
}
}
#[derive(Clone, Debug, Hash, PartialEq, DynAny, serde::Serialize, serde::Deserialize)]
pub enum GraphicElement {
/// Equivalent to the SVG <g> tag: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g
GraphicGroup(Table<GraphicElement>),
RasterFrame(RasterFrame),
}
#[derive(Clone, Default, Debug, PartialEq, specta::Type, serde::Serialize, serde::Deserialize)]
pub struct ImageFrame<P: Pixel> {
pub image: Image<P>,
}
impl From<ImageFrame<Color>> for GraphicElement {
fn from(image_frame: ImageFrame<Color>) -> Self {
GraphicElement::RasterFrame(RasterFrame::ImageFrame(Table::new_from_element(image_frame.image)))
}
}
impl From<GraphicElement> for ImageFrame<Color> {
fn from(element: GraphicElement) -> Self {
match element {
GraphicElement::RasterFrame(RasterFrame::ImageFrame(image)) => Self {
image: image.iter().next().unwrap().element.clone(),
},
_ => panic!("Expected Image, found {element:?}"),
}
}
}
unsafe impl<P> StaticType for ImageFrame<P>
where
P: dyn_any::StaticTypeSized + Pixel,
P::Static: Pixel,
{
type Static = ImageFrame<P::Static>;
}
#[derive(Clone, Default, Debug, PartialEq, specta::Type, serde::Serialize, serde::Deserialize)]
pub struct OldImageFrame<P: Pixel> {
image: Image<P>,
transform: DAffine2,
alpha_blending: AlphaBlending,
}
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
enum FormatVersions {
Image(Image<Color>),
OldImageFrame(OldImageFrame<Color>),
ImageFrameTable(Table<ImageFrame<Color>>),
RasterTable(Table<Raster<CPU>>),
RasterTableRow(TableRow<Raster<CPU>>),
}
Ok(match FormatVersions::deserialize(deserializer)? {
FormatVersions::Image(image) => TableRow {
element: Raster::new_cpu(image),
..Default::default()
},
FormatVersions::OldImageFrame(image_frame_with_transform_and_blending) => TableRow {
element: Raster::new_cpu(image_frame_with_transform_and_blending.image),
transform: image_frame_with_transform_and_blending.transform,
alpha_blending: image_frame_with_transform_and_blending.alpha_blending,
source_node_id: None,
},
FormatVersions::ImageFrameTable(image_frame) => TableRow {
element: Raster::new_cpu(image_frame.iter().next().unwrap().element.image.clone()),
..Default::default()
},
FormatVersions::RasterTable(image_frame_table) => image_frame_table.into_iter().next().unwrap_or_default(),
FormatVersions::RasterTableRow(image_table_row) => image_table_row,
})
}
impl<P: std::fmt::Debug + Copy + Pixel> Sample for Image<P> {
type Pixel = P;
// TODO: Improve sampling logic
#[inline(always)]
fn sample(&self, pos: DVec2, _area: DVec2) -> Option<Self::Pixel> {
let image_size = DVec2::new(self.width() as f64, self.height() as f64);
if pos.x < 0. || pos.y < 0. || pos.x >= image_size.x || pos.y >= image_size.y {
return None;
}
self.get_pixel(pos.x as u32, pos.y as u32)
}
}
impl<P: Copy + Pixel> Image<P> {
pub fn get_mut(&mut self, x: usize, y: usize) -> &mut P {
&mut self.data[y * (self.width as usize) + x]
}
/// Clamps the provided point to ((0, 0), (ImageSize.x, ImageSize.y)) and returns the closest pixel
pub fn sample(&self, position: DVec2) -> P {
let x = position.x.clamp(0., self.width as f64 - 1.) as usize;
let y = position.y.clamp(0., self.height as f64 - 1.) as usize;
self.data[x + y * self.width as usize]
}
}
impl<P: Pixel> AsRef<Image<P>> for Image<P> {
fn as_ref(&self) -> &Image<P> {
self
}
}
impl From<Image<Color>> for Image<SRGBA8> {
fn from(image: Image<Color>) -> Self {
let data = image.data.into_iter().map(|x| x.into()).collect();
Self {
data,
width: image.width,
height: image.height,
base64_string: None,
}
}
}
impl From<Image<SRGBA8>> for Image<Color> {
fn from(image: Image<SRGBA8>) -> Self {
let data = image.data.into_iter().map(|x| x.into()).collect();
Self {
data,
width: image.width,
height: image.height,
base64_string: None,
}
}
}
#[cfg(test)]
mod test {
#[test]
fn test_image_serialization_roundtrip() {
use super::*;
use crate::Color;
let image = Image {
width: 2,
height: 2,
data: vec![Color::WHITE, Color::BLACK, Color::RED, Color::GREEN],
base64_string: None,
};
let serialized = serde_json::to_string(&image).unwrap();
println!("{serialized}");
let deserialized: Image<Color> = serde_json::from_str(&serialized).unwrap();
println!("{deserialized:?}");
assert_eq!(image, deserialized);
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/raster-types/src/raster_types.rs | node-graph/libraries/raster-types/src/raster_types.rs | use crate::image::Image;
use core::ops::Deref;
use core_types::Color;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::math::quad::Quad;
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
use std::fmt::Debug;
use std::ops::DerefMut;
mod __private {
pub trait Sealed {}
}
pub trait Storage: __private::Sealed + Clone + Debug + 'static {
fn is_empty(&self) -> bool;
}
#[derive(Clone, Debug, PartialEq, Hash, Default)]
pub struct Raster<T>
where
Raster<T>: Storage,
{
storage: T,
}
unsafe impl<T> dyn_any::StaticType for Raster<T>
where
Raster<T>: Storage,
{
type Static = Raster<T>;
}
impl<T> Raster<T>
where
Raster<T>: Storage,
{
pub fn new(t: T) -> Self {
Self { storage: t }
}
}
impl<T> Deref for Raster<T>
where
Raster<T>: Storage,
{
type Target = T;
fn deref(&self) -> &Self::Target {
&self.storage
}
}
impl<T> DerefMut for Raster<T>
where
Raster<T>: Storage,
{
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.storage
}
}
pub use cpu::CPU;
mod cpu {
use super::*;
use crate::raster_types::__private::Sealed;
#[derive(Clone, Debug, Default, PartialEq, Hash, DynAny)]
pub struct CPU(Image<Color>);
impl Sealed for Raster<CPU> {}
impl Storage for Raster<CPU> {
fn is_empty(&self) -> bool {
self.0.height == 0 || self.0.width == 0
}
}
impl Raster<CPU> {
pub fn new_cpu(image: Image<Color>) -> Self {
Self::new(CPU(image))
}
pub fn data(&self) -> &Image<Color> {
self
}
pub fn data_mut(&mut self) -> &mut Image<Color> {
self
}
pub fn into_data(self) -> Image<Color> {
self.storage.0
}
}
impl Deref for CPU {
type Target = Image<Color>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for CPU {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<'de> serde::Deserialize<'de> for Raster<CPU> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(Raster::new_cpu(Image::deserialize(deserializer)?))
}
}
impl serde::Serialize for Raster<CPU> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.serialize(serializer)
}
}
}
pub use gpu::GPU;
#[cfg(feature = "wgpu")]
mod gpu {
use super::*;
use crate::raster_types::__private::Sealed;
#[derive(Clone, Debug, PartialEq, Hash)]
pub struct GPU {
pub texture: wgpu::Texture,
}
impl Sealed for Raster<GPU> {}
impl Storage for Raster<GPU> {
fn is_empty(&self) -> bool {
self.texture.width() == 0 || self.texture.height() == 0
}
}
impl Raster<GPU> {
pub fn new_gpu(texture: wgpu::Texture) -> Self {
Self::new(GPU { texture })
}
pub fn data(&self) -> &wgpu::Texture {
&self.texture
}
}
}
#[cfg(not(feature = "wgpu"))]
mod gpu {
use super::*;
use crate::raster_types::__private::Sealed;
#[derive(Clone, Debug, PartialEq, Hash)]
pub struct GPU;
impl Sealed for Raster<GPU> {}
impl Storage for Raster<GPU> {
fn is_empty(&self) -> bool {
true
}
}
}
mod gpu_common {
use super::*;
impl<'de> serde::Deserialize<'de> for Raster<GPU> {
fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
unimplemented!()
}
}
impl serde::Serialize for Raster<GPU> {
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
unimplemented!()
}
}
}
impl<T> BoundingBox for Raster<T>
where
Raster<T>: Storage,
{
fn bounding_box(&self, transform: DAffine2, _include_stroke: bool) -> RenderBoundingBox {
if self.is_empty() || transform.matrix2.determinant() == 0. {
return RenderBoundingBox::None;
}
let unit_rectangle = Quad::from_box([DVec2::ZERO, DVec2::ONE]);
RenderBoundingBox::Rectangle((transform * unit_rectangle).bounding_box())
}
}
// RenderComplexity trait implementations
impl core_types::render_complexity::RenderComplexity for Raster<CPU> {
fn render_complexity(&self) -> usize {
(self.width * self.height / 500) as usize
}
}
impl core_types::render_complexity::RenderComplexity for Raster<GPU> {
fn render_complexity(&self) -> usize {
// GPU textures currently can't have a thumbnail
usize::MAX
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/consts.rs | node-graph/libraries/core-types/src/consts.rs | use crate::Color;
// RENDERING
pub const LAYER_OUTLINE_STROKE_COLOR: Color = Color::BLACK;
pub const LAYER_OUTLINE_STROKE_WEIGHT: f64 = 0.5;
// Fonts
pub const DEFAULT_FONT_FAMILY: &str = "Lato";
pub const DEFAULT_FONT_STYLE: &str = "Regular (400)";
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/misc.rs | node-graph/libraries/core-types/src/misc.rs | // TODO(TrueDoctor): Replace this with the more idiomatic approach instead of using `trait Clampable`.
/// A trait for types that can be clamped within a min/max range defined by f64.
pub trait Clampable: Sized {
/// Clamps the value to be no less than `min`.
fn clamp_hard_min(self, min: f64) -> Self;
/// Clamps the value to be no more than `max`.
fn clamp_hard_max(self, max: f64) -> Self;
}
// Implement for common numeric types
macro_rules! impl_clampable_float {
($($ty:ty),*) => {
$(
impl Clampable for $ty {
#[inline(always)]
fn clamp_hard_min(self, min: f64) -> Self {
self.max(min as $ty)
}
#[inline(always)]
fn clamp_hard_max(self, max: f64) -> Self {
self.min(max as $ty)
}
}
)*
};
}
impl_clampable_float!(f32, f64);
macro_rules! impl_clampable_int {
($($ty:ty),*) => {
$(
impl Clampable for $ty {
#[inline(always)]
fn clamp_hard_min(self, min: f64) -> Self {
// Using try_from to handle potential range issues safely, though min should ideally be valid.
// Consider using a different approach if f64 precision vs integer range is a concern.
<$ty>::try_from(min.ceil() as i64).ok().map_or(self, |min_val| self.max(min_val))
}
#[inline(always)]
fn clamp_hard_max(self, max: f64) -> Self {
<$ty>::try_from(max.floor() as i64).ok().map_or(self, |max_val| self.min(max_val))
}
}
)*
};
}
// Add relevant integer types (adjust as needed)
impl_clampable_int!(u32, u64, i32, i64);
// Implement for DVec2 (component-wise clamping)
use glam::DVec2;
impl Clampable for DVec2 {
#[inline(always)]
fn clamp_hard_min(self, min: f64) -> Self {
self.max(DVec2::splat(min))
}
#[inline(always)]
fn clamp_hard_max(self, max: f64) -> Self {
self.min(DVec2::splat(max))
}
}
// TODO: Eventually remove this migration document upgrade code
pub fn migrate_color<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<crate::table::Table<no_std_types::color::Color>, D::Error> {
use crate::table::Table;
use no_std_types::color::Color;
use serde::Deserialize;
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
enum ColorFormat {
Color(Color),
OptionalColor(Option<Color>),
ColorTable(Table<Color>),
}
Ok(match ColorFormat::deserialize(deserializer)? {
ColorFormat::Color(color) => Table::new_from_element(color),
ColorFormat::OptionalColor(color) => {
if let Some(color) = color {
Table::new_from_element(color)
} else {
Table::new()
}
}
ColorFormat::ColorTable(color_table) => color_table,
})
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/lib.rs | node-graph/libraries/core-types/src/lib.rs | extern crate log;
pub mod bounds;
pub mod consts;
pub mod context;
pub mod generic;
pub mod math;
pub mod memo;
pub mod misc;
pub mod ops;
pub mod registry;
pub mod render_complexity;
pub mod table;
pub mod transform;
pub mod uuid;
pub mod value;
pub use crate as core_types;
pub use blending::*;
pub use color::Color;
pub use context::*;
pub use ctor;
pub use dyn_any::{StaticTypeSized, WasmNotSend, WasmNotSync};
pub use memo::MemoHash;
pub use no_std_types::AsU32;
pub use no_std_types::blending;
pub use no_std_types::choice_type;
pub use no_std_types::color;
pub use no_std_types::shaders;
pub use num_traits;
pub use specta;
use std::any::TypeId;
use std::future::Future;
use std::pin::Pin;
pub use types::Cow;
// pub trait Node: for<'n> NodeIO<'n> {
/// The node trait allows for defining any node. Nodes can only take one call argument input, however they can store references to other nodes inside the struct.
/// See `node-graph/README.md` for information on how to define a new node.
pub trait Node<'i, Input> {
type Output: 'i;
/// Evaluates the node with the single specified input.
fn eval(&'i self, input: Input) -> Self::Output;
/// Resets the node, e.g. the LetNode's cache is set to None.
fn reset(&self) {}
/// Returns the name of the node for diagnostic purposes.
fn node_name(&self) -> &'static str {
std::any::type_name::<Self>()
}
/// Serialize the node which is used for the `introspect` function which can retrieve values from monitor nodes.
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
log::warn!("Node::serialize not implemented for {}", std::any::type_name::<Self>());
None
}
}
mod types;
pub use types::*;
pub trait NodeIO<'i, Input>: Node<'i, Input>
where
Self::Output: 'i + StaticTypeSized,
Input: StaticTypeSized,
{
fn input_type(&self) -> TypeId {
TypeId::of::<Input::Static>()
}
fn input_type_name(&self) -> &'static str {
std::any::type_name::<Input>()
}
fn output_type(&self) -> TypeId {
TypeId::of::<<Self::Output as StaticTypeSized>::Static>()
}
fn output_type_name(&self) -> &'static str {
std::any::type_name::<Self::Output>()
}
fn to_node_io(&self, inputs: Vec<Type>) -> NodeIOTypes {
NodeIOTypes {
call_argument: concrete!(<Input as StaticTypeSized>::Static),
return_value: concrete!(<Self::Output as StaticTypeSized>::Static),
inputs,
}
}
fn to_async_node_io(&self, inputs: Vec<Type>) -> NodeIOTypes
where
<Self::Output as Future>::Output: StaticTypeSized,
Self::Output: Future,
{
NodeIOTypes {
call_argument: concrete!(<Input as StaticTypeSized>::Static),
return_value: future!(<<Self::Output as Future>::Output as StaticTypeSized>::Static),
inputs,
}
}
}
impl<'i, N: Node<'i, I>, I> NodeIO<'i, I> for N
where
N::Output: 'i + StaticTypeSized,
I: StaticTypeSized,
{
}
impl<'i, I: 'i, N: Node<'i, I> + ?Sized> Node<'i, I> for &'i N {
type Output = N::Output;
fn eval(&'i self, input: I) -> N::Output {
(*self).eval(input)
}
}
impl<'i, I: 'i, O: 'i, N: Node<'i, I, Output = O> + ?Sized> Node<'i, I> for Box<N> {
type Output = O;
fn eval(&'i self, input: I) -> O {
(**self).eval(input)
}
}
impl<'i, I: 'i, O: 'i, N: Node<'i, I, Output = O> + ?Sized> Node<'i, I> for std::sync::Arc<N> {
type Output = O;
fn eval(&'i self, input: I) -> O {
(**self).eval(input)
}
}
impl<'i, I, O: 'i> Node<'i, I> for Pin<Box<dyn Node<'i, I, Output = O> + 'i>> {
type Output = O;
fn eval(&'i self, input: I) -> O {
(**self).eval(input)
}
}
impl<'i, I, O: 'i> Node<'i, I> for Pin<&'i (dyn NodeIO<'i, I, Output = O> + 'i)> {
type Output = O;
fn eval(&'i self, input: I) -> O {
(**self).eval(input)
}
}
pub trait InputAccessorSource<'a, T>: InputAccessorSourceIdentifier + std::fmt::Debug {
fn get_input(&'a self, index: usize) -> Option<&'a T>;
fn set_input(&'a mut self, index: usize, value: T);
}
pub trait InputAccessorSourceIdentifier {
fn has_identifier(&self, identifier: &str) -> bool;
}
pub trait InputAccessor<'n, Source: 'n>
where
Self: Sized,
{
fn new_with_source(source: &'n Source) -> Option<Self>;
}
pub trait NodeInputDecleration {
const INDEX: usize;
fn identifier() -> ProtoNodeIdentifier;
type Result;
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/value.rs | node-graph/libraries/core-types/src/value.rs | use crate::Node;
use std::cell::{Cell, RefCell, RefMut};
use std::marker::PhantomData;
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct IntNode<const N: u32>;
impl<'i, const N: u32, I> Node<'i, I> for IntNode<N> {
type Output = u32;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
N
}
}
#[derive(Default, Debug, Clone, Copy)]
pub struct ValueNode<T>(pub T);
impl<'i, T: 'i, I> Node<'i, I> for ValueNode<T> {
type Output = &'i T;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
&self.0
}
}
impl<T> ValueNode<T> {
pub const fn new(value: T) -> ValueNode<T> {
ValueNode(value)
}
}
impl<T> From<T> for ValueNode<T> {
fn from(value: T) -> Self {
ValueNode::new(value)
}
}
#[derive(Default, Debug, Clone, Copy)]
pub struct AsRefNode<T: AsRef<U>, U>(pub T, PhantomData<U>);
impl<'i, T: 'i + AsRef<U>, U: 'i> Node<'i, ()> for AsRefNode<T, U> {
type Output = &'i U;
#[inline(always)]
fn eval(&'i self, _input: ()) -> Self::Output {
self.0.as_ref()
}
}
impl<T: AsRef<U>, U> AsRefNode<T, U> {
pub const fn new(value: T) -> AsRefNode<T, U> {
AsRefNode(value, PhantomData)
}
}
#[derive(Default, Debug, Clone)]
pub struct RefCellMutNode<T>(pub RefCell<T>);
impl<'i, T: 'i> Node<'i, ()> for RefCellMutNode<T> {
type Output = RefMut<'i, T>;
#[inline(always)]
fn eval(&'i self, _input: ()) -> Self::Output {
self.0.borrow_mut()
}
}
impl<T> RefCellMutNode<T> {
pub const fn new(value: T) -> RefCellMutNode<T> {
RefCellMutNode(RefCell::new(value))
}
}
#[derive(Default)]
pub struct OnceCellNode<T>(pub Cell<T>);
impl<'i, T: Default + 'i, I> Node<'i, I> for OnceCellNode<T> {
type Output = T;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
self.0.replace(T::default())
}
}
impl<T> OnceCellNode<T> {
pub const fn new(value: T) -> OnceCellNode<T> {
OnceCellNode(Cell::new(value))
}
}
#[derive(Clone, Copy)]
pub struct ClonedNode<T: Clone>(pub T);
impl<'i, T: Clone + 'i, I> Node<'i, I> for ClonedNode<T> {
type Output = T;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
self.0.clone()
}
}
impl<T: Clone> ClonedNode<T> {
pub const fn new(value: T) -> ClonedNode<T> {
ClonedNode(value)
}
}
impl<T: Clone> From<T> for ClonedNode<T> {
fn from(value: T) -> Self {
ClonedNode::new(value)
}
}
#[derive(Clone, Copy)]
/// The DebugClonedNode logs every time it is evaluated.
/// This is useful for debugging.
pub struct DebugClonedNode<T: Clone>(pub T);
impl<'i, T: Clone + 'i> Node<'i, ()> for DebugClonedNode<T> {
type Output = T;
#[inline(always)]
fn eval(&'i self, _input: ()) -> Self::Output {
// KEEP THIS `debug!()` - It acts as the output for the debug node itself
log::debug!("DebugClonedNode::eval");
self.0.clone()
}
}
impl<T: Clone> DebugClonedNode<T> {
pub const fn new(value: T) -> DebugClonedNode<T> {
DebugClonedNode(value)
}
}
#[derive(Clone, Copy)]
pub struct CopiedNode<T: Copy>(pub T);
impl<'i, T: Copy + 'i, I> Node<'i, I> for CopiedNode<T> {
type Output = T;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
self.0
}
}
impl<T: Copy> CopiedNode<T> {
pub const fn new(value: T) -> CopiedNode<T> {
CopiedNode(value)
}
}
#[derive(Default)]
pub struct DefaultNode<T>(PhantomData<T>);
impl<'i, T: Default + 'i, I> Node<'i, I> for DefaultNode<T> {
type Output = T;
fn eval(&'i self, _input: I) -> Self::Output {
T::default()
}
}
impl<T> DefaultNode<T> {
pub fn new() -> Self {
Self(PhantomData)
}
}
#[repr(C)]
/// Return the unit value
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct ForgetNode;
impl<'i, T: 'i> Node<'i, T> for ForgetNode {
type Output = ();
fn eval(&'i self, _input: T) -> Self::Output {}
}
impl ForgetNode {
pub const fn new() -> Self {
ForgetNode
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_int_node() {
let node = IntNode::<5>;
assert_eq!(node.eval(()), 5);
}
#[test]
fn test_value_node() {
let node = ValueNode::new(5);
assert_eq!(node.eval(()), &5);
let type_erased = &node as &dyn for<'a> Node<'a, (), Output = &'a i32>;
assert_eq!(type_erased.eval(()), &5);
}
#[test]
fn test_default_node() {
let node = DefaultNode::<u32>::new();
assert_eq!(node.eval(42), 0);
}
#[test]
#[allow(clippy::unit_cmp)]
fn test_unit_node() {
let node = ForgetNode::new();
assert_eq!(node.eval(()), ());
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/transform.rs | node-graph/libraries/core-types/src/transform.rs | use crate::math::bbox::AxisAlignedBbox;
use core::f64;
use glam::{DAffine2, DMat2, DVec2, UVec2};
pub trait Transform {
fn transform(&self) -> DAffine2;
fn local_pivot(&self, pivot: DVec2) -> DVec2 {
pivot
}
fn decompose_scale(&self) -> DVec2 {
DVec2::new(self.transform().transform_vector2(DVec2::X).length(), self.transform().transform_vector2(DVec2::Y).length())
}
/// Requires that the transform does not contain any skew.
fn decompose_rotation(&self) -> f64 {
let rotation_matrix = (self.transform() * DAffine2::from_scale(self.decompose_scale().recip())).matrix2;
let rotation = -rotation_matrix.mul_vec2(DVec2::X).angle_to(DVec2::X);
if rotation == -0. { 0. } else { rotation }
}
/// Detects if the transform contains skew by checking if the transformation matrix
/// deviates from a pure rotation + uniform scale + translation.
///
/// Returns true if the matrix columns are not orthogonal or have different lengths,
/// indicating the presence of skew or non-uniform scaling.
fn has_skew(&self) -> bool {
let mat2 = self.transform().matrix2;
let col0 = mat2.x_axis;
let col1 = mat2.y_axis;
const EPSILON: f64 = 1e-10;
// Check if columns are orthogonal (dot product should be ~0) and equal length
// Non-orthogonal columns or different lengths indicate skew/non-uniform scaling
col0.dot(col1).abs() > EPSILON || (col0.length() - col1.length()).abs() > EPSILON
}
}
pub trait TransformMut: Transform {
fn transform_mut(&mut self) -> &mut DAffine2;
fn translate(&mut self, offset: DVec2) {
*self.transform_mut() = DAffine2::from_translation(offset) * self.transform();
}
}
// Implementation for references to anything that implements Transform
impl<T: Transform> Transform for &T {
fn transform(&self) -> DAffine2 {
(*self).transform()
}
}
// Implementations for DAffine2
impl Transform for DAffine2 {
fn transform(&self) -> DAffine2 {
*self
}
}
impl TransformMut for DAffine2 {
fn transform_mut(&mut self) -> &mut DAffine2 {
self
}
}
// Implementations for Footprint
impl Transform for Footprint {
fn transform(&self) -> DAffine2 {
self.transform
}
}
impl TransformMut for Footprint {
fn transform_mut(&mut self) -> &mut DAffine2 {
&mut self.transform
}
}
#[derive(Debug, Clone, Copy, dyn_any::DynAny, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum RenderQuality {
/// Low quality, fast rendering
Preview,
/// Ensure that the render is available with at least the specified quality
/// A value of 0.5 means that the render is available with at least 50% of the final image resolution
Scale(f32),
/// Flip a coin to decide if the render should be available with the current quality or done at full quality
/// This should be used to gradually update the render quality of a cached node
Probability(f32),
/// Render at full quality
Full,
}
#[derive(Debug, Clone, Copy, dyn_any::DynAny, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Footprint {
/// Inverse of the transform which will be applied to the node output during the rendering process
pub transform: DAffine2,
/// Resolution of the target output area in pixels
pub resolution: UVec2,
/// Quality of the render, this may be used by caching nodes to decide if the cached render is sufficient
pub quality: RenderQuality,
}
impl Default for Footprint {
fn default() -> Self {
Self::DEFAULT
}
}
impl Footprint {
pub const DEFAULT: Self = Self {
transform: DAffine2::IDENTITY,
resolution: UVec2::new(1920, 1080),
quality: RenderQuality::Full,
};
pub const BOUNDLESS: Self = Self {
transform: DAffine2 {
matrix2: DMat2::from_diagonal(DVec2::splat(f64::INFINITY)),
translation: DVec2::ZERO,
},
resolution: UVec2::ZERO,
quality: RenderQuality::Full,
};
pub fn viewport_bounds_in_local_space(&self) -> AxisAlignedBbox {
let inverse = self.transform.inverse();
let start = inverse.transform_point2((0., 0.).into());
let end = inverse.transform_point2(self.resolution.as_dvec2());
AxisAlignedBbox { start, end }
}
pub fn scale(&self) -> DVec2 {
self.transform.decompose_scale()
}
pub fn offset(&self) -> DVec2 {
self.transform.transform_point2(DVec2::ZERO)
}
}
impl From<()> for Footprint {
fn from(_: ()) -> Self {
Footprint::default()
}
}
impl std::hash::Hash for Footprint {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.transform.to_cols_array().iter().for_each(|x| x.to_le_bytes().hash(state));
self.resolution.hash(state)
}
}
pub trait ApplyTransform {
fn apply_transform(&mut self, modification: &DAffine2);
fn left_apply_transform(&mut self, modification: &DAffine2);
}
impl<T: TransformMut> ApplyTransform for T {
fn apply_transform(&mut self, &modification: &DAffine2) {
*self.transform_mut() = self.transform() * modification
}
fn left_apply_transform(&mut self, &modification: &DAffine2) {
*self.transform_mut() = modification * self.transform()
}
}
impl ApplyTransform for DVec2 {
fn apply_transform(&mut self, modification: &DAffine2) {
*self = modification.transform_point2(*self);
}
fn left_apply_transform(&mut self, modification: &DAffine2) {
*self = modification.inverse().transform_point2(*self);
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/table.rs | node-graph/libraries/core-types/src/table.rs | use crate::bounds::{BoundingBox, RenderBoundingBox};
use crate::transform::ApplyTransform;
use crate::uuid::NodeId;
use crate::{AlphaBlending, math::quad::Quad};
use dyn_any::{StaticType, StaticTypeSized};
use glam::DAffine2;
use std::hash::Hash;
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Table<T> {
#[serde(alias = "instances", alias = "instance")]
element: Vec<T>,
transform: Vec<DAffine2>,
alpha_blending: Vec<AlphaBlending>,
source_node_id: Vec<Option<NodeId>>,
}
impl<T> Table<T> {
pub fn new() -> Self {
Self::default()
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
element: Vec::with_capacity(capacity),
transform: Vec::with_capacity(capacity),
alpha_blending: Vec::with_capacity(capacity),
source_node_id: Vec::with_capacity(capacity),
}
}
pub fn new_from_element(element: T) -> Self {
Self {
element: vec![element],
transform: vec![DAffine2::IDENTITY],
alpha_blending: vec![AlphaBlending::default()],
source_node_id: vec![None],
}
}
pub fn new_from_row(row: TableRow<T>) -> Self {
Self {
element: vec![row.element],
transform: vec![row.transform],
alpha_blending: vec![row.alpha_blending],
source_node_id: vec![row.source_node_id],
}
}
pub fn push(&mut self, row: TableRow<T>) {
self.element.push(row.element);
self.transform.push(row.transform);
self.alpha_blending.push(row.alpha_blending);
self.source_node_id.push(row.source_node_id);
}
pub fn extend(&mut self, table: Table<T>) {
self.element.extend(table.element);
self.transform.extend(table.transform);
self.alpha_blending.extend(table.alpha_blending);
self.source_node_id.extend(table.source_node_id);
}
pub fn get(&self, index: usize) -> Option<TableRowRef<'_, T>> {
if index >= self.element.len() {
return None;
}
Some(TableRowRef {
element: &self.element[index],
transform: &self.transform[index],
alpha_blending: &self.alpha_blending[index],
source_node_id: &self.source_node_id[index],
})
}
pub fn get_mut(&mut self, index: usize) -> Option<TableRowMut<'_, T>> {
if index >= self.element.len() {
return None;
}
Some(TableRowMut {
element: &mut self.element[index],
transform: &mut self.transform[index],
alpha_blending: &mut self.alpha_blending[index],
source_node_id: &mut self.source_node_id[index],
})
}
pub fn len(&self) -> usize {
self.element.len()
}
pub fn is_empty(&self) -> bool {
self.element.is_empty()
}
/// Borrows a [`Table`] and returns an iterator of [`TableRowRef`]s, each containing references to the data of the respective row from the table.
pub fn iter(&self) -> impl DoubleEndedIterator<Item = TableRowRef<'_, T>> + Clone {
self.element
.iter()
.zip(self.transform.iter())
.zip(self.alpha_blending.iter())
.zip(self.source_node_id.iter())
.map(|(((element, transform), alpha_blending), source_node_id)| TableRowRef {
element,
transform,
alpha_blending,
source_node_id,
})
}
/// Mutably borrows a [`Table`] and returns an iterator of [`TableRowMut`]s, each containing mutable references to the data of the respective row from the table.
pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = TableRowMut<'_, T>> {
self.element
.iter_mut()
.zip(self.transform.iter_mut())
.zip(self.alpha_blending.iter_mut())
.zip(self.source_node_id.iter_mut())
.map(|(((element, transform), alpha_blending), source_node_id)| TableRowMut {
element,
transform,
alpha_blending,
source_node_id,
})
}
}
impl<T: BoundingBox> BoundingBox for Table<T> {
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
let mut combined_bounds = None;
for row in self.iter() {
match row.element.bounding_box(transform * *row.transform, include_stroke) {
RenderBoundingBox::None => continue,
RenderBoundingBox::Infinite => return RenderBoundingBox::Infinite,
RenderBoundingBox::Rectangle(bounds) => match combined_bounds {
Some(existing) => combined_bounds = Some(Quad::combine_bounds(existing, bounds)),
None => combined_bounds = Some(bounds),
},
}
}
match combined_bounds {
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
None => RenderBoundingBox::None,
}
}
}
impl<T> IntoIterator for Table<T> {
type Item = TableRow<T>;
type IntoIter = TableRowIter<T>;
/// Consumes a [`Table`] and returns an iterator of [`TableRow`]s, each containing the owned data of the respective row from the original table.
fn into_iter(self) -> Self::IntoIter {
TableRowIter {
element: self.element.into_iter(),
transform: self.transform.into_iter(),
alpha_blending: self.alpha_blending.into_iter(),
source_node_id: self.source_node_id.into_iter(),
}
}
}
pub struct TableRowIter<T> {
element: std::vec::IntoIter<T>,
transform: std::vec::IntoIter<DAffine2>,
alpha_blending: std::vec::IntoIter<AlphaBlending>,
source_node_id: std::vec::IntoIter<Option<NodeId>>,
}
impl<T> Iterator for TableRowIter<T> {
type Item = TableRow<T>;
fn next(&mut self) -> Option<Self::Item> {
let element = self.element.next()?;
let transform = self.transform.next()?;
let alpha_blending = self.alpha_blending.next()?;
let source_node_id = self.source_node_id.next()?;
Some(TableRow {
element,
transform,
alpha_blending,
source_node_id,
})
}
}
impl<T> Default for Table<T> {
fn default() -> Self {
Self {
element: Vec::new(),
transform: Vec::new(),
alpha_blending: Vec::new(),
source_node_id: Vec::new(),
}
}
}
impl<T: Hash> Hash for Table<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
for element in &self.element {
element.hash(state);
}
for transform in &self.transform {
transform.to_cols_array().map(|x| x.to_bits()).hash(state);
}
for alpha_blending in &self.alpha_blending {
alpha_blending.hash(state);
}
}
}
impl<T: PartialEq> PartialEq for Table<T> {
fn eq(&self, other: &Self) -> bool {
self.element == other.element && self.transform == other.transform && self.alpha_blending == other.alpha_blending
}
}
impl<T> ApplyTransform for Table<T> {
fn apply_transform(&mut self, modification: &DAffine2) {
for transform in &mut self.transform {
*transform *= *modification;
}
}
fn left_apply_transform(&mut self, modification: &DAffine2) {
for transform in &mut self.transform {
*transform = *modification * *transform;
}
}
}
unsafe impl<T: StaticTypeSized> StaticType for Table<T> {
type Static = Table<T::Static>;
}
impl<T> FromIterator<TableRow<T>> for Table<T> {
fn from_iter<I: IntoIterator<Item = TableRow<T>>>(iter: I) -> Self {
let iter = iter.into_iter();
let (lower, _) = iter.size_hint();
let mut table = Self::with_capacity(lower);
for row in iter {
table.push(row);
}
table
}
}
#[derive(Copy, Clone, Default, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct TableRow<T> {
#[serde(alias = "instance")]
pub element: T,
pub transform: DAffine2,
pub alpha_blending: AlphaBlending,
pub source_node_id: Option<NodeId>,
}
impl<T> TableRow<T> {
pub fn new_from_element(element: T) -> Self {
Self {
element,
transform: DAffine2::IDENTITY,
alpha_blending: AlphaBlending::default(),
source_node_id: None,
}
}
pub fn as_ref(&self) -> TableRowRef<'_, T> {
TableRowRef {
element: &self.element,
transform: &self.transform,
alpha_blending: &self.alpha_blending,
source_node_id: &self.source_node_id,
}
}
pub fn as_mut(&mut self) -> TableRowMut<'_, T> {
TableRowMut {
element: &mut self.element,
transform: &mut self.transform,
alpha_blending: &mut self.alpha_blending,
source_node_id: &mut self.source_node_id,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct TableRowRef<'a, T> {
pub element: &'a T,
pub transform: &'a DAffine2,
pub alpha_blending: &'a AlphaBlending,
pub source_node_id: &'a Option<NodeId>,
}
impl<T> TableRowRef<'_, T> {
pub fn into_cloned(self) -> TableRow<T>
where
T: Clone,
{
TableRow {
element: self.element.clone(),
transform: *self.transform,
alpha_blending: *self.alpha_blending,
source_node_id: *self.source_node_id,
}
}
}
#[derive(Debug)]
pub struct TableRowMut<'a, T> {
pub element: &'a mut T,
pub transform: &'a mut DAffine2,
pub alpha_blending: &'a mut AlphaBlending,
pub source_node_id: &'a mut Option<NodeId>,
}
// Conversion from Table<Color> to Option<Color> - extracts first element
impl From<Table<crate::Color>> for Option<crate::Color> {
fn from(table: Table<crate::Color>) -> Self {
table.iter().nth(0).map(|row| row.element).copied()
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/bounds.rs | node-graph/libraries/core-types/src/bounds.rs | use crate::Color;
use glam::{DAffine2, DVec2};
#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub enum RenderBoundingBox {
#[default]
None,
Infinite,
Rectangle([DVec2; 2]),
}
pub trait BoundingBox {
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox;
}
macro_rules! none_impl {
($t:path) => {
impl BoundingBox for $t {
fn bounding_box(&self, _transform: DAffine2, _include_stroke: bool) -> RenderBoundingBox {
RenderBoundingBox::None
}
}
};
}
none_impl!(bool);
none_impl!(f32);
none_impl!(f64);
none_impl!(DVec2);
none_impl!(String);
impl BoundingBox for Color {
fn bounding_box(&self, _transform: DAffine2, _include_stroke: bool) -> RenderBoundingBox {
RenderBoundingBox::Infinite
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/text.rs | node-graph/libraries/core-types/src/text.rs | mod font_cache;
mod path_builder;
mod text_context;
mod to_path;
use dyn_any::DynAny;
pub use font_cache::*;
pub use text_context::TextContext;
pub use to_path::*;
/// Alignment of lines of type within a text block.
#[repr(C)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash, DynAny, specta::Type, node_macro::ChoiceType)]
#[widget(Radio)]
pub enum TextAlign {
#[default]
Left,
Center,
Right,
#[label("Justify")]
JustifyLeft,
// TODO: JustifyCenter, JustifyRight, JustifyAll
}
impl From<TextAlign> for parley::Alignment {
fn from(val: TextAlign) -> Self {
match val {
TextAlign::Left => parley::Alignment::Left,
TextAlign::Center => parley::Alignment::Center,
TextAlign::Right => parley::Alignment::Right,
TextAlign::JustifyLeft => parley::Alignment::Justify,
}
}
}
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub struct TypesettingConfig {
pub font_size: f64,
pub line_height_ratio: f64,
pub character_spacing: f64,
pub max_width: Option<f64>,
pub max_height: Option<f64>,
pub tilt: f64,
pub align: TextAlign,
}
impl Default for TypesettingConfig {
fn default() -> Self {
Self {
font_size: 24.,
line_height_ratio: 1.2,
character_spacing: 0.,
max_width: None,
max_height: None,
tilt: 0.,
align: TextAlign::default(),
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/types.rs | node-graph/libraries/core-types/src/types.rs | use std::any::TypeId;
pub use std::borrow::Cow;
use std::fmt::{Display, Formatter};
use std::ops::Deref;
#[macro_export]
macro_rules! concrete {
($type:ty) => {
$crate::Type::Concrete($crate::TypeDescriptor {
id: Some(std::any::TypeId::of::<$type>()),
name: $crate::Cow::Borrowed(std::any::type_name::<$type>()),
alias: None,
size: std::mem::size_of::<$type>(),
align: std::mem::align_of::<$type>(),
})
};
($type:ty, $name:ty) => {
$crate::Type::Concrete($crate::TypeDescriptor {
id: Some(std::any::TypeId::of::<$type>()),
name: $crate::Cow::Borrowed(std::any::type_name::<$type>()),
alias: Some($crate::Cow::Borrowed(stringify!($name))),
size: std::mem::size_of::<$type>(),
align: std::mem::align_of::<$type>(),
})
};
}
#[macro_export]
macro_rules! concrete_with_name {
($type:ty, $name:expr_2021) => {
$crate::Type::Concrete($crate::TypeDescriptor {
id: Some(std::any::TypeId::of::<$type>()),
name: $crate::Cow::Borrowed($name),
alias: None,
size: std::mem::size_of::<$type>(),
align: std::mem::align_of::<$type>(),
})
};
}
#[macro_export]
macro_rules! generic {
($type:ty) => {{ $crate::Type::Generic($crate::Cow::Borrowed(stringify!($type))) }};
}
#[macro_export]
macro_rules! future {
($type:ty) => {{ $crate::Type::Future(Box::new(concrete!($type))) }};
($type:ty, $name:ty) => {
$crate::Type::Future(Box::new(concrete!($type, $name)))
};
}
#[macro_export]
macro_rules! fn_type {
($type:ty) => {
$crate::Type::Fn(Box::new(concrete!(())), Box::new(concrete!($type)))
};
($in_type:ty, $type:ty, alias: $outname:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(concrete!($type, $outname)))
};
($in_type:ty, $type:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(concrete!($type)))
};
}
#[macro_export]
macro_rules! fn_type_fut {
($type:ty) => {
$crate::Type::Fn(Box::new(concrete!(())), Box::new(future!($type)))
};
($in_type:ty, $type:ty, alias: $outname:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(future!($type, $outname)))
};
($in_type:ty, $type:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(future!($type)))
};
}
#[derive(Clone, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
pub struct NodeIOTypes {
pub call_argument: Type,
pub return_value: Type,
pub inputs: Vec<Type>,
}
impl NodeIOTypes {
pub const fn new(call_argument: Type, return_value: Type, inputs: Vec<Type>) -> Self {
Self { call_argument, return_value, inputs }
}
pub const fn empty() -> Self {
let tds1 = TypeDescriptor {
id: None,
name: Cow::Borrowed("()"),
alias: None,
size: 0,
align: 0,
};
let tds2 = TypeDescriptor {
id: None,
name: Cow::Borrowed("()"),
alias: None,
size: 0,
align: 0,
};
Self {
call_argument: Type::Concrete(tds1),
return_value: Type::Concrete(tds2),
inputs: Vec::new(),
}
}
pub fn ty(&self) -> Type {
Type::Fn(Box::new(self.call_argument.clone()), Box::new(self.return_value.clone()))
}
}
impl std::fmt::Debug for NodeIOTypes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"node({}) → {}",
[&self.call_argument].into_iter().chain(&self.inputs).map(|input| input.to_string()).collect::<Vec<_>>().join(", "),
self.return_value
))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, specta::Type, serde::Serialize, serde::Deserialize)]
pub struct ProtoNodeIdentifier {
pub name: Cow<'static, str>,
}
impl From<String> for ProtoNodeIdentifier {
fn from(value: String) -> Self {
Self { name: Cow::Owned(value) }
}
}
impl From<&'static str> for ProtoNodeIdentifier {
fn from(s: &'static str) -> Self {
ProtoNodeIdentifier { name: Cow::Borrowed(s) }
}
}
impl ProtoNodeIdentifier {
pub const fn new(name: &'static str) -> Self {
ProtoNodeIdentifier { name: Cow::Borrowed(name) }
}
pub const fn with_owned_string(name: String) -> Self {
ProtoNodeIdentifier { name: Cow::Owned(name) }
}
}
impl Deref for ProtoNodeIdentifier {
type Target = str;
fn deref(&self) -> &Self::Target {
self.name.as_ref()
}
}
impl Display for ProtoNodeIdentifier {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ProtoNodeIdentifier").field(&self.name).finish()
}
}
fn migrate_type_descriptor_names<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Cow<'static, str>, D::Error> {
use serde::Deserialize;
let name = String::deserialize(deserializer)?;
let name = match name.as_str() {
"f32" => "f64".to_string(),
"grahpene_core::transform::Footprint" => "std::option::Option<std::sync::Arc<grahpene_core::context::OwnedContextImpl>>".to_string(),
"grahpene_core::graphic_element::GraphicGroup" => "grahpene_core::table::Table<grahpene_core::graphic_types::Graphic>".to_string(),
"grahpene_core::raster::image::ImageFrame<Color>"
| "grahpene_core::raster::image::ImageFrame<grahpene_core::raster::color::Color>"
| "grahpene_core::instances::Instances<grahpene_core::raster::image::ImageFrame<Color>>"
| "grahpene_core::instances::Instances<grahpene_core::raster::image::ImageFrame<grahpene_core::raster::color::Color>>"
| "grahpene_core::instances::Instances<grahpene_core::raster::image::Image<grahpene_core::raster::color::Color>>" => {
"grahpene_core::table::Table<grahpene_core::raster::image::Image<grahpene_core::raster::color::Color>>".to_string()
}
"grahpene_core::vector::vector_data::VectorData"
| "grahpene_core::instances::Instances<grahpene_core::vector::vector_data::VectorData>"
| "grahpene_core::table::Table<grahpene_core::vector::vector_data::VectorData>"
| "grahpene_core::table::Table<grahpene_core::vector::vector_data::Vector>" => "grahpene_core::table::Table<grahpene_core::vector::vector_types::Vector>".to_string(),
"grahpene_core::instances::Instances<grahpene_core::graphic_element::Artboard>" => "grahpene_core::table::Table<grahpene_core::artboard::Artboard>".to_string(),
"grahpene_core::vector::vector_data::modification::VectorModification" => "grahpene_core::vector::vector_modification::VectorModification".to_string(),
"grahpene_core::table::Table<grahpene_core::graphic_element::Graphic>" => "grahpene_core::table::Table<grahpene_core::graphic_types::Graphic>".to_string(),
_ => name,
};
Ok(Cow::Owned(name))
}
#[derive(Clone, Debug, Eq, specta::Type, serde::Serialize, serde::Deserialize)]
pub struct TypeDescriptor {
#[serde(skip)]
#[specta(skip)]
pub id: Option<TypeId>,
#[serde(deserialize_with = "migrate_type_descriptor_names")]
pub name: Cow<'static, str>,
#[serde(default)]
pub alias: Option<Cow<'static, str>>,
#[serde(skip)]
pub size: usize,
#[serde(skip)]
pub align: usize,
}
impl std::hash::Hash for TypeDescriptor {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.name.hash(state);
}
}
impl std::fmt::Display for TypeDescriptor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let text = make_type_user_readable(&format_type(&self.name));
write!(f, "{text}")
}
}
impl PartialEq for TypeDescriptor {
fn eq(&self, other: &Self) -> bool {
match (self.id, other.id) {
(Some(id), Some(other_id)) => id == other_id,
_ => {
// TODO: Add a flag to disable this warning
// warn!("TypeDescriptor::eq: comparing types without ids based on name");
self.name == other.name
}
}
}
}
/// Graph runtime type information used for type inference.
#[derive(Clone, PartialEq, Eq, Hash, specta::Type, serde::Serialize, serde::Deserialize)]
pub enum Type {
/// A wrapper for some type variable used within the inference system. Resolved at inference time and replaced with a concrete type.
Generic(Cow<'static, str>),
/// A wrapper around the Rust type id for any concrete Rust type. Allows us to do equality comparisons, like checking if a String == a String.
Concrete(TypeDescriptor),
/// Runtime type information for a function. Given some input, gives some output.
Fn(Box<Type>, Box<Type>),
/// Represents a future which promises to return the inner type.
Future(Box<Type>),
}
impl Default for Type {
fn default() -> Self {
concrete!(())
}
}
unsafe impl dyn_any::StaticType for Type {
type Static = Self;
}
impl Type {
pub fn is_generic(&self) -> bool {
matches!(self, Type::Generic(_))
}
pub fn is_concrete(&self) -> bool {
matches!(self, Type::Concrete(_))
}
pub fn is_fn(&self) -> bool {
matches!(self, Type::Fn(_, _))
}
pub fn is_value(&self) -> bool {
matches!(self, Type::Fn(_, _) | Type::Concrete(_))
}
pub fn is_unit(&self) -> bool {
matches!(self, Type::Fn(_, _) | Type::Concrete(_))
}
pub fn is_generic_or_fn(&self) -> bool {
matches!(self, Type::Fn(_, _) | Type::Generic(_))
}
pub fn fn_input(&self) -> Option<&Type> {
match self {
Type::Fn(first, _) => Some(first),
_ => None,
}
}
pub fn fn_output(&self) -> Option<&Type> {
match self {
Type::Fn(_, second) => Some(second),
_ => None,
}
}
pub fn function(input: &Type, output: &Type) -> Type {
Type::Fn(Box::new(input.clone()), Box::new(output.clone()))
}
}
impl Type {
pub fn new<T: dyn_any::StaticType + Sized>() -> Self {
Self::Concrete(TypeDescriptor {
id: Some(TypeId::of::<T::Static>()),
name: Cow::Borrowed(std::any::type_name::<T::Static>()),
alias: None,
size: size_of::<T>(),
align: align_of::<T>(),
})
}
pub fn size(&self) -> Option<usize> {
match self {
Self::Generic(_) => None,
Self::Concrete(ty) => Some(ty.size),
Self::Fn(_, _) => None,
Self::Future(_) => None,
}
}
pub fn align(&self) -> Option<usize> {
match self {
Self::Generic(_) => None,
Self::Concrete(ty) => Some(ty.align),
Self::Fn(_, _) => None,
Self::Future(_) => None,
}
}
pub fn nested_type(&self) -> &Type {
match self {
Self::Generic(_) => self,
Self::Concrete(_) => self,
Self::Fn(_, output) => output.nested_type(),
Self::Future(output) => output.nested_type(),
}
}
pub fn replace_nested(&mut self, f: impl Fn(&Type) -> Option<Type>) -> Option<Type> {
if let Some(replacement) = f(self) {
return Some(std::mem::replace(self, replacement));
}
match self {
Self::Generic(_) => None,
Self::Concrete(_) => None,
Self::Fn(_, output) => output.replace_nested(f),
Self::Future(output) => output.replace_nested(f),
}
}
pub fn to_cow_string(&self) -> Cow<'static, str> {
match self {
Type::Generic(name) => name.clone(),
_ => Cow::Owned(self.to_string()),
}
}
}
pub fn format_type(ty: &str) -> String {
ty.split('<')
.map(|path| path.split(',').map(|path| path.split("::").last().unwrap_or(path)).collect::<Vec<_>>().join(","))
.collect::<Vec<_>>()
.join("<")
}
pub fn make_type_user_readable(ty: &str) -> String {
ty.replace("Option<Arc<OwnedContextImpl>>", "Context").replace("Vector<Option<Table<Graphic>>>", "Vector")
}
impl std::fmt::Debug for Type {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let text = match self {
Self::Generic(name) => name.to_string(),
#[cfg(feature = "type_id_logging")]
Self::Concrete(ty) => format!("Concrete<{}, {:?}>", ty.name, ty.id),
#[cfg(not(feature = "type_id_logging"))]
Self::Concrete(ty) => format_type(&ty.name),
Self::Fn(call_arg, return_value) => format!("{return_value:?} called with {call_arg:?}"),
Self::Future(ty) => format!("{ty:?}"),
};
let text = make_type_user_readable(&text);
write!(f, "{text}")
}
}
impl std::fmt::Display for Type {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let text = match self {
Type::Generic(name) => name.to_string(),
Type::Concrete(ty) => format_type(&ty.name),
Type::Fn(call_arg, return_value) => format!("{return_value} called with {call_arg}"),
Type::Future(ty) => ty.to_string(),
};
let text = make_type_user_readable(&text);
write!(f, "{text}")
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/registry.rs | node-graph/libraries/core-types/src/registry.rs | use crate::{ContextFeature, Node, NodeIO, NodeIOTypes, ProtoNodeIdentifier, Type, WasmNotSend};
use dyn_any::{DynAny, StaticType};
use std::collections::HashMap;
use std::marker::PhantomData;
use std::ops::Deref;
use std::pin::Pin;
use std::sync::{LazyLock, Mutex};
pub use no_std_types::registry::types;
// Translation struct between macro and definition
#[derive(Clone, Debug)]
pub struct NodeMetadata {
pub display_name: &'static str,
pub category: Option<&'static str>,
pub fields: Vec<FieldMetadata>,
pub description: &'static str,
pub properties: Option<&'static str>,
pub context_features: Vec<ContextFeature>,
}
// Translation struct between macro and definition
#[derive(Clone, Debug)]
pub struct FieldMetadata {
pub name: &'static str,
pub description: &'static str,
pub exposed: bool,
pub widget_override: RegistryWidgetOverride,
pub value_source: RegistryValueSource,
pub default_type: Option<Type>,
pub number_min: Option<f64>,
pub number_max: Option<f64>,
pub number_mode_range: Option<(f64, f64)>,
pub number_display_decimal_places: Option<u32>,
pub number_step: Option<f64>,
pub unit: Option<&'static str>,
}
#[derive(Clone, Debug)]
pub enum RegistryWidgetOverride {
None,
Hidden,
String(&'static str),
Custom(&'static str),
}
#[derive(Clone, Debug)]
pub enum RegistryValueSource {
None,
Default(&'static str),
Scope(&'static str),
}
type NodeRegistry = LazyLock<Mutex<HashMap<ProtoNodeIdentifier, Vec<(NodeConstructor, NodeIOTypes)>>>>;
pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::new()));
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
#[cfg(not(target_family = "wasm"))]
pub type DynFuture<'n, T> = Pin<Box<dyn Future<Output = T> + 'n + Send>>;
#[cfg(target_family = "wasm")]
pub type DynFuture<'n, T> = Pin<Box<dyn std::future::Future<Output = T> + 'n>>;
pub type LocalFuture<'n, T> = Pin<Box<dyn Future<Output = T> + 'n>>;
#[cfg(not(target_family = "wasm"))]
pub type Any<'n> = Box<dyn DynAny<'n> + 'n + Send>;
#[cfg(target_family = "wasm")]
pub type Any<'n> = Box<dyn DynAny<'n> + 'n>;
pub type FutureAny<'n> = DynFuture<'n, Any<'n>>;
// TODO: is this safe? This is assumed to be send+sync.
#[cfg(not(target_family = "wasm"))]
pub type TypeErasedNode<'n> = dyn for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + 'n + Send + Sync;
#[cfg(target_family = "wasm")]
pub type TypeErasedNode<'n> = dyn for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + 'n;
pub type TypeErasedPinnedRef<'n> = Pin<&'n TypeErasedNode<'n>>;
pub type TypeErasedRef<'n> = &'n TypeErasedNode<'n>;
pub type TypeErasedBox<'n> = Box<TypeErasedNode<'n>>;
pub type TypeErasedPinned<'n> = Pin<Box<TypeErasedNode<'n>>>;
pub type SharedNodeContainer = std::sync::Arc<NodeContainer>;
pub type NodeConstructor = fn(Vec<SharedNodeContainer>) -> DynFuture<'static, TypeErasedBox<'static>>;
#[derive(Clone)]
pub struct NodeContainer {
#[cfg(feature = "dealloc_nodes")]
pub node: *const TypeErasedNode<'static>,
#[cfg(not(feature = "dealloc_nodes"))]
pub node: TypeErasedRef<'static>,
}
impl Deref for NodeContainer {
type Target = TypeErasedNode<'static>;
#[cfg(feature = "dealloc_nodes")]
fn deref(&self) -> &Self::Target {
unsafe { &*(self.node) }
#[cfg(not(feature = "dealloc_nodes"))]
self.node
}
#[cfg(not(feature = "dealloc_nodes"))]
fn deref(&self) -> &Self::Target {
self.node
}
}
/// # Safety
/// Marks NodeContainer as Sync. This dissallows the use of threadlocal storage for nodes as this would invalidate references to them.
// TODO: implement this on a higher level wrapper to avoid missuse
#[cfg(feature = "dealloc_nodes")]
unsafe impl Send for NodeContainer {}
#[cfg(feature = "dealloc_nodes")]
unsafe impl Sync for NodeContainer {}
#[cfg(feature = "dealloc_nodes")]
impl Drop for NodeContainer {
fn drop(&mut self) {
unsafe { self.dealloc_unchecked() }
}
}
impl std::fmt::Debug for NodeContainer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NodeContainer").finish()
}
}
impl NodeContainer {
pub fn new(node: TypeErasedBox<'static>) -> SharedNodeContainer {
let node = Box::leak(node);
Self { node }.into()
}
#[cfg(feature = "dealloc_nodes")]
unsafe fn dealloc_unchecked(&mut self) {
unsafe {
drop(Box::from_raw(self.node as *mut TypeErasedNode));
}
}
}
/// Boxes the input and downcasts the output.
/// Wraps around a node taking Box<dyn DynAny> and returning Box<dyn DynAny>
#[derive(Clone)]
pub struct DowncastBothNode<I, O> {
node: SharedNodeContainer,
_i: PhantomData<I>,
_o: PhantomData<O>,
}
impl<'input, O, I> Node<'input, I> for DowncastBothNode<I, O>
where
O: 'input + StaticType + WasmNotSend,
I: 'input + StaticType + WasmNotSend,
{
type Output = DynFuture<'input, O>;
#[inline]
#[track_caller]
fn eval(&'input self, input: I) -> Self::Output {
{
let node_name = self.node.node_name();
let input = Box::new(input);
let future = self.node.eval(input);
Box::pin(async move {
let out = dyn_any::downcast(future.await).unwrap_or_else(|e| panic!("DowncastBothNode wrong output type: {e} in: \n{node_name}"));
*out
})
}
}
fn reset(&self) {
self.node.reset();
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
self.node.serialize()
}
}
impl<I, O> DowncastBothNode<I, O> {
pub const fn new(node: SharedNodeContainer) -> Self {
Self {
node,
_i: PhantomData,
_o: PhantomData,
}
}
}
pub struct FutureWrapperNode<Node> {
node: Node,
}
impl<'i, T: 'i + WasmNotSend, N> Node<'i, T> for FutureWrapperNode<N>
where
N: Node<'i, T, Output: WasmNotSend> + WasmNotSend,
{
type Output = DynFuture<'i, N::Output>;
#[inline(always)]
fn eval(&'i self, input: T) -> Self::Output {
let result = self.node.eval(input);
Box::pin(async move { result })
}
#[inline(always)]
fn reset(&self) {
self.node.reset();
}
#[inline(always)]
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
self.node.serialize()
}
}
impl<N> FutureWrapperNode<N> {
pub const fn new(node: N) -> Self {
Self { node }
}
}
pub struct DynAnyNode<I, O, Node> {
node: Node,
_i: PhantomData<I>,
_o: PhantomData<O>,
}
impl<'input, I, O, N> Node<'input, Any<'input>> for DynAnyNode<I, O, N>
where
I: 'input + StaticType + WasmNotSend,
O: 'input + StaticType + WasmNotSend,
N: 'input + Node<'input, I, Output = DynFuture<'input, O>>,
{
type Output = FutureAny<'input>;
#[inline]
fn eval(&'input self, input: Any<'input>) -> Self::Output {
let node_name = std::any::type_name::<N>();
let output = |input| {
let result = self.node.eval(input);
async move { Box::new(result.await) as Any<'input> }
};
match dyn_any::downcast(input) {
Ok(input) => Box::pin(output(*input)),
Err(e) => panic!("DynAnyNode Input, {e} in:\n{node_name}"),
}
}
fn reset(&self) {
self.node.reset();
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
self.node.serialize()
}
}
impl<'input, I, O, N> DynAnyNode<I, O, N>
where
I: 'input + StaticType,
O: 'input + StaticType,
N: 'input + Node<'input, I, Output = DynFuture<'input, O>>,
{
pub const fn new(node: N) -> Self {
Self {
node,
_i: PhantomData,
_o: PhantomData,
}
}
}
pub struct PanicNode<I: WasmNotSend, O: WasmNotSend>(PhantomData<I>, PhantomData<O>);
impl<'i, I: 'i + WasmNotSend, O: 'i + WasmNotSend> Node<'i, I> for PanicNode<I, O> {
type Output = O;
fn eval(&'i self, _: I) -> Self::Output {
unimplemented!("This node should never be evaluated")
}
}
impl<I: WasmNotSend, O: WasmNotSend> PanicNode<I, O> {
pub const fn new() -> Self {
Self(PhantomData, PhantomData)
}
}
impl<I: WasmNotSend, O: WasmNotSend> Default for PanicNode<I, O> {
fn default() -> Self {
Self::new()
}
}
// TODO: Evaluate safety
unsafe impl<I: WasmNotSend, O: WasmNotSend> Sync for PanicNode<I, O> {}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/render_complexity.rs | node-graph/libraries/core-types/src/render_complexity.rs | // Raster types moved to raster-types crate
use crate::Color;
use crate::table::Table;
pub trait RenderComplexity {
fn render_complexity(&self) -> usize {
0
}
}
impl<T: RenderComplexity> RenderComplexity for Table<T> {
fn render_complexity(&self) -> usize {
self.iter().map(|row| row.element.render_complexity()).fold(0, usize::saturating_add)
}
}
impl RenderComplexity for Color {
fn render_complexity(&self) -> usize {
1
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/memo.rs | node-graph/libraries/core-types/src/memo.rs | use std::hash::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::sync::Arc;
/// Stores both what a node was called with and what it returned.
#[derive(Clone, Debug)]
pub struct IORecord<I, O> {
pub input: I,
pub output: O,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct MemoHash<T: Hash> {
hash: u64,
value: Arc<T>,
}
impl<'de, T: serde::Deserialize<'de> + Hash> serde::Deserialize<'de> for MemoHash<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
T::deserialize(deserializer).map(|value| Self::new(value))
}
}
impl<T: Hash + serde::Serialize> serde::Serialize for MemoHash<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.value.serialize(serializer)
}
}
impl<T: Hash> MemoHash<T> {
pub fn new(value: T) -> Self {
let hash = Self::calc_hash(&value);
Self { hash, value: value.into() }
}
pub fn new_with_hash(value: T, hash: u64) -> Self {
Self { hash, value: value.into() }
}
fn calc_hash(data: &T) -> u64 {
let mut hasher = DefaultHasher::new();
data.hash(&mut hasher);
hasher.finish()
}
pub fn inner_mut(&mut self) -> MemoHashGuard<'_, T> {
MemoHashGuard { inner: self }
}
pub fn into_inner(self) -> Arc<T> {
self.value
}
pub fn hash_code(&self) -> u64 {
self.hash
}
}
impl<T: Hash> From<T> for MemoHash<T> {
fn from(value: T) -> Self {
Self::new(value)
}
}
impl<T: Hash> Hash for MemoHash<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.hash.hash(state)
}
}
impl<T: Hash> Deref for MemoHash<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.value
}
}
pub struct MemoHashGuard<'a, T: Hash> {
inner: &'a mut MemoHash<T>,
}
impl<T: Hash> Drop for MemoHashGuard<'_, T> {
fn drop(&mut self) {
let hash = MemoHash::<T>::calc_hash(&self.inner.value);
self.inner.hash = hash;
}
}
impl<T: Hash> Deref for MemoHashGuard<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner.value
}
}
impl<T: Hash + Clone> std::ops::DerefMut for MemoHashGuard<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
Arc::make_mut(&mut self.inner.value)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/context.rs | node-graph/libraries/core-types/src/context.rs | use crate::transform::Footprint;
use glam::DVec2;
pub use no_std_types::context::{ArcCtx, Ctx};
use std::any::Any;
use std::borrow::Borrow;
use std::hash::{Hash, Hasher};
use std::panic::Location;
use std::sync::Arc;
pub trait ExtractFootprint {
#[track_caller]
fn try_footprint(&self) -> Option<&Footprint>;
#[track_caller]
fn footprint(&self) -> &Footprint {
self.try_footprint().unwrap_or_else(|| {
log::error!("Context did not have a footprint, called from: {}", Location::caller());
&Footprint::DEFAULT
})
}
}
pub trait ExtractRealTime {
fn try_real_time(&self) -> Option<f64>;
}
pub trait ExtractAnimationTime {
fn try_animation_time(&self) -> Option<f64>;
}
pub trait ExtractPointer {
fn try_pointer(&self) -> Option<DVec2>;
}
pub trait ExtractIndex {
fn try_index(&self) -> Option<impl Iterator<Item = usize>>;
}
// Consider returning a slice or something like that
pub trait ExtractVarArgs {
fn vararg(&self, index: usize) -> Result<DynRef<'_>, VarArgsResult>;
fn varargs_len(&self) -> Result<usize, VarArgsResult>;
fn hash_varargs(&self, hasher: &mut dyn Hasher);
}
// Consider returning a slice or something like that
pub trait CloneVarArgs: ExtractVarArgs {
// fn box_clone(&self) -> Vec<DynBox>;
fn arc_clone(&self) -> Option<Arc<dyn ExtractVarArgs + Send + Sync>>;
}
// Inject* traits for providing context features to downstream nodes
pub trait InjectFootprint {}
pub trait InjectRealTime {}
pub trait InjectAnimationTime {}
pub trait InjectPointer {}
pub trait InjectIndex {}
pub trait InjectVarArgs {}
// Modify* marker traits for context-transparent nodes
pub trait ModifyFootprint: ExtractFootprint + InjectFootprint {}
pub trait ModifyRealTime: ExtractRealTime + InjectRealTime {}
pub trait ModifyAnimationTime: ExtractAnimationTime + InjectAnimationTime {}
pub trait ModifyPointer: ExtractPointer + InjectPointer {}
pub trait ModifyIndex: ExtractIndex + InjectIndex {}
pub trait ModifyVarArgs: ExtractVarArgs + InjectVarArgs {}
pub trait ExtractAll: ExtractFootprint + ExtractIndex + ExtractRealTime + ExtractAnimationTime + ExtractPointer + ExtractVarArgs {}
impl<T: ?Sized + ExtractFootprint + ExtractIndex + ExtractRealTime + ExtractAnimationTime + ExtractPointer + ExtractVarArgs> ExtractAll for T {}
impl<T: Ctx> InjectFootprint for T {}
impl<T: Ctx> InjectRealTime for T {}
impl<T: Ctx> InjectIndex for T {}
impl<T: Ctx> InjectAnimationTime for T {}
impl<T: Ctx> InjectPointer for T {}
impl<T: Ctx> InjectVarArgs for T {}
impl<T: Ctx + InjectFootprint + ExtractFootprint> ModifyFootprint for T {}
impl<T: Ctx + InjectRealTime + ExtractRealTime> ModifyRealTime for T {}
impl<T: Ctx + InjectIndex + ExtractIndex> ModifyIndex for T {}
impl<T: Ctx + InjectAnimationTime + ExtractAnimationTime> ModifyAnimationTime for T {}
impl<T: Ctx + InjectPointer + ExtractPointer> ModifyPointer for T {}
impl<T: Ctx + InjectVarArgs + ExtractVarArgs> ModifyVarArgs for T {}
// Public enum for flexible node macro codegen
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ContextFeature {
ExtractFootprint,
ExtractRealTime,
ExtractAnimationTime,
ExtractPointer,
ExtractIndex,
ExtractVarArgs,
InjectFootprint,
InjectRealTime,
InjectAnimationTime,
InjectPointer,
InjectIndex,
InjectVarArgs,
}
// Internal bitflags for fast compiler analysis
use bitflags::bitflags;
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, dyn_any::DynAny, serde::Serialize, serde::Deserialize, Default)]
pub struct ContextFeatures: u32 {
const FOOTPRINT = 1 << 0;
const REAL_TIME = 1 << 1;
const ANIMATION_TIME = 1 << 2;
const POINTER = 1 << 3;
const INDEX = 1 << 4;
const VARARGS = 1 << 5;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, dyn_any::DynAny, serde::Serialize, serde::Deserialize, Default)]
pub struct ContextDependencies {
pub extract: ContextFeatures,
pub inject: ContextFeatures,
}
impl From<&[ContextFeature]> for ContextDependencies {
fn from(features: &[ContextFeature]) -> Self {
let mut extract = ContextFeatures::empty();
let mut inject = ContextFeatures::empty();
for feature in features {
extract |= match feature {
ContextFeature::ExtractFootprint => ContextFeatures::FOOTPRINT,
ContextFeature::ExtractRealTime => ContextFeatures::REAL_TIME,
ContextFeature::ExtractAnimationTime => ContextFeatures::ANIMATION_TIME,
ContextFeature::ExtractPointer => ContextFeatures::POINTER,
ContextFeature::ExtractIndex => ContextFeatures::INDEX,
ContextFeature::ExtractVarArgs => ContextFeatures::VARARGS,
_ => ContextFeatures::empty(),
};
inject |= match feature {
ContextFeature::InjectFootprint => ContextFeatures::FOOTPRINT,
ContextFeature::InjectRealTime => ContextFeatures::REAL_TIME,
ContextFeature::InjectAnimationTime => ContextFeatures::ANIMATION_TIME,
ContextFeature::InjectPointer => ContextFeatures::POINTER,
ContextFeature::InjectIndex => ContextFeatures::INDEX,
ContextFeature::InjectVarArgs => ContextFeatures::VARARGS,
_ => ContextFeatures::empty(),
};
}
Self { extract, inject }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VarArgsResult {
IndexOutOfBounds,
NoVarArgs,
}
impl Ctx for Footprint {}
impl ExtractFootprint for () {
fn try_footprint(&self) -> Option<&Footprint> {
log::error!("tried to extract footprint form (), {}", Location::caller());
None
}
}
impl<T: ExtractFootprint + Ctx + Sync + Send> ExtractFootprint for &T {
fn try_footprint(&self) -> Option<&Footprint> {
(*self).try_footprint()
}
}
impl<T: ExtractFootprint + Sync> ExtractFootprint for Option<T> {
fn try_footprint(&self) -> Option<&Footprint> {
self.as_ref().and_then(|x| x.try_footprint())
}
#[track_caller]
fn footprint(&self) -> &Footprint {
self.try_footprint().unwrap_or_else(|| {
log::warn!("trying to extract footprint from context None {} ", Location::caller());
&Footprint::DEFAULT
})
}
}
impl<T: ExtractRealTime + Sync> ExtractRealTime for Option<T> {
fn try_real_time(&self) -> Option<f64> {
self.as_ref().and_then(|x| x.try_real_time())
}
}
impl<T: ExtractAnimationTime + Sync> ExtractAnimationTime for Option<T> {
fn try_animation_time(&self) -> Option<f64> {
self.as_ref().and_then(|x| x.try_animation_time())
}
}
impl<T: ExtractPointer + Sync> ExtractPointer for Option<T> {
fn try_pointer(&self) -> Option<DVec2> {
self.as_ref().and_then(|x| x.try_pointer())
}
}
impl<T: ExtractIndex> ExtractIndex for Option<T> {
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
self.as_ref().and_then(|x| x.try_index())
}
}
impl<T: ExtractVarArgs + Sync> ExtractVarArgs for Option<T> {
fn vararg(&self, index: usize) -> Result<DynRef<'_>, VarArgsResult> {
let Some(inner) = self else { return Err(VarArgsResult::NoVarArgs) };
inner.vararg(index)
}
fn varargs_len(&self) -> Result<usize, VarArgsResult> {
let Some(inner) = self else { return Err(VarArgsResult::NoVarArgs) };
inner.varargs_len()
}
fn hash_varargs(&self, hasher: &mut dyn Hasher) {
if let Some(inner) = self {
inner.hash_varargs(hasher)
}
}
}
impl<T: ExtractFootprint + Sync> ExtractFootprint for Arc<T> {
fn try_footprint(&self) -> Option<&Footprint> {
(**self).try_footprint()
}
}
impl<T: ExtractRealTime + Sync> ExtractRealTime for Arc<T> {
fn try_real_time(&self) -> Option<f64> {
(**self).try_real_time()
}
}
impl<T: ExtractAnimationTime + Sync> ExtractAnimationTime for Arc<T> {
fn try_animation_time(&self) -> Option<f64> {
(**self).try_animation_time()
}
}
impl<T: ExtractPointer + Sync> ExtractPointer for Arc<T> {
fn try_pointer(&self) -> Option<DVec2> {
(**self).try_pointer()
}
}
impl<T: ExtractIndex> ExtractIndex for Arc<T> {
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
(**self).try_index()
}
}
impl<T: ExtractVarArgs + Sync> ExtractVarArgs for Arc<T> {
fn vararg(&self, index: usize) -> Result<DynRef<'_>, VarArgsResult> {
(**self).vararg(index)
}
fn varargs_len(&self) -> Result<usize, VarArgsResult> {
(**self).varargs_len()
}
fn hash_varargs(&self, hasher: &mut dyn Hasher) {
(**self).hash_varargs(hasher)
}
}
impl<T: CloneVarArgs + Sync> CloneVarArgs for Option<T> {
fn arc_clone(&self) -> Option<Arc<dyn ExtractVarArgs + Send + Sync>> {
self.as_ref().and_then(CloneVarArgs::arc_clone)
}
}
impl<T: ExtractVarArgs + Sync> ExtractVarArgs for &T {
fn vararg(&self, index: usize) -> Result<DynRef<'_>, VarArgsResult> {
(*self).vararg(index)
}
fn varargs_len(&self) -> Result<usize, VarArgsResult> {
(*self).varargs_len()
}
fn hash_varargs(&self, hasher: &mut dyn Hasher) {
(*self).hash_varargs(hasher)
}
}
impl<T: CloneVarArgs + Sync> CloneVarArgs for Arc<T> {
fn arc_clone(&self) -> Option<Arc<dyn ExtractVarArgs + Send + Sync>> {
(**self).arc_clone()
}
}
impl Ctx for ContextImpl<'_> {}
impl ArcCtx for OwnedContextImpl {}
impl ExtractFootprint for ContextImpl<'_> {
fn try_footprint(&self) -> Option<&Footprint> {
self.footprint
}
}
impl ExtractRealTime for ContextImpl<'_> {
fn try_real_time(&self) -> Option<f64> {
self.real_time
}
}
impl ExtractIndex for ContextImpl<'_> {
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
self.index.clone().map(|x| x.into_iter())
}
}
impl ExtractVarArgs for ContextImpl<'_> {
fn vararg(&self, index: usize) -> Result<DynRef<'_>, VarArgsResult> {
let Some(inner) = self.varargs else { return Err(VarArgsResult::NoVarArgs) };
inner.get(index).ok_or(VarArgsResult::IndexOutOfBounds).copied()
}
fn varargs_len(&self) -> Result<usize, VarArgsResult> {
let Some(inner) = self.varargs else { return Err(VarArgsResult::NoVarArgs) };
Ok(inner.len())
}
fn hash_varargs(&self, _hasher: &mut dyn Hasher) {
todo!()
}
}
impl ExtractFootprint for OwnedContextImpl {
fn try_footprint(&self) -> Option<&Footprint> {
self.footprint.as_ref()
}
}
impl ExtractRealTime for OwnedContextImpl {
fn try_real_time(&self) -> Option<f64> {
self.real_time
}
}
impl ExtractAnimationTime for OwnedContextImpl {
fn try_animation_time(&self) -> Option<f64> {
self.animation_time
}
}
impl ExtractPointer for OwnedContextImpl {
fn try_pointer(&self) -> Option<DVec2> {
self.pointer
}
}
impl ExtractIndex for OwnedContextImpl {
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
self.index.clone().map(|x| x.into_iter().rev())
}
}
impl ExtractVarArgs for OwnedContextImpl {
fn vararg(&self, index: usize) -> Result<DynRef<'_>, VarArgsResult> {
let Some(ref inner) = self.varargs else {
let Some(ref parent) = self.parent else {
return Err(VarArgsResult::NoVarArgs);
};
return parent.vararg(index);
};
inner.get(index).map(|x| x.as_ref() as DynRef<'_>).ok_or(VarArgsResult::IndexOutOfBounds)
}
fn varargs_len(&self) -> Result<usize, VarArgsResult> {
let Some(ref inner) = self.varargs else {
let Some(ref parent) = self.parent else {
return Err(VarArgsResult::NoVarArgs);
};
return parent.varargs_len();
};
Ok(inner.len())
}
fn hash_varargs(&self, mut hasher: &mut dyn Hasher) {
match (&self.varargs, &self.parent) {
(Some(inner), _) => {
for arg in inner.iter() {
arg.hash(&mut hasher);
}
}
(None, Some(parent)) => {
parent.hash_varargs(hasher);
}
_ => (),
};
}
}
impl CloneVarArgs for Arc<OwnedContextImpl> {
fn arc_clone(&self) -> Option<Arc<dyn ExtractVarArgs + Send + Sync>> {
Some(self.clone())
}
}
pub type Context<'a> = Option<Arc<OwnedContextImpl>>;
type DynRef<'a> = &'a (dyn Any + Send + Sync);
type DynBox = Box<dyn AnyHash + Send + Sync>;
#[derive(dyn_any::DynAny)]
pub struct OwnedContextImpl {
footprint: Option<Footprint>,
varargs: Option<Arc<[DynBox]>>,
parent: Option<Arc<dyn ExtractVarArgs + Sync + Send>>,
// This could be converted into a single enum to save extra bytes
index: Option<Vec<usize>>,
real_time: Option<f64>,
animation_time: Option<f64>,
pointer: Option<DVec2>,
}
impl std::fmt::Debug for OwnedContextImpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OwnedContextImpl")
.field("footprint", &self.footprint)
.field("varargs_len", &self.varargs.as_ref().map(|x| x.len()))
.field("parent", &self.parent.as_ref().map(|_| "<Parent>"))
.field("index", &self.index)
.field("real_time", &self.real_time)
.field("animation_time", &self.animation_time)
.field("pointer", &self.pointer)
.finish()
}
}
impl Default for OwnedContextImpl {
#[track_caller]
fn default() -> Self {
Self::empty()
}
}
impl Hash for OwnedContextImpl {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.footprint.hash(state);
self.hash_varargs(state);
self.index.hash(state);
self.real_time.map(|x| x.to_bits()).hash(state);
self.animation_time.map(|x| x.to_bits()).hash(state);
self.pointer.map(|v| (v.x.to_bits(), v.y.to_bits())).hash(state);
}
}
impl OwnedContextImpl {
#[track_caller]
pub fn from<T: ExtractAll + CloneVarArgs>(value: T) -> Self {
OwnedContextImpl::from_flags(value, ContextFeatures::all())
}
#[track_caller]
pub fn from_flags<T: ExtractAll + CloneVarArgs>(value: T, bitflags: ContextFeatures) -> Self {
let footprint = bitflags.contains(ContextFeatures::FOOTPRINT).then(|| value.try_footprint().copied()).flatten();
let index = bitflags.contains(ContextFeatures::INDEX).then(|| value.try_index()).flatten();
let real_time = bitflags.contains(ContextFeatures::REAL_TIME).then(|| value.try_real_time()).flatten();
let animation_time = bitflags.contains(ContextFeatures::ANIMATION_TIME).then(|| value.try_animation_time()).flatten();
let pointer = bitflags.contains(ContextFeatures::POINTER).then(|| value.try_pointer()).flatten();
let parent = bitflags
.contains(ContextFeatures::VARARGS)
.then(|| match value.varargs_len() {
Ok(x) if x > 0 => value.arc_clone(),
_ => None,
})
.flatten();
OwnedContextImpl {
footprint,
varargs: None,
parent,
index: index.map(|x| x.collect()),
real_time,
animation_time,
pointer,
}
}
pub const fn empty() -> Self {
OwnedContextImpl {
footprint: None,
varargs: None,
parent: None,
index: None,
real_time: None,
animation_time: None,
pointer: None,
}
}
}
pub trait DynHash {
fn dyn_hash(&self, state: &mut dyn Hasher);
}
impl<H: Hash + ?Sized> DynHash for H {
fn dyn_hash(&self, mut state: &mut dyn Hasher) {
self.hash(&mut state);
}
}
impl Hash for dyn AnyHash {
fn hash<H: Hasher>(&self, state: &mut H) {
self.dyn_hash(state);
}
}
impl Hash for Box<dyn AnyHash + Send + Sync> {
fn hash<H: Hasher>(&self, state: &mut H) {
(**self).dyn_hash(state);
}
}
pub trait AnyHash: DynHash + Any {}
impl<T: DynHash + Any> AnyHash for T {}
impl OwnedContextImpl {
pub fn set_footprint(&mut self, footprint: Footprint) {
self.footprint = Some(footprint);
}
pub fn with_footprint(mut self, footprint: Footprint) -> Self {
self.footprint = Some(footprint);
self
}
pub fn with_real_time(mut self, real_time: f64) -> Self {
self.real_time = Some(real_time);
self
}
pub fn with_animation_time(mut self, animation_time: f64) -> Self {
self.animation_time = Some(animation_time);
self
}
pub fn with_pointer(mut self, pointer: DVec2) -> Self {
self.pointer = Some(pointer);
self
}
pub fn with_vararg(mut self, value: Box<dyn AnyHash + Send + Sync>) -> Self {
assert!(self.varargs.is_none_or(|value| value.is_empty()));
self.varargs = Some(Arc::new([value]));
self
}
pub fn with_index(mut self, index: usize) -> Self {
if let Some(current_index) = &mut self.index {
current_index.push(index);
} else {
self.index = Some(vec![index]);
}
self
}
pub fn into_context(self) -> Option<Arc<Self>> {
Some(Arc::new(self))
}
pub fn erase_parent(mut self) -> Self {
self.parent = None;
self
}
}
#[derive(Default, Clone, dyn_any::DynAny)]
pub struct ContextImpl<'a> {
pub(crate) footprint: Option<&'a Footprint>,
varargs: Option<&'a [DynRef<'a>]>,
index: Option<Vec<usize>>, // This could be converted into a single enum to save extra bytes
real_time: Option<f64>,
}
impl<'a> ContextImpl<'a> {
pub fn with_footprint<'f>(&self, new_footprint: &'f Footprint, varargs: Option<&'f impl Borrow<[DynRef<'f>]>>) -> ContextImpl<'f>
where
'a: 'f,
{
ContextImpl {
footprint: Some(new_footprint),
varargs: varargs.map(|x| x.borrow()),
index: self.index.clone(),
..*self
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/generic.rs | node-graph/libraries/core-types/src/generic.rs | use crate::Node;
use std::marker::PhantomData;
#[derive(Clone)]
pub struct FnNode<T: Fn(I) -> O, I, O>(T, PhantomData<(I, O)>);
impl<'i, T: Fn(I) -> O + 'i, O: 'i, I: 'i> Node<'i, I> for FnNode<T, I, O> {
type Output = O;
fn eval(&'i self, input: I) -> Self::Output {
self.0(input)
}
}
impl<T: Fn(I) -> O, I, O> FnNode<T, I, O> {
pub fn new(f: T) -> Self {
FnNode(f, PhantomData)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/ops.rs | node-graph/libraries/core-types/src/ops.rs | use crate::Node;
use crate::table::{Table, TableRow};
use crate::transform::Footprint;
use glam::DVec2;
use std::future::Future;
use std::marker::PhantomData;
// Type
// TODO: Document this
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct TypeNode<N: for<'a> Node<'a, I>, I, O>(pub N, pub PhantomData<(I, O)>);
impl<'i, N, I: 'i, O: 'i> Node<'i, I> for TypeNode<N, I, O>
where
N: for<'n> Node<'n, I, Output = O>,
{
type Output = O;
fn eval(&'i self, input: I) -> Self::Output {
self.0.eval(input)
}
fn reset(&self) {
self.0.reset();
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
self.0.serialize()
}
}
impl<'i, N: for<'a> Node<'a, I>, I: 'i> TypeNode<N, I, <N as Node<'i, I>>::Output> {
pub fn new(node: N) -> Self {
Self(node, PhantomData)
}
}
impl<'i, N: for<'a> Node<'a, I> + Clone, I: 'i> Clone for TypeNode<N, I, <N as Node<'i, I>>::Output> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1)
}
}
impl<'i, N: for<'a> Node<'a, I> + Copy, I: 'i> Copy for TypeNode<N, I, <N as Node<'i, I>>::Output> {}
/// The [`Convert`] trait allows for conversion between Rust primitive numeric types.
/// Because number casting is lossy, we cannot use the normal [`Into`] trait like we do for other types.
pub trait Convert<T, C>: Sized {
/// Converts this type into the (usually inferred) output type.
#[must_use]
fn convert(self, footprint: Footprint, converter: C) -> impl Future<Output = T> + Send;
}
impl<T: ToString + Send> Convert<String, ()> for T {
/// Converts this type into a `String` using its `ToString` implementation.
#[inline]
async fn convert(self, _: Footprint, _converter: ()) -> String {
self.to_string()
}
}
pub trait TableConvert<U> {
fn convert_row(self) -> U;
}
impl<U, T: TableConvert<U> + Send> Convert<Table<U>, ()> for Table<T> {
async fn convert(self, _: Footprint, _: ()) -> Table<U> {
let table: Table<U> = self
.into_iter()
.map(|row| TableRow {
element: row.element.convert_row(),
transform: row.transform,
alpha_blending: row.alpha_blending,
source_node_id: row.source_node_id,
})
.collect();
table
}
}
impl Convert<DVec2, ()> for DVec2 {
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
self
}
}
// TODO: Add a DVec2 to Table<Vector> anchor point conversion implementation to replace the 'Vec2 to Point' node
/// Implements the [`Convert`] trait for conversion between the cartesian product of Rust's primitive numeric types.
macro_rules! impl_convert {
($from:ty, $to:ty) => {
impl Convert<$to, ()> for $from {
async fn convert(self, _: Footprint, _: ()) -> $to {
self as $to
}
}
};
($to:ty) => {
impl_convert!(f32, $to);
impl_convert!(f64, $to);
impl_convert!(i8, $to);
impl_convert!(u8, $to);
impl_convert!(u16, $to);
impl_convert!(i16, $to);
impl_convert!(i32, $to);
impl_convert!(u32, $to);
impl_convert!(i64, $to);
impl_convert!(u64, $to);
impl_convert!(i128, $to);
impl_convert!(u128, $to);
impl_convert!(isize, $to);
impl_convert!(usize, $to);
impl Convert<DVec2, ()> for $to {
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
DVec2::splat(self as f64)
}
}
};
}
impl_convert!(f32);
impl_convert!(f64);
impl_convert!(i8);
impl_convert!(u8);
impl_convert!(u16);
impl_convert!(i16);
impl_convert!(i32);
impl_convert!(u32);
impl_convert!(i64);
impl_convert!(u64);
impl_convert!(i128);
impl_convert!(u128);
impl_convert!(isize);
impl_convert!(usize);
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/uuid.rs | node-graph/libraries/core-types/src/uuid.rs | use dyn_any::DynAny;
pub use uuid_generation::*;
#[derive(Clone, Copy, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct Uuid(
#[serde(with = "u64_string")]
#[specta(type = String)]
u64,
);
mod u64_string {
use serde::{self, Deserialize, Deserializer, Serializer};
use std::str::FromStr;
// The signature of a serialize_with function must follow the pattern:
//
// fn serialize<S>(&T, S) -> Result<S::Ok, S::Error>
// where
// S: Serializer
//
// although it may also be generic over the input types T.
pub fn serialize<S>(value: &u64, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&value.to_string())
}
// The signature of a deserialize_with function must follow the pattern:
//
// fn deserialize<'de, D>(D) -> Result<T, D::Error>
// where
// D: Deserializer<'de>
//
// although it may also be generic over the output types T.
pub fn deserialize<'de, D>(deserializer: D) -> Result<u64, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
u64::from_str(&s).map_err(serde::de::Error::custom)
}
}
mod uuid_generation {
use rand_chacha::ChaCha20Rng;
use rand_chacha::rand_core::{RngCore, SeedableRng};
use std::cell::Cell;
use std::sync::Mutex;
static RNG: Mutex<Option<ChaCha20Rng>> = Mutex::new(None);
thread_local! {
pub static UUID_SEED: Cell<Option<u64>> = const { Cell::new(None) };
}
pub fn set_uuid_seed(random_seed: u64) {
UUID_SEED.with(|seed| seed.set(Some(random_seed)))
}
pub fn generate_uuid() -> u64 {
let Ok(mut lock) = RNG.lock() else { panic!("UUID mutex poisoned") };
if lock.is_none() {
UUID_SEED.with(|seed| {
let random_seed = seed.get().unwrap_or(42);
*lock = Some(ChaCha20Rng::seed_from_u64(random_seed));
})
}
lock.as_mut().map(ChaCha20Rng::next_u64).expect("UUID mutex poisoned")
}
}
#[repr(transparent)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize, specta::Type, DynAny)]
pub struct NodeId(pub u64);
impl NodeId {
pub fn new() -> Self {
Self(generate_uuid())
}
}
impl std::fmt::Display for NodeId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/math/polynomial.rs | node-graph/libraries/core-types/src/math/polynomial.rs | use kurbo::PathSeg;
use std::fmt::{self, Display, Formatter};
use std::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
/// A struct that represents a polynomial with a maximum degree of `N-1`.
///
/// It provides basic mathematical operations for polynomials like addition, multiplication, differentiation, integration, etc.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Polynomial<const N: usize> {
coefficients: [f64; N],
}
impl<const N: usize> Polynomial<N> {
/// Create a new polynomial from the coefficients given in the array.
///
/// The coefficient for nth degree is at the nth index in array. Therefore the order of coefficients are reversed than the usual order for writing polynomials mathematically.
pub fn new(coefficients: [f64; N]) -> Polynomial<N> {
Polynomial { coefficients }
}
/// Create a polynomial where all its coefficients are zero.
pub fn zero() -> Polynomial<N> {
Polynomial { coefficients: [0.; N] }
}
/// Return an immutable reference to the coefficients.
///
/// The coefficient for nth degree is at the nth index in array. Therefore the order of coefficients are reversed than the usual order for writing polynomials mathematically.
pub fn coefficients(&self) -> &[f64; N] {
&self.coefficients
}
/// Return a mutable reference to the coefficients.
///
/// The coefficient for nth degree is at the nth index in array. Therefore the order of coefficients are reversed than the usual order for writing polynomials mathematically.
pub fn coefficients_mut(&mut self) -> &mut [f64; N] {
&mut self.coefficients
}
/// Evaluate the polynomial at `value`.
pub fn eval(&self, value: f64) -> f64 {
self.coefficients.iter().rev().copied().reduce(|acc, x| acc * value + x).unwrap()
}
/// Return the same polynomial but with a different maximum degree of `M-1`.\
///
/// Returns `None` if the polynomial cannot fit in the specified size.
pub fn as_size<const M: usize>(&self) -> Option<Polynomial<M>> {
let mut coefficients = [0.; M];
if M >= N {
coefficients[..N].copy_from_slice(&self.coefficients);
} else if self.coefficients.iter().rev().take(N - M).all(|&x| x == 0.) {
coefficients.copy_from_slice(&self.coefficients[..M])
} else {
return None;
}
Some(Polynomial { coefficients })
}
/// Computes the derivative in place.
pub fn derivative_mut(&mut self) {
self.coefficients.iter_mut().enumerate().for_each(|(index, x)| *x *= index as f64);
self.coefficients.rotate_left(1);
}
/// Computes the antiderivative at `C = 0` in place.
///
/// Returns `None` if the polynomial is not big enough to accommodate the extra degree.
pub fn antiderivative_mut(&mut self) -> Option<()> {
if self.coefficients[N - 1] != 0. {
return None;
}
self.coefficients.rotate_right(1);
self.coefficients.iter_mut().enumerate().skip(1).for_each(|(index, x)| *x /= index as f64);
Some(())
}
/// Computes the polynomial's derivative.
pub fn derivative(&self) -> Polynomial<N> {
let mut ans = *self;
ans.derivative_mut();
ans
}
/// Computes the antiderivative at `C = 0`.
///
/// Returns `None` if the polynomial is not big enough to accommodate the extra degree.
pub fn antiderivative(&self) -> Option<Polynomial<N>> {
let mut ans = *self;
ans.antiderivative_mut()?;
Some(ans)
}
}
impl<const N: usize> Default for Polynomial<N> {
fn default() -> Self {
Self::zero()
}
}
impl<const N: usize> Display for Polynomial<N> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut first = true;
for (index, coefficient) in self.coefficients.iter().enumerate().rev().filter(|&(_, &coefficient)| coefficient != 0.) {
if first {
first = false;
} else {
f.write_str(" + ")?
}
coefficient.fmt(f)?;
if index == 0 {
continue;
}
f.write_str("x")?;
if index == 1 {
continue;
}
f.write_str("^")?;
index.fmt(f)?;
}
Ok(())
}
}
impl<const N: usize> AddAssign<&Polynomial<N>> for Polynomial<N> {
fn add_assign(&mut self, rhs: &Polynomial<N>) {
self.coefficients.iter_mut().zip(rhs.coefficients.iter()).for_each(|(a, b)| *a += b);
}
}
impl<const N: usize> Add for &Polynomial<N> {
type Output = Polynomial<N>;
fn add(self, other: &Polynomial<N>) -> Polynomial<N> {
let mut output = *self;
output += other;
output
}
}
impl<const N: usize> Neg for &Polynomial<N> {
type Output = Polynomial<N>;
fn neg(self) -> Polynomial<N> {
let mut output = *self;
output.coefficients.iter_mut().for_each(|x| *x = -*x);
output
}
}
impl<const N: usize> Neg for Polynomial<N> {
type Output = Polynomial<N>;
fn neg(mut self) -> Polynomial<N> {
self.coefficients.iter_mut().for_each(|x| *x = -*x);
self
}
}
impl<const N: usize> SubAssign<&Polynomial<N>> for Polynomial<N> {
fn sub_assign(&mut self, rhs: &Polynomial<N>) {
self.coefficients.iter_mut().zip(rhs.coefficients.iter()).for_each(|(a, b)| *a -= b);
}
}
impl<const N: usize> Sub for &Polynomial<N> {
type Output = Polynomial<N>;
fn sub(self, other: &Polynomial<N>) -> Polynomial<N> {
let mut output = *self;
output -= other;
output
}
}
impl<const N: usize> MulAssign<&Polynomial<N>> for Polynomial<N> {
fn mul_assign(&mut self, rhs: &Polynomial<N>) {
for i in (0..N).rev() {
self.coefficients[i] = self.coefficients[i] * rhs.coefficients[0];
for j in 0..i {
self.coefficients[i] += self.coefficients[j] * rhs.coefficients[i - j];
}
}
}
}
impl<const N: usize> Mul for &Polynomial<N> {
type Output = Polynomial<N>;
fn mul(self, other: &Polynomial<N>) -> Polynomial<N> {
let mut output = *self;
output *= other;
output
}
}
/// Returns two [`Polynomial`]s representing the parametric equations for x and y coordinates of the bezier curve respectively.
/// The domain of both the equations are from t=0.0 representing the start and t=1.0 representing the end of the bezier curve.
pub fn pathseg_to_parametric_polynomial(segment: PathSeg) -> (Polynomial<4>, Polynomial<4>) {
match segment {
PathSeg::Line(line) => {
let term1 = line.p1 - line.p0;
(Polynomial::new([line.p0.x, term1.x, 0., 0.]), Polynomial::new([line.p0.y, term1.y, 0., 0.]))
}
PathSeg::Quad(quad_bez) => {
let term1 = 2. * (quad_bez.p1 - quad_bez.p0);
let term2 = quad_bez.p0 - 2. * quad_bez.p1.to_vec2() + quad_bez.p2.to_vec2();
(Polynomial::new([quad_bez.p0.x, term1.x, term2.x, 0.]), Polynomial::new([quad_bez.p0.y, term1.y, term2.y, 0.]))
}
PathSeg::Cubic(cubic_bez) => {
let term1 = 3. * (cubic_bez.p1 - cubic_bez.p0);
let term2 = 3. * (cubic_bez.p2 - cubic_bez.p1) - term1;
let term3 = cubic_bez.p3 - cubic_bez.p0 - term2 - term1;
(
Polynomial::new([cubic_bez.p0.x, term1.x, term2.x, term3.x]),
Polynomial::new([cubic_bez.p0.y, term1.y, term2.y, term3.y]),
)
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn evaluation() {
let p = Polynomial::new([1., 2., 3.]);
assert_eq!(p.eval(1.), 6.);
assert_eq!(p.eval(2.), 17.);
}
#[test]
fn size_change() {
let p1 = Polynomial::new([1., 2., 3.]);
let p2 = Polynomial::new([1., 2., 3., 0.]);
assert_eq!(p1.as_size(), Some(p2));
assert_eq!(p2.as_size(), Some(p1));
assert_eq!(p2.as_size::<2>(), None);
}
#[test]
fn addition_and_subtaction() {
let p1 = Polynomial::new([1., 2., 3.]);
let p2 = Polynomial::new([4., 5., 6.]);
let addition = Polynomial::new([5., 7., 9.]);
let subtraction = Polynomial::new([-3., -3., -3.]);
assert_eq!(&p1 + &p2, addition);
assert_eq!(&p1 - &p2, subtraction);
}
#[test]
fn multiplication() {
let p1 = Polynomial::new([1., 2., 3.]).as_size().unwrap();
let p2 = Polynomial::new([4., 5., 6.]).as_size().unwrap();
let multiplication = Polynomial::new([4., 13., 28., 27., 18.]);
assert_eq!(&p1 * &p2, multiplication);
}
#[test]
fn derivative_and_antiderivative() {
let mut p = Polynomial::new([1., 2., 3.]);
let p_deriv = Polynomial::new([2., 6., 0.]);
assert_eq!(p.derivative(), p_deriv);
p.coefficients_mut()[0] = 0.;
assert_eq!(p_deriv.antiderivative().unwrap(), p);
assert_eq!(p.antiderivative(), None);
}
#[test]
fn display() {
let p = Polynomial::new([1., 2., 0., 3.]);
assert_eq!(format!("{p:.2}"), "3.00x^3 + 2.00x + 1.00");
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/math/rect.rs | node-graph/libraries/core-types/src/math/rect.rs | use crate::math::quad::Quad;
use glam::{DAffine2, DVec2};
#[derive(Debug, Clone, Default, Copy, PartialEq)]
/// An axis aligned rect defined by two vertices.
pub struct Rect(pub [DVec2; 2]);
impl Rect {
/// Create a zero sized quad at the point
#[must_use]
pub fn from_point(point: DVec2) -> Self {
Self([point; 2])
}
/// Convert a box defined by two corner points to a quad.
#[must_use]
pub fn from_box(bbox: [DVec2; 2]) -> Self {
Self([bbox[0].min(bbox[1]), bbox[0].max(bbox[1])])
}
/// Create a quad from the center and offset (distance from center to middle of an edge)
#[must_use]
pub fn from_square(center: DVec2, offset: f64) -> Self {
Self::from_box([center - offset, center + offset])
}
/// Create an AABB from an iter of points, returning None if empty.
#[must_use]
pub fn point_iter(points: impl Iterator<Item = DVec2>) -> Option<Self> {
let mut bounds = None;
for point in points {
let bounds = bounds.get_or_insert(Self::from_point(point));
bounds[0] = bounds[0].min(point);
bounds[1] = bounds[1].max(point);
}
bounds
}
/// Get all the edges in the rect.
#[must_use]
pub fn edges(&self) -> [[DVec2; 2]; 4] {
let corners = [self[0], DVec2::new(self[0].x, self[1].y), self[1], DVec2::new(self[1].y, self[0].x)];
[[corners[0], corners[1]], [corners[1], corners[2]], [corners[2], corners[3]], [corners[3], corners[0]]]
}
/// Gets the center of a rect
#[must_use]
pub fn center(&self) -> DVec2 {
self.0.iter().sum::<DVec2>() / 2.
}
/// Take the outside bounds of two axis aligned rectangles, which are defined by two corner points.
#[must_use]
pub fn combine_bounds(a: Self, b: Self) -> Self {
Self::from_box([a[0].min(b[0]), a[1].max(b[1])])
}
/// Expand a rect by a certain amount on top/bottom and on left/right
#[must_use]
pub fn expand_by(&self, x: f64, y: f64) -> Self {
let delta = DVec2::new(x, y);
Self::from_box([self[0] - delta, self[1] + delta])
}
/// Checks if two rects intersect
#[must_use]
pub fn intersects(&self, other: Self) -> bool {
let [mina, maxa] = [self[0].min(self[1]), self[0].max(self[1])];
let [minb, maxb] = [other[0].min(other[1]), other[0].max(other[1])];
mina.x <= maxb.x && minb.x <= maxa.x && mina.y <= maxb.y && minb.y <= maxa.y
}
/// Does this rect contain a point
#[must_use]
pub fn contains(&self, p: DVec2) -> bool {
(self[0].x < p.x && p.x < self[1].x) && (self[0].y < p.y && p.y < self[1].y)
}
#[must_use]
pub fn min(&self) -> DVec2 {
self.0[0].min(self.0[1])
}
#[must_use]
pub fn max(&self) -> DVec2 {
self.0[0].max(self.0[1])
}
#[must_use]
pub fn translate(&self, offset: DVec2) -> Self {
Self([self.0[0] + offset, self.0[1] + offset])
}
}
impl std::ops::Mul<Rect> for DAffine2 {
type Output = Quad;
fn mul(self, rhs: Rect) -> Self::Output {
self * Quad::from_box(rhs.0)
}
}
impl std::ops::Index<usize> for Rect {
type Output = DVec2;
fn index(&self, index: usize) -> &Self::Output {
&self.0[index]
}
}
impl std::ops::IndexMut<usize> for Rect {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.0[index]
}
}
impl From<Rect> for Quad {
fn from(val: Rect) -> Self {
Quad::from_box(val.0)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/math/bbox.rs | node-graph/libraries/core-types/src/math/bbox.rs | use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
#[derive(Clone, Debug, DynAny)]
pub struct AxisAlignedBbox {
pub start: DVec2,
pub end: DVec2,
}
impl AxisAlignedBbox {
pub const ZERO: Self = Self { start: DVec2::ZERO, end: DVec2::ZERO };
pub const ONE: Self = Self { start: DVec2::ZERO, end: DVec2::ONE };
pub fn size(&self) -> DVec2 {
self.end - self.start
}
pub fn to_transform(&self) -> DAffine2 {
DAffine2::from_translation(self.start) * DAffine2::from_scale(self.size())
}
pub fn contains(&self, point: DVec2) -> bool {
point.x >= self.start.x && point.x <= self.end.x && point.y >= self.start.y && point.y <= self.end.y
}
pub fn intersects(&self, other: &AxisAlignedBbox) -> bool {
other.start.x <= self.end.x && other.end.x >= self.start.x && other.start.y <= self.end.y && other.end.y >= self.start.y
}
pub fn union(&self, other: &AxisAlignedBbox) -> AxisAlignedBbox {
AxisAlignedBbox {
start: DVec2::new(self.start.x.min(other.start.x), self.start.y.min(other.start.y)),
end: DVec2::new(self.end.x.max(other.end.x), self.end.y.max(other.end.y)),
}
}
pub fn union_non_empty(&self, other: &AxisAlignedBbox) -> Option<AxisAlignedBbox> {
match (self.size() == DVec2::ZERO, other.size() == DVec2::ZERO) {
(true, true) => None,
(true, _) => Some(other.clone()),
(_, true) => Some(self.clone()),
_ => Some(AxisAlignedBbox {
start: DVec2::new(self.start.x.min(other.start.x), self.start.y.min(other.start.y)),
end: DVec2::new(self.end.x.max(other.end.x), self.end.y.max(other.end.y)),
}),
}
}
pub fn intersect(&self, other: &AxisAlignedBbox) -> AxisAlignedBbox {
AxisAlignedBbox {
start: DVec2::new(self.start.x.max(other.start.x), self.start.y.max(other.start.y)),
end: DVec2::new(self.end.x.min(other.end.x), self.end.y.min(other.end.y)),
}
}
}
impl From<(DVec2, DVec2)> for AxisAlignedBbox {
fn from((start, end): (DVec2, DVec2)) -> Self {
Self { start, end }
}
}
#[derive(Clone, Debug)]
pub struct Bbox {
pub top_left: DVec2,
pub top_right: DVec2,
pub bottom_left: DVec2,
pub bottom_right: DVec2,
}
impl Bbox {
pub fn unit() -> Self {
Self {
top_left: DVec2::new(0., 1.),
top_right: DVec2::new(1., 1.),
bottom_left: DVec2::new(0., 0.),
bottom_right: DVec2::new(1., 0.),
}
}
pub fn from_transform(transform: DAffine2) -> Self {
Self {
top_left: transform.transform_point2(DVec2::new(0., 1.)),
top_right: transform.transform_point2(DVec2::new(1., 1.)),
bottom_left: transform.transform_point2(DVec2::new(0., 0.)),
bottom_right: transform.transform_point2(DVec2::new(1., 0.)),
}
}
pub fn affine_transform(self, transform: DAffine2) -> Self {
Self {
top_left: transform.transform_point2(self.top_left),
top_right: transform.transform_point2(self.top_right),
bottom_left: transform.transform_point2(self.bottom_left),
bottom_right: transform.transform_point2(self.bottom_right),
}
}
pub fn to_axis_aligned_bbox(&self) -> AxisAlignedBbox {
let start_x = self.top_left.x.min(self.top_right.x).min(self.bottom_left.x).min(self.bottom_right.x);
let start_y = self.top_left.y.min(self.top_right.y).min(self.bottom_left.y).min(self.bottom_right.y);
let end_x = self.top_left.x.max(self.top_right.x).max(self.bottom_left.x).max(self.bottom_right.x);
let end_y = self.top_left.y.max(self.top_right.y).max(self.bottom_left.y).max(self.bottom_right.y);
AxisAlignedBbox {
start: DVec2::new(start_x, start_y),
end: DVec2::new(end_x, end_y),
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/math/mod.rs | node-graph/libraries/core-types/src/math/mod.rs | pub mod bbox;
pub mod polynomial;
pub mod quad;
pub mod rect;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/libraries/core-types/src/math/quad.rs | node-graph/libraries/core-types/src/math/quad.rs | use glam::{DAffine2, DVec2};
#[derive(Debug, Clone, Default, Copy)]
/// A quad defined by four vertices. Clockwise from the top left:
///
/// `top_left`, `top_right`, `bottom_right`, `bottom_left`.
pub struct Quad(pub [DVec2; 4]);
impl Quad {
/// Get the top left corner of the quad.
pub fn top_left(&self) -> DVec2 {
self.0[0]
}
/// Get the top right corner of the quad.
pub fn top_right(&self) -> DVec2 {
self.0[1]
}
/// Get the bottom right corner of the quad.
pub fn bottom_right(&self) -> DVec2 {
self.0[2]
}
/// Get the bottom left corner of the quad.
pub fn bottom_left(&self) -> DVec2 {
self.0[3]
}
/// Create a zero-sized quad at the point.
pub fn from_point(point: DVec2) -> Self {
Self([point; 4])
}
/// Convert a box defined by two corner points to a quad. The points must be given as `minimum (top left)` then `maximum (bottom right)`.
pub fn from_box(bbox: [DVec2; 2]) -> Self {
let size = bbox[1] - bbox[0];
Self([bbox[0], bbox[0] + size * DVec2::X, bbox[1], bbox[0] + size * DVec2::Y])
}
/// Create a quad from the center and offset (distance from center to middle of an edge)
pub fn from_square(center: DVec2, offset: f64) -> Self {
Self::from_box([center - offset, center + offset])
}
/// Get all the edges in the quad.
pub fn all_edges(&self) -> [[DVec2; 2]; 4] {
[[self.0[0], self.0[1]], [self.0[1], self.0[2]], [self.0[2], self.0[3]], [self.0[3], self.0[0]]]
}
/// Get two edges as bases.
pub fn edges(&self) -> [[DVec2; 2]; 2] {
[[self.0[0], self.0[1]], [self.0[1], self.0[2]]]
}
/// Returns true only if the width and height are both greater than or equal to the given width.
pub fn all_sides_at_least_width(&self, width: f64) -> bool {
self.edges().into_iter().all(|[a, b]| (a - b).length_squared() >= width.powi(2))
}
/// Generates the axis aligned bounding box of the quad
pub fn bounding_box(&self) -> [DVec2; 2] {
[
self.0.into_iter().reduce(|a, b| a.min(b)).unwrap_or_default(),
self.0.into_iter().reduce(|a, b| a.max(b)).unwrap_or_default(),
]
}
/// Gets the center of a quad
pub fn center(&self) -> DVec2 {
self.0.iter().sum::<DVec2>() / 4.
}
/// Take the outside bounds of two axis aligned rectangles, which are defined by two corner points.
pub fn combine_bounds(a: [DVec2; 2], b: [DVec2; 2]) -> [DVec2; 2] {
[a[0].min(b[0]), a[1].max(b[1])]
}
/// "Clip" bounds of `a` to the limits of `b`.
pub fn clip(a: [DVec2; 2], b: [DVec2; 2]) -> [DVec2; 2] {
[
a[0].max(b[0]), // Constrain min corner
a[1].min(b[1]), // Constrain max corner
]
}
/// Expand a quad by a certain amount on all sides.
///
/// Not currently very optimized
pub fn inflate(&self, offset: f64) -> Quad {
let offset = |index_before, index, index_after| {
let [point_before, point, point_after]: [DVec2; 3] = [self.0[index_before], self.0[index], self.0[index_after]];
let [line_in, line_out] = [point - point_before, point_after - point];
let angle = line_in.angle_to(-line_out);
let offset_length = offset / (std::f64::consts::FRAC_PI_2 - angle / 2.).cos();
point + (line_in.perp().normalize_or_zero() + line_out.perp().normalize_or_zero()).normalize_or_zero() * offset_length
};
Self([offset(3, 0, 1), offset(0, 1, 2), offset(1, 2, 3), offset(2, 3, 0)])
}
/// Does this quad contain a point
///
/// Code from https://wrfranklin.org/Research/Short_Notes/pnpoly.html
pub fn contains(&self, p: DVec2) -> bool {
let mut inside = false;
for (i, j) in (0..4).zip([3, 0, 1, 2]) {
if (self.0[i].y > p.y) != (self.0[j].y > p.y) && p.x < ((self.0[j].x - self.0[i].x) * (p.y - self.0[i].y) / (self.0[j].y - self.0[i].y) + self.0[i].x) {
inside = !inside;
}
}
inside
}
/// https://www.cs.rpi.edu/~cutler/classes/computationalgeometry/F23/lectures/02_line_segment_intersections.pdf
fn line_intersection_t(a: DVec2, b: DVec2, c: DVec2, d: DVec2) -> (f64, f64) {
let t = ((a.x - c.x) * (c.y - d.y) - (a.y - c.y) * (c.x - d.x)) / ((a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x));
let u = ((a.x - c.x) * (a.y - b.y) - (a.y - c.y) * (a.x - b.x)) / ((a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x));
(t, u)
}
fn intersect_lines(a: DVec2, b: DVec2, c: DVec2, d: DVec2) -> Option<DVec2> {
let (t, u) = Self::line_intersection_t(a, b, c, d);
((0. ..=1.).contains(&t) && (0. ..=1.).contains(&u)).then(|| a + t * (b - a))
}
pub fn intersect_rays(a: DVec2, a_direction: DVec2, b: DVec2, b_direction: DVec2) -> Option<DVec2> {
let (t, u) = Self::line_intersection_t(a, a + a_direction, b, b + b_direction);
(t.is_finite() && u.is_finite()).then(|| a + t * a_direction)
}
pub fn intersects(&self, other: Quad) -> bool {
let intersects = self
.all_edges()
.into_iter()
.any(|[a, b]| other.all_edges().into_iter().any(|[c, d]| Self::intersect_lines(a, b, c, d).is_some()));
self.contains(other.center()) || other.contains(self.center()) || intersects
}
}
impl std::ops::Mul<Quad> for DAffine2 {
type Output = Quad;
fn mul(self, rhs: Quad) -> Self::Output {
Quad(rhs.0.map(|point| self.transform_point2(point)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn offset_quad() {
fn eq(a: Quad, b: Quad) -> bool {
a.0.iter().zip(b.0).all(|(a, b)| a.abs_diff_eq(b, 0.0001))
}
assert!(eq(Quad::from_box([DVec2::ZERO, DVec2::ONE]).inflate(0.5), Quad::from_box([DVec2::splat(-0.5), DVec2::splat(1.5)])));
assert!(eq(Quad::from_box([DVec2::ONE, DVec2::ZERO]).inflate(0.5), Quad::from_box([DVec2::splat(1.5), DVec2::splat(-0.5)])));
assert!(eq(
(DAffine2::from_scale(DVec2::new(-1., 1.)) * Quad::from_box([DVec2::ZERO, DVec2::ONE])).inflate(0.5),
DAffine2::from_scale(DVec2::new(-1., 1.)) * Quad::from_box([DVec2::splat(-0.5), DVec2::splat(1.5)])
));
}
#[test]
fn quad_contains() {
assert!(Quad::from_box([DVec2::ZERO, DVec2::ONE]).contains(DVec2::splat(0.5)));
assert!(Quad::from_box([DVec2::ONE, DVec2::ZERO]).contains(DVec2::splat(0.5)));
assert!(Quad::from_box([DVec2::splat(300.), DVec2::splat(500.)]).contains(DVec2::splat(350.)));
assert!((DAffine2::from_scale(DVec2::new(-1., 1.)) * Quad::from_box([DVec2::ZERO, DVec2::ONE])).contains(DVec2::new(-0.5, 0.5)));
assert!(!Quad::from_box([DVec2::ZERO, DVec2::ONE]).contains(DVec2::new(1., 1.1)));
assert!(!Quad::from_box([DVec2::ONE, DVec2::ZERO]).contains(DVec2::new(0.5, -0.01)));
assert!(!(DAffine2::from_scale(DVec2::new(-1., 1.)) * Quad::from_box([DVec2::ZERO, DVec2::ONE])).contains(DVec2::splat(0.5)));
}
#[test]
fn intersect_lines() {
assert_eq!(
Quad::intersect_lines(DVec2::new(-5., 5.), DVec2::new(5., 5.), DVec2::new(2., 7.), DVec2::new(2., 3.)),
Some(DVec2::new(2., 5.))
);
assert_eq!(Quad::intersect_lines(DVec2::new(4., 6.), DVec2::new(4., 5.), DVec2::new(2., 7.), DVec2::new(2., 3.)), None);
assert_eq!(Quad::intersect_lines(DVec2::new(-5., 5.), DVec2::new(5., 5.), DVec2::new(2., 7.), DVec2::new(2., 9.)), None);
}
#[test]
fn intersect_quad() {
assert!(Quad::from_box([DVec2::ZERO, DVec2::splat(5.)]).intersects(Quad::from_box([DVec2::splat(4.), DVec2::splat(7.)])));
assert!(Quad::from_box([DVec2::ZERO, DVec2::splat(5.)]).intersects(Quad::from_box([DVec2::splat(4.), DVec2::splat(4.2)])));
assert!(!Quad::from_box([DVec2::ZERO, DVec2::splat(3.)]).intersects(Quad::from_box([DVec2::splat(4.), DVec2::splat(4.2)])));
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/proc-macros/src/helper_structs.rs | proc-macros/src/helper_structs.rs | use proc_macro2::{Ident, TokenStream};
use std::collections::HashMap;
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::token::Paren;
use syn::{LitStr, Token, parenthesized};
pub struct IdentList {
pub parts: Punctuated<Ident, Token![,]>,
}
impl Parse for IdentList {
fn parse(input: ParseStream) -> syn::Result<Self> {
let content;
let _paren_token = parenthesized!(content in input);
Ok(Self {
parts: Punctuated::parse_terminated(&content)?,
})
}
}
/// Parses `("some text")`
pub struct AttrInnerSingleString {
_paren_token: Paren,
pub content: LitStr,
}
impl Parse for AttrInnerSingleString {
fn parse(input: ParseStream) -> syn::Result<Self> {
let content;
let _paren_token = parenthesized!(content in input);
Ok(Self {
_paren_token,
content: content.parse()?,
})
}
}
/// Parses `key="value"`
pub struct KeyEqString {
key: Ident,
_eq_token: Token![=],
lit: LitStr,
}
impl Parse for KeyEqString {
fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(Self {
key: input.parse()?,
_eq_token: input.parse()?,
lit: input.parse()?,
})
}
}
/// Parses `(key="value", key="value", …)`
pub struct AttrInnerKeyStringMap {
parts: Punctuated<KeyEqString, Token![,]>,
}
impl Parse for AttrInnerKeyStringMap {
fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(Self {
parts: Punctuated::parse_terminated(input)?,
})
}
}
impl AttrInnerKeyStringMap {
pub fn multi_into_iter(iter: impl IntoIterator<Item = Self>) -> impl Iterator<Item = (Ident, Vec<LitStr>)> {
use std::collections::hash_map::Entry;
let mut res = Vec::<(Ident, Vec<LitStr>)>::new();
let mut idx = HashMap::<Ident, usize>::new();
for part in iter.into_iter().flat_map(|x: Self| x.parts) {
match idx.entry(part.key) {
Entry::Occupied(occ) => {
res[*occ.get()].1.push(part.lit);
}
Entry::Vacant(vac) => {
let ident = vac.key().clone();
vac.insert(res.len());
res.push((ident, vec![part.lit]));
}
}
}
res.into_iter()
}
}
/// Parses `(left, right)`
pub struct Pair<F, S> {
pub first: F,
pub sep: Token![,],
pub second: S,
}
impl<F, S> Parse for Pair<F, S>
where
F: Parse,
S: Parse,
{
fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(Self {
first: input.parse()?,
sep: input.parse()?,
second: input.parse()?,
})
}
}
/// parses `(...)`
pub struct ParenthesizedTokens {
pub paren: Paren,
pub tokens: TokenStream,
}
impl Parse for ParenthesizedTokens {
fn parse(input: ParseStream) -> syn::Result<Self> {
let content;
let paren = parenthesized!(content in input);
Ok(Self { paren, tokens: content.parse()? })
}
}
/// parses a comma-delimeted list of `T`s with optional trailing comma
pub struct SimpleCommaDelimeted<T>(pub Vec<T>);
impl<T: Parse> Parse for SimpleCommaDelimeted<T> {
fn parse(input: ParseStream) -> syn::Result<Self> {
let punctuated = Punctuated::<T, Token![,]>::parse_terminated(input)?;
Ok(Self(punctuated.into_iter().collect()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn attr_inner_single_string() {
let res = syn::parse2::<AttrInnerSingleString>(quote::quote! {
("a string literal")
});
assert!(res.is_ok());
assert_eq!(res.ok().unwrap().content.value(), "a string literal");
let res = syn::parse2::<AttrInnerSingleString>(quote::quote! {
wrong, "stuff"
});
assert!(res.is_err());
}
#[test]
fn key_eq_string() {
let res = syn::parse2::<KeyEqString>(quote::quote! {
key="value"
});
assert!(res.is_ok());
let res = res.ok().unwrap();
assert_eq!(res.key, "key");
assert_eq!(res.lit.value(), "value");
let res = syn::parse2::<KeyEqString>(quote::quote! {
wrong, "stuff"
});
assert!(res.is_err());
}
#[test]
fn attr_inner_key_string_map() {
let res = syn::parse2::<AttrInnerKeyStringMap>(quote::quote! {
key="value", key2="value2"
});
assert!(res.is_ok());
let res = res.ok().unwrap();
for (item, (k, v)) in res.parts.into_iter().zip(vec![("key", "value"), ("key2", "value2")]) {
assert_eq!(item.key, k);
assert_eq!(item.lit.value(), v);
}
let res = syn::parse2::<AttrInnerKeyStringMap>(quote::quote! {
key="value", key2="value2",
});
assert!(res.is_ok());
let res = res.ok().unwrap();
for (item, (k, v)) in res.parts.into_iter().zip(vec![("key", "value"), ("key2", "value2")]) {
assert_eq!(item.key, k);
assert_eq!(item.lit.value(), v);
}
let res = syn::parse2::<AttrInnerKeyStringMap>(quote::quote! {
wrong, "stuff"
});
assert!(res.is_err());
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/proc-macros/src/lib.rs | proc-macros/src/lib.rs | #![allow(unused)]
mod as_message;
mod combined_message_attrs;
mod discriminant;
mod extract_fields;
mod helper_structs;
mod helpers;
mod hierarchical_tree;
mod hint;
mod message_handler_data_attr;
mod transitive_child;
mod widget_builder;
use crate::as_message::derive_as_message_impl;
use crate::combined_message_attrs::combined_message_attrs_impl;
use crate::discriminant::derive_discriminant_impl;
use crate::extract_fields::derive_extract_field_impl;
use crate::helper_structs::AttrInnerSingleString;
use crate::hierarchical_tree::generate_hierarchical_tree;
use crate::hint::derive_hint_impl;
use crate::message_handler_data_attr::message_handler_data_attr_impl;
use crate::transitive_child::derive_transitive_child_impl;
use crate::widget_builder::derive_widget_builder_impl;
use proc_macro::TokenStream;
/// Derive the `ToDiscriminant` trait and create a `<Type Name>Discriminant` enum
///
/// This derive macro is enum-only.
///
/// The discriminant enum is a copy of the input enum with all fields of every variant removed.
/// The exception to that rule is the `#[child]` attribute.
///
/// # Helper attributes
/// - `#[sub_discriminant]`: only usable on variants with a single field; instead of no fields, the discriminant of the single field will be included in the discriminant,
/// acting as a sub-discriminant.
/// - `#[discriminant_attr(…)]`: usable on the enum itself or on any variant; applies `#[…]` in its place on the discriminant.
///
/// # Attributes on the Discriminant
/// All attributes on variants and the type itself are cleared when constructing the discriminant.
/// If the discriminant is supposed to also have an attribute, you must double it with `#[discriminant_attr(…)]`
///
/// # Example
/// ```
/// # use graphite_proc_macros::ToDiscriminant;
/// # use editor::utility_traits::ToDiscriminant;
/// # use std::ffi::OsString;
///
/// #[derive(ToDiscriminant)]
/// #[discriminant_attr(derive(Debug, Eq, PartialEq))]
/// pub enum EnumA {
/// A(u8),
/// #[sub_discriminant]
/// B(EnumB)
/// }
///
/// #[derive(ToDiscriminant)]
/// #[discriminant_attr(derive(Debug, Eq, PartialEq))]
/// #[discriminant_attr(repr(u8))]
/// pub enum EnumB {
/// Foo(u8),
/// Bar(String),
/// #[cfg(feature = "some-feature")]
/// #[discriminant_attr(cfg(feature = "some-feature"))]
/// WindowsBar(OsString)
/// }
///
/// let a = EnumA::A(1);
/// assert_eq!(a.to_discriminant(), EnumADiscriminant::A);
/// let b = EnumA::B(EnumB::Bar("bar".to_string()));
/// assert_eq!(b.to_discriminant(), EnumADiscriminant::B(EnumBDiscriminant::Bar));
/// ```
#[proc_macro_derive(ToDiscriminant, attributes(sub_discriminant, discriminant_attr))]
pub fn derive_discriminant(input_item: TokenStream) -> TokenStream {
TokenStream::from(derive_discriminant_impl(input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
}
/// Derive the `TransitiveChild` trait and generate `From` impls to convert into the parent, as well as the top parent type
///
/// This macro cannot be invoked on the top parent (which has no parent but itself). Instead, implement `TransitiveChild` manually
/// like in the example.
///
/// # Helper Attributes
/// - `#[parent(<Type>, <Expr>)]` (**required**): declare the parent type (`<Type>`)
/// and a function (`<Expr>`, has to evaluate to a single arg function) for converting a value of this type to the parent type
/// - `#[parent_is_top]`: Denote that the parent type has no further parent type (this is required because otherwise the `From` impls for parent and top parent would overlap)
///
/// # Example
/// ```
/// # use graphite_proc_macros::TransitiveChild;
/// # use editor::utility_traits::TransitiveChild;
///
/// #[derive(Debug, Eq, PartialEq)]
/// struct A { u: u8, b: B };
///
/// impl A {
/// pub fn from_b(b: B) -> Self {
/// Self { u: 7, b }
/// }
/// }
///
/// impl TransitiveChild for A {
/// type Parent = Self;
/// type TopParent = Self;
/// }
///
/// #[derive(TransitiveChild, Debug, Eq, PartialEq)]
/// #[parent(A, A::from_b)]
/// #[parent_is_top]
/// enum B {
/// Foo,
/// Bar,
/// Child(C)
/// }
///
/// #[derive(TransitiveChild, Debug, Eq, PartialEq)]
/// #[parent(B, B::Child)]
/// struct C(D);
///
/// #[derive(TransitiveChild, Debug, Eq, PartialEq)]
/// #[parent(C, C)]
/// struct D;
///
/// let d = D;
/// assert_eq!(A::from(d), A { u: 7, b: B::Child(C(D)) });
/// ```
#[proc_macro_derive(TransitiveChild, attributes(parent, parent_is_top))]
pub fn derive_transitive_child(input_item: TokenStream) -> TokenStream {
TokenStream::from(derive_transitive_child_impl(input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
}
/// Derive the `AsMessage` trait
///
/// # Helper Attributes
/// - `#[child]`: only on tuple variants with a single field; Denote that the message path should continue inside the variant
///
/// # Example
/// See also [`TransitiveChild`]
/// ```
/// # use graphite_proc_macros::{TransitiveChild, AsMessage};
/// # use editor::utility_traits::TransitiveChild;
/// # use editor::messages::prelude::*;
///
/// #[derive(AsMessage)]
/// pub enum TopMessage {
/// A(u8),
/// B(u16),
/// #[child]
/// C(MessageC),
/// #[child]
/// D(MessageD)
/// }
///
/// impl TransitiveChild for TopMessage {
/// type Parent = Self;
/// type TopParent = Self;
/// }
///
/// #[derive(TransitiveChild, AsMessage, Copy, Clone)]
/// #[parent(TopMessage, TopMessage::C)]
/// #[parent_is_top]
/// pub enum MessageC {
/// X1,
/// X2
/// }
///
/// #[derive(TransitiveChild, AsMessage, Copy, Clone)]
/// #[parent(TopMessage, TopMessage::D)]
/// #[parent_is_top]
/// pub enum MessageD {
/// Y1,
/// #[child]
/// Y2(MessageE)
/// }
///
/// #[derive(TransitiveChild, AsMessage, Copy, Clone)]
/// #[parent(MessageD, MessageD::Y2)]
/// pub enum MessageE {
/// Alpha,
/// Beta
/// }
///
/// let c = MessageC::X1;
/// assert_eq!(c.local_name(), "X1");
/// assert_eq!(c.global_name(), "C.X1");
/// let d = MessageD::Y2(MessageE::Alpha);
/// assert_eq!(d.local_name(), "Y2.Alpha");
/// assert_eq!(d.global_name(), "D.Y2.Alpha");
/// let e = MessageE::Beta;
/// assert_eq!(e.local_name(), "Beta");
/// assert_eq!(e.global_name(), "D.Y2.Beta");
/// ```
#[proc_macro_derive(AsMessage, attributes(child))]
pub fn derive_message(input_item: TokenStream) -> TokenStream {
TokenStream::from(derive_as_message_impl(input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
}
/// This macro is basically an abbreviation for the usual [ToDiscriminant], [TransitiveChild] and [AsMessage] invocations.
///
/// This macro is enum-only.
///
/// Also note that all three of those derives have to be in scope.
///
/// # Usage
/// There are three possible argument syntaxes you can use:
/// 1. no arguments: this is for the top-level message enum. It derives `ToDiscriminant`, `AsMessage` on the discriminant, and implements `TransitiveChild` on both
/// (the parent and top parent being the respective types themselves).
/// It also derives the following `std` traits on the discriminant: `Debug, Copy, Clone, PartialEq, Eq, Hash`.
/// 2. two arguments: this is for message enums whose direct parent is the top level message enum. The syntax is `#[impl_message(<Type>, <Ident>)]`,
/// where `<Type>` is the parent message type and `<Ident>` is the identifier of the variant used to construct this child.
/// It derives `ToDiscriminant`, `AsMessage` on the discriminant, and `TransitiveChild` on both (adding `#[parent_is_top]` to both).
/// It also derives the following `std` traits on the discriminant: `Debug, Copy, Clone, PartialEq, Eq, Hash`.
/// 3. three arguments: this is for all other message enums that are transitive children of the top level message enum. The syntax is
/// `#[impl_message(<Type>, <Type>, <Ident>)]`, where the first `<Type>` is the top parent message type, the second `<Type>` is the parent message type
/// and `<Ident>` is the identifier of the variant used to construct this child.
/// It derives `ToDiscriminant`, `AsMessage` on the discriminant, and `TransitiveChild` on both.
/// It also derives the following `std` traits on the discriminant: `Debug, Copy, Clone, PartialEq, Eq, Hash`.
/// **This third option will likely change in the future**
#[proc_macro_attribute]
pub fn impl_message(attr: TokenStream, input_item: TokenStream) -> TokenStream {
TokenStream::from(combined_message_attrs_impl(attr.into(), input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
}
/// Derive the `Hint` trait
///
/// # Example
/// ```
/// # use graphite_proc_macros::Hint;
/// # use editor::utility_traits::Hint;
///
/// #[derive(Hint)]
/// pub enum StateMachine {
/// #[hint(rmb = "foo", lmb = "bar")]
/// Ready,
/// #[hint(alt = "baz")]
/// RMBDown,
/// // no hint (also ok)
/// LMBDown
/// }
/// ```
#[proc_macro_derive(Hint, attributes(hint))]
pub fn derive_hint(input_item: TokenStream) -> TokenStream {
TokenStream::from(derive_hint_impl(input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
}
/// The `edge` proc macro does nothing, it is intended for use with an external tool
///
/// # Example
/// ```ignore
/// match (example_tool_state, event) {
/// (ToolState::Ready, Event::PointerDown(mouse_state)) if *mouse_state == MouseState::Left => {
/// #[edge("LMB Down")]
/// ToolState::Pending
/// }
/// (SelectToolState::Pending, Event::PointerUp(mouse_state)) if *mouse_state == MouseState::Left => {
/// #[edge("LMB Up: Select Object")]
/// SelectToolState::Ready
/// }
/// (SelectToolState::Pending, Event::PointerMove(x,y)) => {
/// #[edge("Mouse Move")]
/// SelectToolState::TransformSelected
/// }
/// (SelectToolState::TransformSelected, Event::PointerMove(x,y)) => {
/// #[edge("Mouse Move")]
/// SelectToolState::TransformSelected
/// }
/// (SelectToolState::TransformSelected, Event::PointerUp(mouse_state)) if *mouse_state == MouseState::Left => {
/// #[edge("LMB Up")]
/// SelectToolState::Ready
/// }
/// (state, _) => {
/// // Do nothing
/// state
/// }
/// }
/// ```
#[proc_macro_attribute]
pub fn edge(attr: TokenStream, item: TokenStream) -> TokenStream {
// to make sure that only `#[edge("string")]` is allowed
let _verify = syn::parse_macro_input!(attr as AttrInnerSingleString);
item
}
#[proc_macro_derive(WidgetBuilder, attributes(widget_builder))]
pub fn derive_widget_builder(input_item: TokenStream) -> TokenStream {
TokenStream::from(derive_widget_builder_impl(input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
}
#[proc_macro_derive(HierarchicalTree)]
pub fn derive_hierarchical_tree(input_item: TokenStream) -> TokenStream {
TokenStream::from(generate_hierarchical_tree(input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
}
#[proc_macro_derive(ExtractField)]
pub fn derive_extract_field(input_item: TokenStream) -> TokenStream {
TokenStream::from(derive_extract_field_impl(input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
}
#[proc_macro_attribute]
pub fn message_handler_data(attr: TokenStream, input_item: TokenStream) -> TokenStream {
TokenStream::from(message_handler_data_attr_impl(attr.into(), input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
}
#[cfg(test)]
mod tests {
use super::*;
use proc_macro2::TokenStream as TokenStream2;
fn ts_assert_eq(l: TokenStream2, r: TokenStream2) {
// not sure if this is the best way of doing things but if two TokenStreams are equal, their `to_string` is also equal
// so there are at least no false negatives
assert_eq!(l.to_string(), r.to_string());
}
#[test]
fn test_derive_hint() {
let res = derive_hint_impl(quote::quote! {
#[hint(key1="val1",key2="val2",)]
struct S { a: u8, b: String, c: bool }
});
assert!(res.is_ok());
ts_assert_eq(
res.unwrap(),
quote::quote! {
impl Hint for S {
fn hints(&self) -> ::std::collections::HashMap<String, String> {
let mut hm = ::std::collections::HashMap::with_capacity(2usize);
hm.insert("key1".to_string(), "val1".to_string());
hm.insert("key2".to_string(), "val2".to_string());
hm
}
}
},
);
let res = derive_hint_impl(quote::quote! {
enum E {
#[hint(key1="val1",key2="val2",)]
S { a: u8, b: String, c: bool },
#[hint(key3="val3")]
X,
Y
}
});
assert!(res.is_ok());
ts_assert_eq(
res.unwrap(),
quote::quote! {
impl Hint for E {
fn hints(&self) -> ::std::collections::HashMap<String, String> {
match self {
E::S { .. } => {
let mut hm = ::std::collections::HashMap::with_capacity(2usize);
hm.insert("key1".to_string(), "val1".to_string());
hm.insert("key2".to_string(), "val2".to_string());
hm
}
E::X { .. } => {
let mut hm = ::std::collections::HashMap::with_capacity(1usize);
hm.insert("key3".to_string(), "val3".to_string());
hm
}
E::Y { .. } => {
let mut hm = ::std::collections::HashMap::with_capacity(0usize);
hm
}
}
}
}
},
);
let res = derive_hint_impl(quote::quote! {
union NoHint {}
});
assert!(res.is_ok());
ts_assert_eq(
res.unwrap(),
quote::quote! {
impl Hint for NoHint {
fn hints(&self) -> ::std::collections::HashMap<String, String> {
let mut hm = ::std::collections::HashMap::with_capacity(0usize);
hm
}
}
},
);
let res = derive_hint_impl(quote::quote! {
#[hint(a="1", a="2")]
struct S;
});
assert!(res.is_err());
let res = derive_hint_impl(quote::quote! {
#[hint(a="1")]
#[hint(b="2")]
struct S;
});
assert!(res.is_ok());
ts_assert_eq(
res.unwrap(),
quote::quote! {
impl Hint for S {
fn hints(&self) -> ::std::collections::HashMap<String, String> {
let mut hm = ::std::collections::HashMap::with_capacity(2usize);
hm.insert("a".to_string(), "1".to_string());
hm.insert("b".to_string(), "2".to_string());
hm
}
}
},
)
}
// note: edge needs no testing since AttrInnerSingleString has testing and that's all you'd need to test with edge
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/proc-macros/src/combined_message_attrs.rs | proc-macros/src/combined_message_attrs.rs | use crate::helpers::call_site_ident;
use proc_macro2::Ident;
use proc_macro2::TokenStream;
use quote::ToTokens;
use syn::Token;
use syn::parse::{Parse, ParseStream};
use syn::{ItemEnum, TypePath};
struct MessageArgs {
pub _top_parent: TypePath,
pub _comma1: Token![,],
pub parent: TypePath,
pub _comma2: Token![,],
pub variant: Ident,
}
impl Parse for MessageArgs {
fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(Self {
_top_parent: input.parse()?,
_comma1: input.parse()?,
parent: input.parse()?,
_comma2: input.parse()?,
variant: input.parse()?,
})
}
}
struct TopLevelMessageArgs {
pub parent: TypePath,
pub _comma2: Token![,],
pub variant: Ident,
}
impl Parse for TopLevelMessageArgs {
fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(Self {
parent: input.parse()?,
_comma2: input.parse()?,
variant: input.parse()?,
})
}
}
pub fn combined_message_attrs_impl(attr: TokenStream, input_item: TokenStream) -> syn::Result<TokenStream> {
if attr.is_empty() {
return top_level_impl(input_item);
}
let mut input = syn::parse2::<ItemEnum>(input_item)?;
let (parent_is_top, parent, variant) = match syn::parse2::<MessageArgs>(attr.clone()) {
Ok(x) => (false, x.parent, x.variant),
Err(_) => {
let x = syn::parse2::<TopLevelMessageArgs>(attr)?;
(true, x.parent, x.variant)
}
};
let parent_discriminant = quote::quote! {
<#parent as ToDiscriminant>::Discriminant
};
input.attrs.push(syn::parse_quote! { #[derive(ToDiscriminant, TransitiveChild, HierarchicalTree)] });
input.attrs.push(syn::parse_quote! { #[parent(#parent, #parent::#variant)] });
if parent_is_top {
input.attrs.push(syn::parse_quote! { #[parent_is_top] });
}
input
.attrs
.push(syn::parse_quote! { #[discriminant_attr(derive(Debug, Copy, Clone, PartialEq, Eq, Hash, AsMessage, TransitiveChild))] });
input
.attrs
.push(syn::parse_quote! { #[discriminant_attr(parent(#parent_discriminant, #parent_discriminant::#variant))] });
if parent_is_top {
input.attrs.push(syn::parse_quote! { #[discriminant_attr(parent_is_top)] });
}
for var in &mut input.variants {
if let Some(attr) = var.attrs.iter_mut().find(|a| a.path().is_ident("child")) {
let path = match &mut attr.meta {
syn::Meta::Path(path) => path,
syn::Meta::List(list) => &mut list.path,
syn::Meta::NameValue(named_value) => &mut named_value.path,
};
let last_segment = path.segments.last_mut().unwrap();
last_segment.ident = call_site_ident("sub_discriminant");
var.attrs.push(syn::parse_quote! {
#[discriminant_attr(child)]
});
}
}
Ok(input.into_token_stream())
}
fn top_level_impl(input_item: TokenStream) -> syn::Result<TokenStream> {
let mut input = syn::parse2::<ItemEnum>(input_item)?;
input.attrs.push(syn::parse_quote! { #[derive(ToDiscriminant, HierarchicalTree)] });
input.attrs.push(syn::parse_quote! { #[discriminant_attr(derive(Debug, Copy, Clone, PartialEq, Eq, Hash, AsMessage))] });
for var in &mut input.variants {
if let Some(attr) = var.attrs.iter_mut().find(|a| a.path().is_ident("child")) {
let path = match &mut attr.meta {
syn::Meta::Path(path) => path,
syn::Meta::List(list) => &mut list.path,
syn::Meta::NameValue(named_value) => &mut named_value.path,
};
let last_segment = path.segments.last_mut().unwrap();
last_segment.ident = call_site_ident("sub_discriminant");
var.attrs.push(syn::parse_quote! {
#[discriminant_attr(child)]
});
}
}
let input_type = &input.ident;
let discriminant = call_site_ident(format!("{input_type}Discriminant"));
Ok(quote::quote! {
#input
impl TransitiveChild for #input_type {
type TopParent = Self;
type Parent = Self;
}
impl TransitiveChild for #discriminant {
type TopParent = Self;
type Parent = Self;
}
})
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/proc-macros/src/extract_fields.rs | proc-macros/src/extract_fields.rs | use crate::helpers::clean_rust_type_syntax;
use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, format_ident, quote};
use syn::{Data, DeriveInput, Fields, Type, parse2};
pub fn derive_extract_field_impl(input: TokenStream) -> syn::Result<TokenStream> {
let input = parse2::<DeriveInput>(input)?;
let struct_name = &input.ident;
let generics = &input.generics;
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let fields = match &input.data {
Data::Struct(data) => match &data.fields {
Fields::Named(fields) => &fields.named,
_ => return Err(syn::Error::new(Span::call_site(), "ExtractField only works on structs with named fields")),
},
_ => return Err(syn::Error::new(Span::call_site(), "ExtractField only works on structs")),
};
let mut field_line = Vec::new();
// Extract field names and types as strings at compile time
let field_info = fields
.iter()
.map(|field| {
let ident = field.ident.as_ref().unwrap();
let name = ident.to_string();
let ty = clean_rust_type_syntax(field.ty.to_token_stream().to_string());
let line = ident.span().start().line;
field_line.push(line);
(name, ty)
})
.collect::<Vec<_>>();
let field_str = field_info.into_iter().map(|(name, ty)| (format!("{name}: {ty}")));
let res = quote! {
impl #impl_generics ExtractField for #struct_name #ty_generics #where_clause {
fn field_types() -> Vec<(String, usize)> {
vec![
#((String::from(#field_str), #field_line)),*
]
}
fn print_field_types() {
for (field, line) in Self::field_types() {
println!("{} at line {}", field, line);
}
}
fn path() -> &'static str {
file!()
}
}
};
Ok(res)
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/proc-macros/src/helpers.rs | proc-macros/src/helpers.rs | use proc_macro2::{Ident, Span};
use syn::punctuated::Punctuated;
use syn::{Path, PathArguments, PathSegment, Token};
/// Returns `Ok(Vec<T>)` if all items are `Ok(T)`, else returns a combination of every error encountered (not just the first one)
// Allowing this lint because this is a false positive in this case. The fold can only be changed into a `try_fold` if the closure
// doesn't have an error case. See for details: https://rust-lang.github.io/rust-clippy/master/index.html#/manual_try_fold.
#[allow(clippy::manual_try_fold)]
pub fn fold_error_iter<T>(iter: impl Iterator<Item = syn::Result<T>>) -> syn::Result<Vec<T>> {
iter.fold(Ok(vec![]), |acc, x| match acc {
Ok(mut v) => x.map(|x| {
v.push(x);
v
}),
Err(mut e) => match x {
Ok(_) => Err(e),
Err(e2) => {
e.combine(e2);
Err(e)
}
},
})
}
/// Creates an ident at the call site
pub fn call_site_ident<S: AsRef<str>>(s: S) -> Ident {
Ident::new(s.as_ref(), Span::call_site())
}
/// Creates the path `left::right` from the identifiers `left` and `right`
pub fn two_segment_path(left_ident: Ident, right_ident: Ident) -> Path {
let mut segments: Punctuated<PathSegment, Token![::]> = Punctuated::new();
segments.push(PathSegment {
ident: left_ident,
arguments: PathArguments::None,
});
segments.push(PathSegment {
ident: right_ident,
arguments: PathArguments::None,
});
Path { leading_colon: None, segments }
}
pub fn clean_rust_type_syntax(input: String) -> String {
let mut result = String::new();
let mut chars = input.chars().peekable();
while let Some(c) = chars.next() {
match c {
'&' => {
result.push('&');
while let Some(' ') = chars.peek() {
chars.next();
}
}
'<' => {
while let Some(' ') = result.chars().next_back() {
result.pop();
}
result.push('<');
while let Some(' ') = chars.peek() {
chars.next();
}
}
'>' => {
while let Some(' ') = result.chars().next_back() {
result.pop();
}
result.push('>');
while let Some(' ') = chars.peek() {
chars.next();
}
}
'-' => {
if let Some('>') = chars.peek() {
while let Some(' ') = result.chars().next_back() {
result.pop();
}
result.push_str(" -> ");
chars.next();
while let Some(' ') = chars.peek() {
chars.next();
}
} else {
result.push(c);
}
}
':' => {
if let Some(':') = chars.peek() {
while let Some(' ') = result.chars().next_back() {
result.pop();
}
}
result.push(':');
chars.next();
result.push(':');
while let Some(' ') = chars.peek() {
chars.next();
}
}
_ => {
result.push(c);
}
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use quote::ToTokens;
use syn::spanned::Spanned;
#[test]
fn test_fold_error_iter() {
let res = fold_error_iter(vec![Ok(()), Ok(())].into_iter());
assert!(res.is_ok());
let _span = quote::quote! { "" }.span();
let res = fold_error_iter(vec![Ok(()), Err(syn::Error::new(_span, "err1")), Err(syn::Error::new(_span, "err2"))].into_iter());
assert!(res.is_err());
let err = res.unwrap_err();
let mut check_err = syn::Error::new(_span, "err1");
check_err.combine(syn::Error::new(_span, "err2"));
assert_eq!(err.to_compile_error().to_string(), check_err.to_compile_error().to_string());
}
#[test]
fn test_two_path() {
let _span = quote::quote! { "" }.span();
assert_eq!(two_segment_path(Ident::new("a", _span), Ident::new("b", _span)).to_token_stream().to_string(), "a :: b");
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/proc-macros/src/hierarchical_tree.rs | proc-macros/src/hierarchical_tree.rs | use crate::helpers::clean_rust_type_syntax;
use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, quote};
use syn::{Data, DeriveInput, Fields, Type, parse2};
pub fn generate_hierarchical_tree(input: TokenStream) -> syn::Result<TokenStream> {
let input = parse2::<DeriveInput>(input)?;
let input_type = &input.ident;
let data = match &input.data {
Data::Enum(data) => data,
_ => return Err(syn::Error::new(Span::call_site(), "Tried to derive HierarchicalTree for non-enum")),
};
let build_message_tree: Result<Vec<_>, syn::Error> = data
.variants
.iter()
.map(|variant| {
let variant_type = &variant.ident;
let has_child = variant
.attrs
.iter()
.any(|attr| attr.path().get_ident().is_some_and(|ident| ident == "sub_discriminant" || ident == "child"));
match &variant.fields {
Fields::Unit => Ok(quote! {
message_tree.add_variant(DebugMessageTree::new(stringify!(#variant_type)));
}),
Fields::Unnamed(fields) => {
if has_child {
let field_type = &fields.unnamed.first().unwrap().ty;
Ok(quote! {
{
let mut variant_tree = DebugMessageTree::new(stringify!(#variant_type));
let field_name = stringify!(#field_type);
const MESSAGE_SUFFIX: &str = "Message";
if MESSAGE_SUFFIX == &field_name[field_name.len().saturating_sub(MESSAGE_SUFFIX.len())..] {
// The field is a Message type, recursively build its tree
let sub_tree = #field_type::build_message_tree();
variant_tree.add_variant(sub_tree);
} else {
variant_tree.add_fields(vec![format!("{field_name}")]);
}
message_tree.add_variant(variant_tree);
}
})
} else {
let error_msg = match fields.unnamed.len() {
0 => format!("Remove the unnecessary `()` from the `{variant_type}` message enum variant."),
1 => {
let field_type = &fields.unnamed.first().unwrap().ty;
format!(
"The `{variant_type}` message should be defined as a struct-style (not tuple-style) enum variant to maintain consistent formatting across all editor messages.\n\
Replace `{}` with a named field using {{curly braces}} instead of a positional field using (parentheses).",
field_type.to_token_stream()
)
}
_ => {
let field_types = fields.unnamed.iter().map(|f| f.ty.to_token_stream().to_string()).collect::<Vec<_>>().join(", ");
format!(
"The `{variant_type}` message should be defined as a struct-style (not tuple-style) enum variant to maintain consistent formatting across all editor messages.\n\
Replace `{field_types}` with named fields using {{curly braces}} instead of positional fields using (parentheses)."
)
}
};
Err(syn::Error::new(Span::call_site(), error_msg))
}
}
Fields::Named(fields) => {
let names = fields.named.iter().map(|f| f.ident.as_ref().unwrap());
let ty = fields.named.iter().map(|f| clean_rust_type_syntax(f.ty.to_token_stream().to_string()));
Ok(quote! {
{
let mut field_names = Vec::new();
#(field_names.push(format!("{}: {}",stringify!(#names), #ty));)*
let mut variant_tree = DebugMessageTree::new(stringify!(#variant_type));
variant_tree.add_fields(field_names);
message_tree.add_variant(variant_tree);
}
})
}
}
})
.collect();
let build_message_tree = build_message_tree?;
let res = quote! {
impl HierarchicalTree for #input_type {
fn build_message_tree() -> DebugMessageTree {
let mut message_tree = DebugMessageTree::new(stringify!(#input_type));
#(#build_message_tree)*
let message_handler_str = #input_type::message_handler_str();
message_tree.add_message_handler_field(message_handler_str);
let message_handler_data_str = #input_type::message_handler_data_str();
if message_handler_data_str.fields().len() > 0 {
message_tree.add_message_handler_data_field(message_handler_data_str);
}
message_tree.set_path(file!());
message_tree
}
}
};
Ok(res)
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/proc-macros/src/transitive_child.rs | proc-macros/src/transitive_child.rs | use crate::helper_structs::Pair;
use proc_macro2::{Span, TokenStream};
use syn::{DeriveInput, Expr, Type};
pub fn derive_transitive_child_impl(input_item: TokenStream) -> syn::Result<TokenStream> {
let input = syn::parse2::<DeriveInput>(input_item).unwrap();
let attribute = input
.attrs
.iter()
.find(|a| a.path().is_ident("parent"))
.ok_or_else(|| syn::Error::new(Span::call_site(), format!("tried to derive TransitiveChild without a #[parent] attribute (on {})", input.ident)))?;
let parent_is_top = input.attrs.iter().any(|a| a.path().is_ident("parent_is_top"));
let Pair {
first: parent_type,
second: to_parent,
..
} = attribute.parse_args::<Pair<Type, Expr>>()?;
let top_parent_type: Type = syn::parse_quote! { <#parent_type as TransitiveChild>::TopParent };
let input_type = &input.ident;
let trait_impl = quote::quote! {
impl TransitiveChild for #input_type {
type Parent = #parent_type;
type TopParent = #top_parent_type;
}
};
let from_for_parent = quote::quote! {
impl From<#input_type> for #parent_type {
fn from(x: #input_type) -> #parent_type {
(#to_parent)(x)
}
}
};
let from_for_top = quote::quote! {
impl From<#input_type> for #top_parent_type {
fn from(x: #input_type) -> #top_parent_type {
#top_parent_type::from((#to_parent)(x))
}
}
};
Ok(if parent_is_top {
quote::quote! { #trait_impl #from_for_parent }
} else {
quote::quote! { #trait_impl #from_for_parent #from_for_top }
})
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/proc-macros/src/hint.rs | proc-macros/src/hint.rs | use crate::helper_structs::AttrInnerKeyStringMap;
use crate::helpers::{fold_error_iter, two_segment_path};
use proc_macro2::{Span, TokenStream as TokenStream2};
use syn::{Attribute, Data, DeriveInput, LitStr, Variant};
fn parse_hint_helper_attrs(attrs: &[Attribute]) -> syn::Result<(Vec<LitStr>, Vec<LitStr>)> {
fold_error_iter(
attrs
.iter()
.filter(|a| a.path().get_ident().is_some_and(|i| i == "hint"))
.map(|attr| attr.parse_args::<AttrInnerKeyStringMap>()),
)
.and_then(|v: Vec<AttrInnerKeyStringMap>| {
fold_error_iter(AttrInnerKeyStringMap::multi_into_iter(v).map(|(k, mut v)| match v.len() {
0 => panic!("internal error: a key without values was somehow inserted into the hashmap"),
1 => {
let single_val = v.pop().unwrap();
Ok((LitStr::new(&k.to_string(), Span::call_site()), single_val))
}
_ => {
// the first value is ok, the other ones should error
let after_first = v.into_iter().skip(1);
// this call to fold_error_iter will always return Err with a combined error
fold_error_iter(after_first.map(|lit| Err(syn::Error::new(lit.span(), format!("value for key {k} was already given"))))).map(|_: Vec<()>| unreachable!())
}
}))
})
.map(|v| v.into_iter().unzip())
}
pub fn derive_hint_impl(input_item: TokenStream2) -> syn::Result<TokenStream2> {
let input = syn::parse2::<DeriveInput>(input_item)?;
let ident = input.ident;
match input.data {
Data::Enum(data) => {
let variants = data.variants.iter().map(|var: &Variant| two_segment_path(ident.clone(), var.ident.clone())).collect::<Vec<_>>();
let hint_result = fold_error_iter(data.variants.into_iter().map(|var: Variant| parse_hint_helper_attrs(&var.attrs)));
hint_result.map(|hints: Vec<(Vec<LitStr>, Vec<LitStr>)>| {
let (keys, values): (Vec<Vec<LitStr>>, Vec<Vec<LitStr>>) = hints.into_iter().unzip();
let cap: Vec<usize> = keys.iter().map(|v| v.len()).collect();
quote::quote! {
impl Hint for #ident {
fn hints(&self) -> ::std::collections::HashMap<String, String> {
match self {
#(
#variants { .. } => {
let mut hm = ::std::collections::HashMap::with_capacity(#cap);
#(
hm.insert(#keys.to_string(), #values.to_string());
)*
hm
}
)*
}
}
}
}
})
}
Data::Struct(_) | Data::Union(_) => {
let hint_result = parse_hint_helper_attrs(&input.attrs);
hint_result.map(|(keys, values)| {
let cap = keys.len();
quote::quote! {
impl Hint for #ident {
fn hints(&self) -> ::std::collections::HashMap<String, String> {
let mut hm = ::std::collections::HashMap::with_capacity(#cap);
#(
hm.insert(#keys.to_string(), #values.to_string());
)*
hm
}
}
}
})
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/proc-macros/src/message_handler_data_attr.rs | proc-macros/src/message_handler_data_attr.rs | use crate::helpers::{call_site_ident, clean_rust_type_syntax};
use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, quote};
use syn::{ItemImpl, Type, parse2, spanned::Spanned};
pub fn message_handler_data_attr_impl(attr: TokenStream, input_item: TokenStream) -> syn::Result<TokenStream> {
// Parse the input as an impl block
let impl_block = parse2::<ItemImpl>(input_item.clone())?;
let self_ty = &impl_block.self_ty;
let path = match &**self_ty {
Type::Path(path) => &path.path,
_ => return Err(syn::Error::new(Span::call_site(), "Expected impl implementation")),
};
let input_type = path.segments.last().map(|s| &s.ident).unwrap();
// Extract the message type from the trait path
let trait_path = match &impl_block.trait_ {
Some((_, path, _)) => path,
None => return Err(syn::Error::new(Span::call_site(), "Expected trait implementation")),
};
// Get the trait generics (should be MessageHandler<M, C>)
if let Some(segment) = trait_path.segments.last() {
if segment.ident != "MessageHandler" {
return Err(syn::Error::new(segment.ident.span(), "Expected MessageHandler trait"));
}
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
if args.args.len() >= 2 {
// Extract the message type (M) and context struct type (C) from the trait params
let message_type = &args.args[0];
let data_type = &args.args[1];
let impl_item = match data_type {
syn::GenericArgument::Type(t) => {
match t {
syn::Type::Path(type_path) if !type_path.path.segments.is_empty() => {
// Get just the base identifier (ToolMessageData) without generics
let type_name = &type_path.path.segments.first().unwrap().ident;
quote! {
#input_item
impl #message_type {
pub fn message_handler_data_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#type_name)), #type_name::field_types(), #type_name::path())
}
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path())
}
}
}
}
syn::Type::Tuple(_) => quote! {
#input_item
impl #message_type {
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path())
}
}
},
syn::Type::Reference(type_reference) => {
let message_type = call_site_ident(format!("{input_type}Message"));
let type_ident = match &*type_reference.elem {
syn::Type::Path(type_path) => &type_path.path.segments.first().unwrap().ident,
_ => return Err(syn::Error::new(type_reference.elem.span(), "Expected type path")),
};
let tr = clean_rust_type_syntax(type_reference.to_token_stream().to_string());
quote! {
#input_item
impl #message_type {
pub fn message_handler_data_str() -> MessageData {
MessageData::new(format!("{}", #tr), #type_ident::field_types(), #type_ident::path())
}
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path())
}
}
}
}
_ => return Err(syn::Error::new(t.span(), "Unsupported type format")),
}
}
_ => quote! {
#input_item
},
};
return Ok(impl_item);
}
}
}
Ok(input_item)
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/proc-macros/src/discriminant.rs | proc-macros/src/discriminant.rs | use crate::helpers::call_site_ident;
use proc_macro2::{Ident, Span, TokenStream};
use syn::spanned::Spanned;
use syn::{Attribute, Data, DeriveInput, Field, Fields, ItemEnum, MetaList};
pub fn derive_discriminant_impl(input_item: TokenStream) -> syn::Result<TokenStream> {
let input = syn::parse2::<DeriveInput>(input_item).unwrap();
let mut data = match input.data {
Data::Enum(data) => data,
_ => return Err(syn::Error::new(Span::call_site(), "Tried to derive a discriminant for non-enum")),
};
let mut is_sub_discriminant = vec![];
let mut attr_errs = vec![];
for var in &mut data.variants {
if var.attrs.iter().any(|a| a.path().is_ident("sub_discriminant")) {
match var.fields.len() {
1 => {
let Field { ty, .. } = var.fields.iter_mut().next().unwrap();
*ty = syn::parse_quote! {
<#ty as ToDiscriminant>::Discriminant
};
is_sub_discriminant.push(true);
}
n => unimplemented!("#[sub_discriminant] on variants with {n} fields is not supported (for now)"),
}
} else {
var.fields = Fields::Unit;
is_sub_discriminant.push(false);
}
let mut retain = vec![];
for (i, a) in var.attrs.iter_mut().enumerate() {
if a.path().is_ident("discriminant_attr") {
match a.meta.require_list() {
Ok(MetaList { tokens, .. }) => {
let attr: Attribute = syn::parse_quote! {
#[#tokens]
};
*a = attr;
retain.push(i);
}
Err(e) => {
attr_errs.push(syn::Error::new(a.span(), e));
}
}
}
}
var.attrs = var.attrs.iter().enumerate().filter(|(i, _)| retain.contains(i)).map(|(_, x)| x.clone()).collect();
}
let attrs = input
.attrs
.iter()
.cloned()
.filter_map(|a| {
let a_span = a.span();
a.path()
.is_ident("discriminant_attr")
.then(|| match a.meta.require_list() {
Ok(MetaList { tokens, .. }) => {
let attr: Attribute = syn::parse_quote! {
#[#tokens]
};
Some(attr)
}
Err(e) => {
attr_errs.push(syn::Error::new(a_span, e));
None
}
})
.and_then(|opt| opt)
})
.collect::<Vec<Attribute>>();
if !attr_errs.is_empty() {
return Err(attr_errs
.into_iter()
.reduce(|mut l, r| {
l.combine(r);
l
})
.unwrap());
}
let discriminant = ItemEnum {
attrs,
vis: input.vis,
enum_token: data.enum_token,
ident: call_site_ident(format!("{}Discriminant", input.ident)),
generics: input.generics,
brace_token: data.brace_token,
variants: data.variants,
};
let input_type = &input.ident;
let discriminant_type = &discriminant.ident;
let variant = &discriminant.variants.iter().map(|var| &var.ident).collect::<Vec<&Ident>>();
let (pattern, value) = is_sub_discriminant
.into_iter()
.map(|b| {
if b {
(quote::quote! {(x)}, quote::quote! {(x.to_discriminant())})
} else {
(quote::quote! {{..}}, Default::default())
}
})
.unzip::<_, _, Vec<_>, Vec<_>>();
#[cfg(feature = "serde-discriminant")]
let serde = quote::quote! {
#[derive(serde::Serialize, serde::Deserialize)]
};
#[cfg(not(feature = "serde-discriminant"))]
let serde = quote::quote! {};
let res = quote::quote! {
#serde
#discriminant
impl ToDiscriminant for #input_type {
type Discriminant = #discriminant_type;
fn to_discriminant(&self) -> #discriminant_type {
match self {
#(
#input_type::#variant #pattern => #discriminant_type::#variant #value
),*
}
}
}
impl From<&#input_type> for #discriminant_type {
fn from(x: &#input_type) -> #discriminant_type {
x.to_discriminant()
}
}
};
Ok(res)
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/proc-macros/src/widget_builder.rs | proc-macros/src/widget_builder.rs | use proc_macro2::{Ident, Literal, TokenStream as TokenStream2};
use quote::ToTokens;
use syn::spanned::Spanned;
use syn::{Attribute, Data, DeriveInput, Field, PathArguments, Type};
/// Check if a specified `#[widget_builder target]` attribute can be found in the list
fn has_attribute(attrs: &[Attribute], target: &str) -> bool {
attrs
.iter()
.filter(|attr| attr.path().to_token_stream().to_string() == "widget_builder")
.any(|attr| attr.meta.require_list().is_ok_and(|list| list.tokens.to_string() == target))
}
/// Make setting strings easier by allowing all types that `impl Into<String>`
///
/// Returns the new input type and a conversion to the original.
fn easier_string_assignment(field_ty: &Type, field_ident: &Ident) -> (TokenStream2, TokenStream2) {
if let Type::Path(type_path) = field_ty {
if let Some(last_segment) = type_path.path.segments.last() {
// Check if this type is a `String`
// Based on https://stackoverflow.com/questions/66906261/rust-proc-macro-derive-how-do-i-check-if-a-field-is-of-a-primitive-type-like-b
if last_segment.ident == Ident::new("String", last_segment.ident.span()) {
return (
quote::quote_spanned!(type_path.span()=> impl Into<String>),
quote::quote_spanned!(field_ident.span()=> #field_ident.into()),
);
}
}
}
(quote::quote_spanned!(field_ty.span()=> #field_ty), quote::quote_spanned!(field_ident.span()=> #field_ident))
}
/// Extract the identifier of the field (which should always be present)
fn extract_ident(field: &Field) -> syn::Result<&Ident> {
field
.ident
.as_ref()
.ok_or_else(|| syn::Error::new_spanned(field, "Constructing a builder not supported for unnamed fields"))
}
/// Find the type passed into the builder and the right hand side of the assignment.
///
/// Applies special behavior for easier String and WidgetCallback assignment.
fn find_type_and_assignment(field: &Field) -> syn::Result<(TokenStream2, TokenStream2)> {
let field_ty = &field.ty;
let field_ident = extract_ident(field)?;
let (mut function_input_ty, mut assignment) = easier_string_assignment(field_ty, field_ident);
// Check if type is `WidgetCallback`
if let Type::Path(type_path) = field_ty {
if let Some(last_segment) = type_path.path.segments.last() {
if let PathArguments::AngleBracketed(generic_args) = &last_segment.arguments {
if let Some(first_generic) = generic_args.args.first() {
if last_segment.ident == Ident::new("WidgetCallback", last_segment.ident.span()) {
// Assign builder pattern to assign the closure directly
function_input_ty = quote::quote_spanned!(field_ty.span()=> impl Fn(&#first_generic) -> crate::messages::message::Message + 'static + Send + Sync);
assignment = quote::quote_spanned!(field_ident.span()=> crate::messages::layout::utility_types::layout_widget::WidgetCallback::new(#field_ident));
}
}
}
}
}
Ok((function_input_ty, assignment))
}
// Construct a builder function for a specific field in the struct
fn construct_builder(field: &Field) -> syn::Result<TokenStream2> {
// Check if this field should be skipped with `#[widget_builder(skip)]`
if has_attribute(&field.attrs, "skip") {
return Ok(Default::default());
}
let field_ident = extract_ident(field)?;
// Create a doc comment literal describing the behaviour of the function
let doc_comment = Literal::string(&format!("Set the `{field_ident}` field using a builder pattern."));
let (function_input_ty, assignment) = find_type_and_assignment(field)?;
// Create builder function
Ok(quote::quote_spanned!(field.span()=>
#[doc = #doc_comment]
pub fn #field_ident(mut self, #field_ident: #function_input_ty) -> Self{
self.#field_ident = #assignment;
self
}
))
}
pub fn derive_widget_builder_impl(input_item: TokenStream2) -> syn::Result<TokenStream2> {
let input = syn::parse2::<DeriveInput>(input_item)?;
let struct_name_ident = input.ident;
// Extract the struct fields
let fields = match &input.data {
Data::Enum(enum_data) => return Err(syn::Error::new_spanned(enum_data.enum_token, "Derive widget builder is not supported for enums")),
Data::Union(union_data) => return Err(syn::Error::new_spanned(union_data.union_token, "Derive widget builder is not supported for unions")),
Data::Struct(struct_data) => &struct_data.fields,
};
// Create functions based on each field
let builder_functions = fields.iter().map(construct_builder).collect::<Result<Vec<_>, _>>()?;
// Check if this should not have the `widget_instance()` function due to a `#[widget_builder(not_widget_instance)]` attribute
let widget_instance_fn = if !has_attribute(&input.attrs, "not_widget_instance") {
// A doc comment for the widget_instance function
let widget_instance_doc_comment = Literal::string(&format!("Wrap {struct_name_ident} as a WidgetInstance."));
// Construct the `widget_instance` function
quote::quote! {
#[doc = #widget_instance_doc_comment]
pub fn widget_instance(self) -> crate::messages::layout::utility_types::layout_widget::WidgetInstance {
crate::messages::layout::utility_types::layout_widget::WidgetInstance::new( crate::messages::layout::utility_types::layout_widget::Widget::#struct_name_ident(self))
}
}
} else {
quote::quote!()
};
// The new function takes any fields tagged with `#[widget_builder(constructor)]` as arguments.
let new_fn = {
// A doc comment for the new function
let new_doc_comment = Literal::string(&format!("Create a new {struct_name_ident}, based on default values."));
let is_constructor = |field: &Field| has_attribute(&field.attrs, "constructor");
let idents = fields.iter().filter(|field| is_constructor(field)).map(extract_ident).collect::<Result<Vec<_>, _>>()?;
let types_and_assignments = fields.iter().filter(|field| is_constructor(field)).map(find_type_and_assignment).collect::<Result<Vec<_>, _>>()?;
let (types, assignments): (Vec<_>, Vec<_>) = types_and_assignments.into_iter().unzip();
let construction = if idents.is_empty() {
quote::quote!(Default::default())
} else {
let default = (idents.len() != fields.len()).then_some(quote::quote!(..Default::default())).unwrap_or_default();
quote::quote! {
Self {
#(#idents: #assignments,)*
#default
}
}
};
quote::quote! {
#[doc = #new_doc_comment]
pub fn new(#(#idents: #types),*) -> Self {
#construction
}
}
};
// Construct the code block
Ok(quote::quote! {
impl #struct_name_ident {
#new_fn
#(#builder_functions)*
#widget_instance_fn
}
})
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/proc-macros/src/as_message.rs | proc-macros/src/as_message.rs | use proc_macro2::{Span, TokenStream};
use syn::{Data, DeriveInput};
pub fn derive_as_message_impl(input_item: TokenStream) -> syn::Result<TokenStream> {
let input = syn::parse2::<DeriveInput>(input_item).unwrap();
let data = match input.data {
Data::Enum(data) => data,
_ => return Err(syn::Error::new(Span::call_site(), "Tried to derive AsMessage for non-enum")),
};
let input_type = input.ident;
let (globs, names) = data
.variants
.iter()
.map(|var| {
let var_name = &var.ident;
let var_name_s = var.ident.to_string();
if var.attrs.iter().any(|a| a.path().is_ident("child")) {
(
quote::quote! {
#input_type::#var_name(child)
},
quote::quote! {
format!("{}.{}", #var_name_s, child.local_name())
},
)
} else {
(
quote::quote! {
#input_type::#var_name { .. }
},
quote::quote! {
#var_name_s.to_string()
},
)
}
})
.unzip::<_, _, Vec<_>, Vec<_>>();
let res = quote::quote! {
impl AsMessage for #input_type {
fn local_name(self) -> String {
match self {
#(
#globs => #names
),*
}
}
}
};
Ok(res)
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/frontend/wasm/src/lib.rs | frontend/wasm/src/lib.rs | #![doc = include_str!("../README.md")]
// `macro_use` puts the log macros (`error!`, `warn!`, `debug!`, `info!` and `trace!`) in scope for the crate
#[macro_use]
extern crate log;
pub mod editor_api;
pub mod helpers;
pub mod native_communcation;
use editor::messages::prelude::*;
use std::panic;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use wasm_bindgen::prelude::*;
// Set up the persistent editor backend state
pub static EDITOR_HAS_CRASHED: AtomicBool = AtomicBool::new(false);
pub static NODE_GRAPH_ERROR_DISPLAYED: AtomicBool = AtomicBool::new(false);
pub static LOGGER: WasmLog = WasmLog;
thread_local! {
#[cfg(not(feature = "native"))]
pub static EDITOR: Mutex<Option<editor::application::Editor>> = const { Mutex::new(None) };
pub static MESSAGE_BUFFER: std::cell::RefCell<Vec<Message>> = const { std::cell::RefCell::new(Vec::new()) };
pub static EDITOR_HANDLE: Mutex<Option<editor_api::EditorHandle>> = const { Mutex::new(None) };
}
/// Initialize the backend
#[wasm_bindgen(start)]
pub fn init_graphite() {
// Set up the panic hook
panic::set_hook(Box::new(panic_hook));
// Set up the logger with a default level of debug
log::set_logger(&LOGGER).expect("Failed to set logger");
log::set_max_level(log::LevelFilter::Debug);
}
/// When a panic occurs, notify the user and log the error to the JS console before the backend dies
pub fn panic_hook(info: &panic::PanicHookInfo) {
let info = info.to_string();
let backtrace = Error::new("stack").stack().to_string();
if backtrace.contains("DynAnyNode") {
log::error!("Node graph evaluation panicked {info}");
// When the graph panics, the node runtime lock may not be released properly
if editor::node_graph_executor::NODE_RUNTIME.try_lock().is_none() {
unsafe { editor::node_graph_executor::NODE_RUNTIME.force_unlock() };
}
if !NODE_GRAPH_ERROR_DISPLAYED.load(Ordering::SeqCst) {
NODE_GRAPH_ERROR_DISPLAYED.store(true, Ordering::SeqCst);
editor_api::handle(|handle| {
let error = r#"
<rect x="50%" y="50%" width="600" height="100" transform="translate(-300 -50)" rx="4" fill="var(--color-error-red)" />
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="18" fill="var(--color-2-mildblack)">
<tspan x="50%" dy="-24" font-weight="bold">The document crashed while being rendered in its current state.</tspan>
<tspan x="50%" dy="24">The editor is now unstable! Undo your last action to restore the artwork,</tspan>
<tspan x="50%" dy="24">then save your document and restart the editor before continuing work.</tspan>
/text>"#
// It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed.
.to_string();
handle.send_frontend_message_to_js_rust_proxy(FrontendMessage::UpdateDocumentArtwork { svg: error });
});
}
return;
} else {
EDITOR_HAS_CRASHED.store(true, Ordering::SeqCst);
}
log::error!("{info}");
EDITOR_HANDLE.with(|editor_handle| {
let mut guard = editor_handle.lock();
if let Ok(Some(handle)) = guard.as_deref_mut() {
handle.send_frontend_message_to_js_rust_proxy(FrontendMessage::DisplayDialogPanic { panic_info: info.to_string() });
}
});
}
#[wasm_bindgen]
extern "C" {
/// The JavaScript `Error` type
#[derive(Clone, Debug)]
pub type Error;
#[wasm_bindgen(constructor)]
pub fn new(msg: &str) -> Error;
#[wasm_bindgen(structural, method, getter)]
fn stack(error: &Error) -> String;
}
/// Logging to the JS console
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(msg: &str, format: &str);
#[wasm_bindgen(js_namespace = console)]
fn info(msg: &str, format: &str);
#[wasm_bindgen(js_namespace = console)]
fn warn(msg: &str, format: &str);
#[wasm_bindgen(js_namespace = console)]
fn error(msg: &str, format: &str);
#[wasm_bindgen(js_namespace = console)]
fn trace(msg: &str, format: &str);
}
#[derive(Default)]
pub struct WasmLog;
impl log::Log for WasmLog {
#[inline]
fn enabled(&self, metadata: &log::Metadata) -> bool {
metadata.level() <= log::max_level()
}
fn log(&self, record: &log::Record) {
if !self.enabled(record.metadata()) {
return;
}
let (log, name, color): (fn(&str, &str), &str, &str) = match record.level() {
log::Level::Trace => (log, "trace", "color:plum"),
log::Level::Debug => (log, "debug", "color:cyan"),
log::Level::Warn => (warn, "warn", "color:goldenrod"),
log::Level::Info => (info, "info", "color:mediumseagreen"),
log::Level::Error => (error, "error", "color:red"),
};
// The %c is replaced by the message color
if record.level() == log::Level::Info {
// We don't print the file name and line number for info-level logs because it's used for printing the message system logs
log(&format!("%c{}\t{}", name, record.args()), color);
} else {
let file = record.file().unwrap_or_else(|| record.target());
let line = record.line().map_or_else(|| "[Unknown]".to_string(), |line| line.to_string());
let args = record.args();
log(&format!("%c{name}\t{file}:{line}\n{args}"), color);
}
}
fn flush(&self) {}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/frontend/wasm/src/helpers.rs | frontend/wasm/src/helpers.rs | use editor::messages::input_mapper::utility_types::input_keyboard::Key;
/// Translate a keyboard key from its JS name to its Rust `Key` enum
pub fn translate_key(name: &str) -> Key {
use Key::*;
trace!("Key event received: {name}");
match name {
// Writing system keys
"Digit0" | "Numpad0" => Digit0,
"Digit1" | "Numpad1" => Digit1,
"Digit2" | "Numpad2" => Digit2,
"Digit3" | "Numpad3" => Digit3,
"Digit4" | "Numpad4" => Digit4,
"Digit5" | "Numpad5" => Digit5,
"Digit6" | "Numpad6" => Digit6,
"Digit7" | "Numpad7" => Digit7,
"Digit8" | "Numpad8" => Digit8,
"Digit9" | "Numpad9" => Digit9,
//
"KeyA" => KeyA,
"KeyB" => KeyB,
"KeyC" => KeyC,
"KeyD" => KeyD,
"KeyE" => KeyE,
"KeyF" => KeyF,
"KeyG" => KeyG,
"KeyH" => KeyH,
"KeyI" => KeyI,
"KeyJ" => KeyJ,
"KeyK" => KeyK,
"KeyL" => KeyL,
"KeyM" => KeyM,
"KeyN" => KeyN,
"KeyO" => KeyO,
"KeyP" => KeyP,
"KeyQ" => KeyQ,
"KeyR" => KeyR,
"KeyS" => KeyS,
"KeyT" => KeyT,
"KeyU" => KeyU,
"KeyV" => KeyV,
"KeyW" => KeyW,
"KeyX" => KeyX,
"KeyY" => KeyY,
"KeyZ" => KeyZ,
//
"Backquote" => Backquote,
"Backslash" => Backslash,
"BracketLeft" => BracketLeft,
"BracketRight" => BracketRight,
"Comma" | "NumpadComma" => Comma,
"Equal" | "NumpadEqual" => Equal,
"Minus" | "NumpadSubtract" => Minus,
"Period" | "NumpadDecimal" => Period,
"Quote" => Quote,
"Semicolon" => Semicolon,
"Slash" | "NumpadDivide" => Slash,
// Functional keys
"AltLeft" | "AltRight" | "AltGraph" => Alt,
"MetaLeft" | "MetaRight" => Meta,
"ShiftLeft" | "ShiftRight" => Shift,
"ControlLeft" | "ControlRight" => Control,
"Backspace" | "NumpadBackspace" => Backspace,
"CapsLock" => CapsLock,
"ContextMenu" => ContextMenu,
"Enter" | "NumpadEnter" => Enter,
"Space" => Space,
"Tab" => Tab,
// Control pad keys
"Delete" => Delete,
"End" => End,
"Help" => Help,
"Home" => Home,
"Insert" => Insert,
"PageDown" => PageDown,
"PageUp" => PageUp,
// Arrow pad keys
"ArrowDown" => ArrowDown,
"ArrowLeft" => ArrowLeft,
"ArrowRight" => ArrowRight,
"ArrowUp" => ArrowUp,
// Numpad keys
// "Numpad0" => KeyNumpad0,
// "Numpad1" => KeyNumpad1,
// "Numpad2" => KeyNumpad2,
// "Numpad3" => KeyNumpad3,
// "Numpad4" => KeyNumpad4,
// "Numpad5" => KeyNumpad5,
// "Numpad6" => KeyNumpad6,
// "Numpad7" => KeyNumpad7,
// "Numpad8" => KeyNumpad8,
// "Numpad9" => KeyNumpad9,
"NumLock" => NumLock,
"NumpadAdd" => NumpadAdd,
// "NumpadBackspace" => KeyNumpadBackspace,
// "NumpadClear" => NumpadClear,
// "NumpadClearEntry" => NumpadClearEntry,
// "NumpadComma" => KeyNumpadComma,
// "NumpadDecimal" => KeyNumpadDecimal,
// "NumpadDivide" => KeyNumpadDivide,
// "NumpadEnter" => KeyNumpadEnter,
// "NumpadEqual" => KeyNumpadEqual,
"NumpadHash" => NumpadHash,
// "NumpadMemoryAdd" => NumpadMemoryAdd,
// "NumpadMemoryClear" => NumpadMemoryClear,
// "NumpadMemoryRecall" => NumpadMemoryRecall,
// "NumpadMemoryStore" => NumpadMemoryStore,
// "NumpadMemorySubtract" => NumpadMemorySubtract,
"NumpadMultiply" | "NumpadStar" => NumpadMultiply,
"NumpadParenLeft" => NumpadParenLeft,
"NumpadParenRight" => NumpadParenRight,
// "NumpadStar" => NumpadStar,
// "NumpadSubtract" => KeyNumpadSubtract,
// Function keys
"Escape" => Escape,
"F1" => F1,
"F2" => F2,
"F3" => F3,
"F4" => F4,
"F5" => F5,
"F6" => F6,
"F7" => F7,
"F8" => F8,
"F9" => F9,
"F10" => F10,
"F11" => F11,
"F12" => F12,
"F13" => F13,
"F14" => F14,
"F15" => F15,
"F16" => F16,
"F17" => F17,
"F18" => F18,
"F19" => F19,
"F20" => F20,
"F21" => F21,
"F22" => F22,
"F23" => F23,
"F24" => F24,
"Fn" => Fn,
"FnLock" => FnLock,
"PrintScreen" => PrintScreen,
"ScrollLock" => ScrollLock,
"Pause" => Pause,
// Unidentified keys
_ => Unidentified,
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/frontend/wasm/src/native_communcation.rs | frontend/wasm/src/native_communcation.rs | use editor::messages::prelude::FrontendMessage;
use js_sys::{ArrayBuffer, Uint8Array};
use wasm_bindgen::prelude::*;
use crate::editor_api::{self, EditorHandle};
#[wasm_bindgen(js_name = "receiveNativeMessage")]
pub fn receive_native_message(buffer: ArrayBuffer) {
let buffer = Uint8Array::new(buffer.as_ref()).to_vec();
match ron::from_str::<Vec<FrontendMessage>>(str::from_utf8(buffer.as_slice()).unwrap()) {
Ok(messages) => {
let callback = move |handle: &mut EditorHandle| {
for message in messages {
handle.send_frontend_message_to_js_rust_proxy(message);
}
};
editor_api::handle(callback);
}
Err(e) => log::error!("Failed to deserialize frontend messages: {e:?}"),
}
}
pub fn initialize_native_communication() {
let global = js_sys::global();
// Get the function by name
let func = js_sys::Reflect::get(&global, &JsValue::from_str("initializeNativeCommunication")).expect("Function not found");
let func = func.dyn_into::<js_sys::Function>().expect("Not a function");
// Call it
func.call0(&JsValue::NULL).expect("Function call failed");
}
pub fn send_message_to_cef(message: String) {
let global = js_sys::global();
// Get the function by name
let func = js_sys::Reflect::get(&global, &JsValue::from_str("sendNativeMessage")).expect("Function not found");
let func = func.dyn_into::<js_sys::Function>().expect("Not a function");
let array = Uint8Array::from(message.as_bytes());
let buffer = array.buffer();
// Call it with argument
func.call1(&JsValue::NULL, &JsValue::from(buffer)).expect("Function call failed");
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/frontend/wasm/src/editor_api.rs | frontend/wasm/src/editor_api.rs | #![allow(clippy::too_many_arguments)]
//
// This file is where functions are defined to be called directly from JS.
// It serves as a thin wrapper over the editor backend API that relies
// on the dispatcher messaging system and more complex Rust data types.
//
use crate::helpers::translate_key;
use crate::{EDITOR_HANDLE, EDITOR_HAS_CRASHED, Error, MESSAGE_BUFFER};
use editor::consts::FILE_EXTENSION;
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
use editor::messages::portfolio::utility_types::{FontCatalog, FontCatalogFamily, Platform};
use editor::messages::prelude::*;
use editor::messages::tool::tool_messages::tool_prelude::WidgetId;
use graph_craft::document::NodeId;
use graphene_std::raster::Image;
use graphene_std::raster::color::Color;
use js_sys::{Object, Reflect};
use serde::Serialize;
use serde_wasm_bindgen::{self, from_value};
use std::cell::RefCell;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement, ImageData, window};
#[cfg(not(feature = "native"))]
use crate::EDITOR;
#[cfg(not(feature = "native"))]
use editor::application::Editor;
static IMAGE_DATA_HASH: AtomicU64 = AtomicU64::new(0);
fn calculate_hash<T: std::hash::Hash>(t: &T) -> u64 {
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
let mut hasher = DefaultHasher::new();
t.hash(&mut hasher);
hasher.finish()
}
/// Set the random seed used by the editor by calling this from JS upon initialization.
/// This is necessary because WASM doesn't have a random number generator.
#[wasm_bindgen(js_name = setRandomSeed)]
pub fn set_random_seed(seed: u64) {
editor::application::set_uuid_seed(seed);
}
/// Provides a handle to access the raw WASM memory.
#[wasm_bindgen(js_name = wasmMemory)]
pub fn wasm_memory() -> JsValue {
wasm_bindgen::memory()
}
#[wasm_bindgen(js_name = isPlatformNative)]
pub fn is_platform_native() -> bool {
#[cfg(feature = "native")]
{
true
}
#[cfg(not(feature = "native"))]
{
false
}
}
// ============================================================================
/// This struct is, via wasm-bindgen, used by JS to interact with the editor backend. It does this by calling functions, which are `impl`ed
#[wasm_bindgen]
#[derive(Clone)]
pub struct EditorHandle {
/// This callback is called by the editor's dispatcher when directing FrontendMessages from Rust to JS
frontend_message_handler_callback: js_sys::Function,
}
// Defined separately from the `impl` block below since this `impl` block lacks the `#[wasm_bindgen]` attribute.
// Quirks in wasm-bindgen prevent functions in `#[wasm_bindgen]` `impl` blocks from being made publicly accessible from Rust.
impl EditorHandle {
pub fn send_frontend_message_to_js_rust_proxy(&self, message: FrontendMessage) {
self.send_frontend_message_to_js(message);
}
}
#[wasm_bindgen]
impl EditorHandle {
#[cfg(not(feature = "native"))]
#[wasm_bindgen(constructor)]
pub fn new(frontend_message_handler_callback: js_sys::Function) -> Self {
let editor = Editor::new();
let editor_handle = EditorHandle { frontend_message_handler_callback };
if EDITOR.with(|handle| handle.lock().ok().map(|mut guard| *guard = Some(editor))).is_none() {
log::error!("Attempted to initialize the editor more than once");
}
if EDITOR_HANDLE.with(|handle| handle.lock().ok().map(|mut guard| *guard = Some(editor_handle.clone()))).is_none() {
log::error!("Attempted to initialize the editor handle more than once");
}
editor_handle
}
#[cfg(feature = "native")]
#[wasm_bindgen(constructor)]
pub fn new(frontend_message_handler_callback: js_sys::Function) -> Self {
let editor_handle = EditorHandle { frontend_message_handler_callback };
if EDITOR_HANDLE.with(|handle| handle.lock().ok().map(|mut guard| *guard = Some(editor_handle.clone()))).is_none() {
log::error!("Attempted to initialize the editor handle more than once");
}
editor_handle
}
// Sends a message to the dispatcher in the Editor Backend
#[cfg(not(feature = "native"))]
fn dispatch<T: Into<Message>>(&self, message: T) {
// Process no further messages after a crash to avoid spamming the console
use crate::MESSAGE_BUFFER;
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
return;
}
// Get the editor, dispatch the message, and store the `FrontendMessage` queue response
let frontend_messages = EDITOR.with(|editor| {
let mut guard = editor.try_lock();
let Ok(Some(editor)) = guard.as_deref_mut() else {
// Enqueue messages which can't be procssed currently
MESSAGE_BUFFER.with_borrow_mut(|buffer| buffer.push(message.into()));
return vec![];
};
editor.handle_message(message)
});
// Send each `FrontendMessage` to the JavaScript frontend
for message in frontend_messages.into_iter() {
self.send_frontend_message_to_js(message);
}
}
#[cfg(feature = "native")]
fn dispatch<T: Into<Message>>(&self, message: T) {
let message: Message = message.into();
let Ok(serialized_message) = ron::to_string(&message) else {
log::error!("Failed to serialize message");
return;
};
crate::native_communcation::send_message_to_cef(serialized_message)
}
// Sends a FrontendMessage to JavaScript
fn send_frontend_message_to_js(&self, mut message: FrontendMessage) {
if let FrontendMessage::UpdateImageData { ref image_data } = message {
let new_hash = calculate_hash(image_data);
let prev_hash = IMAGE_DATA_HASH.load(Ordering::Relaxed);
if new_hash != prev_hash {
render_image_data_to_canvases(image_data.as_slice());
IMAGE_DATA_HASH.store(new_hash, Ordering::Relaxed);
}
return;
}
if let FrontendMessage::UpdateDocumentLayerStructure { data_buffer } = message {
message = FrontendMessage::UpdateDocumentLayerStructureJs { data_buffer: data_buffer.into() };
}
let message_type = message.to_discriminant().local_name();
let serializer = serde_wasm_bindgen::Serializer::new().serialize_large_number_types_as_bigints(true);
let message_data = message.serialize(&serializer).expect("Failed to serialize FrontendMessage");
let js_return_value = self.frontend_message_handler_callback.call2(&JsValue::null(), &JsValue::from(message_type), &message_data);
if let Err(error) = js_return_value {
error!("While handling FrontendMessage {:?}, JavaScript threw an error:\n{:?}", message.to_discriminant().local_name(), error,)
}
}
// ========================================================================
// Add additional JS -> Rust wrapper functions below as needed for calling
// the backend from the web frontend.
// ========================================================================
#[wasm_bindgen(js_name = initAfterFrontendReady)]
pub fn init_after_frontend_ready(&self, platform: String) {
#[cfg(feature = "native")]
crate::native_communcation::initialize_native_communication();
// Send initialization messages
let platform = match platform.as_str() {
"Windows" => Platform::Windows,
"Mac" => Platform::Mac,
"Linux" => Platform::Linux,
_ => Platform::Unknown,
};
self.dispatch(GlobalsMessage::SetPlatform { platform });
self.dispatch(PortfolioMessage::Init);
// Poll node graph evaluation on `requestAnimationFrame`
{
let f = std::rc::Rc::new(RefCell::new(None));
let g = f.clone();
*g.borrow_mut() = Some(Closure::new(move |_timestamp| {
#[cfg(not(feature = "native"))]
wasm_bindgen_futures::spawn_local(poll_node_graph_evaluation());
if !EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
handle(|handle| {
// Process all messages that have been queued up
let messages = MESSAGE_BUFFER.take();
for message in messages {
handle.dispatch(message);
}
handle.dispatch(InputPreprocessorMessage::CurrentTime {
timestamp: js_sys::Date::now() as u64,
});
handle.dispatch(AnimationMessage::IncrementFrameCounter);
// Used by auto-panning, but this could possibly be refactored in the future, see:
// <https://github.com/GraphiteEditor/Graphite/pull/2562#discussion_r2041102786>
handle.dispatch(BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame));
});
}
// Schedule ourself for another requestAnimationFrame callback
request_animation_frame(f.borrow().as_ref().unwrap());
}));
request_animation_frame(g.borrow().as_ref().unwrap());
}
// Auto save all documents on `setTimeout`
{
let f = std::rc::Rc::new(RefCell::new(None));
let g = f.clone();
*g.borrow_mut() = Some(Closure::new(move || {
auto_save_all_documents();
// Schedule ourself for another setTimeout callback
set_timeout(f.borrow().as_ref().unwrap(), Duration::from_secs(editor::consts::AUTO_SAVE_TIMEOUT_SECONDS));
}));
set_timeout(g.borrow().as_ref().unwrap(), Duration::from_secs(editor::consts::AUTO_SAVE_TIMEOUT_SECONDS));
}
}
#[wasm_bindgen(js_name = addPrimaryImport)]
pub fn add_primary_import(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddPrimaryImport);
}
#[wasm_bindgen(js_name = addSecondaryImport)]
pub fn add_secondary_import(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddSecondaryImport);
}
#[wasm_bindgen(js_name = addPrimaryExport)]
pub fn add_primary_export(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddPrimaryExport);
}
#[wasm_bindgen(js_name = addSecondaryExport)]
pub fn add_secondary_export(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddSecondaryExport);
}
/// Minimizes the application window to the taskbar or dock
#[wasm_bindgen(js_name = appWindowMinimize)]
pub fn app_window_minimize(&self) {
let message = AppWindowMessage::Minimize;
self.dispatch(message);
}
/// Toggles minimizing or restoring down the application window
#[wasm_bindgen(js_name = appWindowMaximize)]
pub fn app_window_maximize(&self) {
let message = AppWindowMessage::Maximize;
self.dispatch(message);
}
/// Closes the application window
#[wasm_bindgen(js_name = appWindowClose)]
pub fn app_window_close(&self) {
let message = AppWindowMessage::Close;
self.dispatch(message);
}
/// Drag the application window
#[wasm_bindgen(js_name = appWindowDrag)]
pub fn app_window_start_drag(&self) {
let message = AppWindowMessage::Drag;
self.dispatch(message);
}
/// Displays a dialog with an error message
#[wasm_bindgen(js_name = errorDialog)]
pub fn error_dialog(&self, title: String, description: String) {
let message = DialogMessage::DisplayDialogError { title, description };
self.dispatch(message);
}
/// Answer whether or not the editor has crashed
#[wasm_bindgen(js_name = hasCrashed)]
pub fn has_crashed(&self) -> bool {
EDITOR_HAS_CRASHED.load(Ordering::SeqCst)
}
/// Answer whether or not the editor is in development mode
#[wasm_bindgen(js_name = inDevelopmentMode)]
pub fn in_development_mode(&self) -> bool {
cfg!(debug_assertions)
}
/// Get the constant `FILE_EXTENSION`
#[wasm_bindgen(js_name = fileExtension)]
pub fn file_extension(&self) -> String {
FILE_EXTENSION.into()
}
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
#[wasm_bindgen(js_name = widgetValueUpdate)]
pub fn widget_value_update(&self, layout_target: JsValue, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
self.widget_value_update_helper(layout_target, widget_id, value, resend_widget)
}
/// Commit the value of a given UI widget to the history
#[wasm_bindgen(js_name = widgetValueCommit)]
pub fn widget_value_commit(&self, layout_target: JsValue, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
self.widget_value_commit_helper(layout_target, widget_id, value)
}
/// Update the value of a given UI widget, and commit it to the history
#[wasm_bindgen(js_name = widgetValueCommitAndUpdate)]
pub fn widget_value_commit_and_update(&self, layout_target: JsValue, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
self.widget_value_commit_helper(layout_target.clone(), widget_id, value.clone())?;
self.widget_value_update_helper(layout_target, widget_id, value, resend_widget)?;
Ok(())
}
pub fn widget_value_update_helper(&self, layout_target: JsValue, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
let widget_id = WidgetId(widget_id);
match (from_value(layout_target), from_value(value)) {
(Ok(layout_target), Ok(value)) => {
let message = LayoutMessage::WidgetValueUpdate { layout_target, widget_id, value };
self.dispatch(message);
if resend_widget {
let resend_message = LayoutMessage::ResendActiveWidget { layout_target, widget_id };
self.dispatch(resend_message);
}
Ok(())
}
(target, val) => Err(Error::new(&format!("Could not update UI\nDetails:\nTarget: {target:?}\nValue: {val:?}")).into()),
}
}
pub fn widget_value_commit_helper(&self, layout_target: JsValue, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
let widget_id = WidgetId(widget_id);
match (from_value(layout_target), from_value(value)) {
(Ok(layout_target), Ok(value)) => {
let message = LayoutMessage::WidgetValueCommit { layout_target, widget_id, value };
self.dispatch(message);
Ok(())
}
(target, val) => Err(Error::new(&format!("Could not commit UI\nDetails:\nTarget: {target:?}\nValue: {val:?}")).into()),
}
}
#[wasm_bindgen(js_name = loadPreferences)]
pub fn load_preferences(&self, preferences: Option<String>) {
let preferences = if let Some(preferences) = preferences {
let Ok(preferences) = serde_json::from_str(&preferences) else {
log::error!("Failed to deserialize preferences");
return;
};
Some(preferences)
} else {
None
};
let message = PreferencesMessage::Load { preferences };
self.dispatch(message);
}
#[wasm_bindgen(js_name = selectDocument)]
pub fn select_document(&self, document_id: u64) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::SelectDocument { document_id };
self.dispatch(message);
}
#[wasm_bindgen(js_name = newDocumentDialog)]
pub fn new_document_dialog(&self) {
let message = DialogMessage::RequestNewDocumentDialog;
self.dispatch(message);
}
#[wasm_bindgen(js_name = openDocumentFile)]
pub fn open_document_file(&self, document_name: String, document_serialized_content: String) {
let message = PortfolioMessage::OpenDocumentFile {
document_name: Some(document_name),
document_path: None,
document_serialized_content,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = openAutoSavedDocument)]
pub fn open_auto_saved_document(&self, document_id: u64, document_name: String, document_is_saved: bool, document_serialized_content: String, to_front: bool) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::OpenDocumentFileWithId {
document_id,
document_name: Some(document_name),
document_path: None,
document_is_auto_saved: true,
document_is_saved,
document_serialized_content,
to_front,
select_after_open: false,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = triggerAutoSave)]
pub fn trigger_auto_save(&self, document_id: u64) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::AutoSaveDocument { document_id };
self.dispatch(message);
}
#[wasm_bindgen(js_name = closeDocumentWithConfirmation)]
pub fn close_document_with_confirmation(&self, document_id: u64) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::CloseDocumentWithConfirmation { document_id };
self.dispatch(message);
}
#[wasm_bindgen(js_name = requestAboutGraphiteDialogWithLocalizedCommitDate)]
pub fn request_about_graphite_dialog_with_localized_commit_date(&self, localized_commit_date: String, localized_commit_year: String) {
let message = DialogMessage::RequestAboutGraphiteDialogWithLocalizedCommitDate {
localized_commit_date,
localized_commit_year,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = requestLicensesThirdPartyDialogWithLicenseText)]
pub fn request_licenses_third_party_dialog_with_license_text(&self, license_text: String) {
let message = DialogMessage::RequestLicensesThirdPartyDialogWithLicenseText { license_text };
self.dispatch(message);
}
/// Send new viewport info to the backend
#[wasm_bindgen(js_name = updateViewport)]
pub fn update_viewport(&self, x: f64, y: f64, width: f64, height: f64, scale: f64) {
let message = ViewportMessage::Update { x, y, width, height, scale };
self.dispatch(message);
}
/// Zoom the canvas to fit all content
#[wasm_bindgen(js_name = zoomCanvasToFitAll)]
pub fn zoom_canvas_to_fit_all(&self) {
let message = DocumentMessage::ZoomCanvasToFitAll;
self.dispatch(message);
}
/// Mouse movement within the screenspace bounds of the viewport
#[wasm_bindgen(js_name = onMouseMove)]
pub fn on_mouse_move(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// Mouse scrolling within the screenspace bounds of the viewport
#[wasm_bindgen(js_name = onWheelScroll)]
pub fn on_wheel_scroll(&self, x: f64, y: f64, mouse_keys: u8, wheel_delta_x: f64, wheel_delta_y: f64, wheel_delta_z: f64, modifiers: u8) {
let mut editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
editor_mouse_state.scroll_delta = ScrollDelta::new(wheel_delta_x, wheel_delta_y, wheel_delta_z);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// A mouse button depressed within screenspace the bounds of the viewport
#[wasm_bindgen(js_name = onMouseDown)]
pub fn on_mouse_down(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// A mouse button released
#[wasm_bindgen(js_name = onMouseUp)]
pub fn on_mouse_up(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// Mouse shaken
#[wasm_bindgen(js_name = onMouseShake)]
pub fn on_mouse_shake(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// Mouse double clicked
#[wasm_bindgen(js_name = onDoubleClick)]
pub fn on_double_click(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// A keyboard button depressed within screenspace the bounds of the viewport
#[wasm_bindgen(js_name = onKeyDown)]
pub fn on_key_down(&self, name: String, modifiers: u8, key_repeat: bool) {
let key = translate_key(&name);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
trace!("Key down {key:?}, name: {name}, modifiers: {modifiers:?}, key repeat: {key_repeat}");
let message = InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys };
self.dispatch(message);
}
/// A keyboard button released
#[wasm_bindgen(js_name = onKeyUp)]
pub fn on_key_up(&self, name: String, modifiers: u8, key_repeat: bool) {
let key = translate_key(&name);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
trace!("Key up {key:?}, name: {name}, modifiers: {modifier_keys:?}, key repeat: {key_repeat}");
let message = InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys };
self.dispatch(message);
}
/// A text box was committed
#[wasm_bindgen(js_name = onChangeText)]
pub fn on_change_text(&self, new_text: String, is_left_or_right_click: bool) -> Result<(), JsValue> {
let message = TextToolMessage::TextChange { new_text, is_left_or_right_click };
self.dispatch(message);
Ok(())
}
/// The font catalog has been loaded
#[wasm_bindgen(js_name = onFontCatalogLoad)]
pub fn on_font_catalog_load(&self, catalog: JsValue) -> Result<(), JsValue> {
// Deserializing from TS type: `{ name: string; styles: { weight: number, italic: boolean, url: string }[] }[]`
let families = serde_wasm_bindgen::from_value::<Vec<FontCatalogFamily>>(catalog)?;
let message = PortfolioMessage::FontCatalogLoaded { catalog: FontCatalog(families) };
self.dispatch(message);
Ok(())
}
/// A font has been downloaded
#[wasm_bindgen(js_name = onFontLoad)]
pub fn on_font_load(&self, font_family: String, font_style: String, data: Vec<u8>) -> Result<(), JsValue> {
let message = PortfolioMessage::FontLoaded { font_family, font_style, data };
self.dispatch(message);
Ok(())
}
/// A text box was changed
#[wasm_bindgen(js_name = updateBounds)]
pub fn update_bounds(&self, new_text: String) -> Result<(), JsValue> {
let message = TextToolMessage::UpdateBounds { new_text };
self.dispatch(message);
Ok(())
}
/// Update primary color with values on a scale from 0 to 1.
#[wasm_bindgen(js_name = updatePrimaryColor)]
pub fn update_primary_color(&self, red: f32, green: f32, blue: f32, alpha: f32) -> Result<(), JsValue> {
let Some(primary_color) = Color::from_rgbaf32(red, green, blue, alpha) else {
return Err(Error::new("Invalid color").into());
};
let message = ToolMessage::SelectWorkingColor {
color: primary_color.to_linear_srgb(),
primary: true,
};
self.dispatch(message);
Ok(())
}
/// Update secondary color with values on a scale from 0 to 1.
#[wasm_bindgen(js_name = updateSecondaryColor)]
pub fn update_secondary_color(&self, red: f32, green: f32, blue: f32, alpha: f32) -> Result<(), JsValue> {
let Some(secondary_color) = Color::from_rgbaf32(red, green, blue, alpha) else {
return Err(Error::new("Invalid color").into());
};
let message = ToolMessage::SelectWorkingColor {
color: secondary_color.to_linear_srgb(),
primary: false,
};
self.dispatch(message);
Ok(())
}
#[wasm_bindgen(js_name = clipLayer)]
pub fn clip_layer(&self, id: u64) {
let id = NodeId(id);
let message = DocumentMessage::ClipLayer { id };
self.dispatch(message);
}
/// Modify the layer selection based on the layer which is clicked while holding down the <kbd>Ctrl</kbd> and/or <kbd>Shift</kbd> modifier keys used for range selection behavior
#[wasm_bindgen(js_name = selectLayer)]
pub fn select_layer(&self, id: u64, ctrl: bool, shift: bool) {
let id = NodeId(id);
let message = DocumentMessage::SelectLayer { id, ctrl, shift };
self.dispatch(message);
}
/// Deselect all layers
#[wasm_bindgen(js_name = deselectAllLayers)]
pub fn deselect_all_layers(&self) {
let message = DocumentMessage::DeselectAllLayers;
self.dispatch(message);
}
/// Move a layer to within a folder and placed down at the given index.
/// If the folder is `None`, it is inserted into the document root.
/// If the insert index is `None`, it is inserted at the start of the folder.
#[wasm_bindgen(js_name = moveLayerInTree)]
pub fn move_layer_in_tree(&self, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
let insert_parent_id = insert_parent_id.map(NodeId);
let parent = insert_parent_id.map(LayerNodeIdentifier::new_unchecked).unwrap_or_default();
let message = DocumentMessage::MoveSelectedLayersTo {
parent,
insert_index: insert_index.unwrap_or_default(),
};
self.dispatch(message);
}
/// Set the name for the layer
#[wasm_bindgen(js_name = setLayerName)]
pub fn set_layer_name(&self, id: u64, name: String) {
let layer = LayerNodeIdentifier::new_unchecked(NodeId(id));
let message = NodeGraphMessage::SetDisplayName {
node_id: layer.to_node(),
alias: name,
skip_adding_history_step: false,
};
self.dispatch(message);
}
/// Translates document (in viewport coords)
#[wasm_bindgen(js_name = panCanvasAbortPrepare)]
pub fn pan_canvas_abort_prepare(&self, x_not_y_axis: bool) {
let message = NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis };
self.dispatch(message);
}
#[wasm_bindgen(js_name = panCanvasAbort)]
pub fn pan_canvas_abort(&self, x_not_y_axis: bool) {
let message = NavigationMessage::CanvasPanAbort { x_not_y_axis };
self.dispatch(message);
}
/// Translates document (in viewport coords)
#[wasm_bindgen(js_name = panCanvas)]
pub fn pan_canvas(&self, delta_x: f64, delta_y: f64) {
let message = NavigationMessage::CanvasPan { delta: (delta_x, delta_y).into() };
self.dispatch(message);
}
/// Translates document (in viewport coords)
#[wasm_bindgen(js_name = panCanvasByFraction)]
pub fn pan_canvas_by_fraction(&self, delta_x: f64, delta_y: f64) {
let message = NavigationMessage::CanvasPanByViewportFraction { delta: (delta_x, delta_y).into() };
self.dispatch(message);
}
/// Merge the selected nodes into a subnetwork
#[wasm_bindgen(js_name = mergeSelectedNodes)]
pub fn merge_nodes(&self) {
let message = NodeGraphMessage::MergeSelectedNodes;
self.dispatch(message);
}
/// Creates a new document node in the node graph
#[wasm_bindgen(js_name = createNode)]
pub fn create_node(&self, node_type: String, x: i32, y: i32) {
let id = NodeId::new();
let message = NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(id),
node_type,
xy: Some((x / 24, y / 24)),
add_transaction: true,
};
self.dispatch(message);
}
/// Respond to selection read
#[wasm_bindgen(js_name = readSelection)]
pub fn read_selection(&self, content: Option<String>, cut: bool) {
let message = ClipboardMessage::ReadSelection { content, cut };
self.dispatch(message);
}
/// Paste from a serialized JSON representation
#[wasm_bindgen(js_name = pasteText)]
pub fn paste_text(&self, data: String) {
let message = ClipboardMessage::ReadClipboard {
content: ClipboardContentRaw::Text(data),
};
self.dispatch(message);
}
/// Pastes an image
#[wasm_bindgen(js_name = pasteImage)]
pub fn paste_image(
&self,
name: Option<String>,
image_data: Vec<u8>,
width: u32,
height: u32,
mouse_x: Option<f64>,
mouse_y: Option<f64>,
insert_parent_id: Option<u64>,
insert_index: Option<usize>,
) {
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
let image = graphene_std::raster::Image::from_image_data(&image_data, width, height);
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
let insert_parent_id = NodeId(insert_parent_id);
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
Some((parent, insert_index))
} else {
None
};
let message = PortfolioMessage::PasteImage {
name,
image,
mouse,
parent_and_insert_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = pasteSvg)]
pub fn paste_svg(&self, name: Option<String>, svg: String, mouse_x: Option<f64>, mouse_y: Option<f64>, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
let insert_parent_id = NodeId(insert_parent_id);
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
Some((parent, insert_index))
} else {
None
};
let message = PortfolioMessage::PasteSvg {
name,
svg,
mouse,
parent_and_insert_index,
};
self.dispatch(message);
}
/// Toggle visibility of a layer or node given its node ID
#[wasm_bindgen(js_name = toggleNodeVisibilityLayerPanel)]
pub fn toggle_node_visibility_layer(&self, id: u64) {
let node_id = NodeId(id);
let message = NodeGraphMessage::ToggleVisibility { node_id };
self.dispatch(message);
}
/// Pin or unpin a node given its node ID
#[wasm_bindgen(js_name = setNodePinned)]
pub fn set_node_pinned(&self, id: u64, pinned: bool) {
self.dispatch(DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned });
}
/// Delete a layer or node given its node ID
#[wasm_bindgen(js_name = deleteNode)]
pub fn delete_node(&self, id: u64) {
self.dispatch(DocumentMessage::DeleteNode { node_id: NodeId(id) });
}
/// Toggle lock state of a layer from the layer list
#[wasm_bindgen(js_name = toggleLayerLock)]
pub fn toggle_layer_lock(&self, node_id: u64) {
let message = NodeGraphMessage::ToggleLocked { node_id: NodeId(node_id) };
self.dispatch(message);
}
/// Toggle expansions state of a layer from the layer list
#[wasm_bindgen(js_name = toggleLayerExpansion)]
pub fn toggle_layer_expansion(&self, id: u64, recursive: bool) {
let id = NodeId(id);
let message = DocumentMessage::ToggleLayerExpansion { id, recursive };
self.dispatch(message);
}
/// Set the active panel to the most recently clicked panel
#[wasm_bindgen(js_name = setActivePanel)]
pub fn set_active_panel(&self, panel: String) {
let message = PortfolioMessage::SetActivePanel { panel: panel.into() };
self.dispatch(message);
}
/// Toggle display type for a layer
#[wasm_bindgen(js_name = setToNodeOrLayer)]
pub fn set_to_node_or_layer(&self, id: u64, is_layer: bool) {
self.dispatch(DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer });
}
/// Set the name of an import or export
#[wasm_bindgen(js_name = setImportName)]
pub fn set_import_name(&self, index: usize, name: String) {
let message = NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Import(index),
};
self.dispatch(message);
}
/// Set the name of an export
#[wasm_bindgen(js_name = setExportName)]
pub fn set_export_name(&self, index: usize, name: String) {
let message = NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Export(index),
};
self.dispatch(message);
}
}
// ============================================================================
#[wasm_bindgen(js_name = evaluateMathExpression)]
pub fn evaluate_math_expression(expression: &str) -> Option<f64> {
let value = math_parser::evaluate(expression)
.inspect_err(|err| error!("Math parser error on \"{expression}\": {err}"))
.ok()?
.0
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err} "))
.ok()?;
let Some(real) = value.as_real() else {
error!("{value} was not a real; skipping.");
return None;
};
Some(real)
}
/// Helper function for calling JS's `requestAnimationFrame` with the given closure
fn request_animation_frame(f: &Closure<dyn FnMut(f64)>) {
web_sys::window()
.expect("No global `window` exists")
.request_animation_frame(f.as_ref().unchecked_ref())
.expect("Failed to call `requestAnimationFrame`");
}
/// Helper function for calling JS's `setTimeout` with the given closure and delay
fn set_timeout(f: &Closure<dyn FnMut()>, delay: Duration) {
let delay = delay.clamp(Duration::ZERO, Duration::from_millis(i32::MAX as u64)).as_millis() as i32;
web_sys::window()
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | true |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/lib.rs | libraries/rawkit/src/lib.rs | pub mod decoder;
pub mod demosaicing;
pub mod metadata;
pub mod postprocessing;
pub mod preprocessing;
pub mod processing;
pub mod tiff;
use crate::metadata::identify::CameraModel;
use processing::{Pixel, PixelTransform, RawPixel, RawPixelTransform};
use rawkit_proc_macros::Tag;
use std::io::{Read, Seek};
use thiserror::Error;
use tiff::file::TiffRead;
use tiff::tags::{Compression, ImageLength, ImageWidth, Orientation, StripByteCounts, SubIfd, Tag, ThumbnailLength, ThumbnailOffset};
use tiff::values::{CompressionValue, OrientationValue};
use tiff::{Ifd, TiffError};
pub(crate) const CHANNELS_IN_RGB: usize = 3;
pub(crate) type Histogram = [[usize; 0x2000]; CHANNELS_IN_RGB];
pub enum ThumbnailFormat {
Jpeg,
Unsupported,
}
/// A thumbnail image extracted from the raw file. This is usually a JPEG image.
pub struct ThumbnailImage {
pub data: Vec<u8>,
pub format: ThumbnailFormat,
}
/// The amount of black level to be subtracted from Raw Image.
pub enum SubtractBlack {
/// Don't subtract any value.
None,
/// Subtract a singular value for all pixels in Bayer CFA Grid.
Value(u16),
/// Subtract the appropriate value for pixels in Bayer CFA Grid.
CfaGrid([u16; 4]),
}
/// Represents a Raw Image along with its metadata.
pub struct RawImage {
/// Raw pixel data stored in linear fashion.
pub data: Vec<u16>,
/// Width of the raw image.
pub width: usize,
/// Height of the raw image.
pub height: usize,
/// Bayer CFA pattern used to arrange pixels in [`RawImage::data`].
///
/// It encodes Red, Blue and Green as 0, 1, and 2 respectively.
pub cfa_pattern: [u8; 4],
/// Transformation to be applied to negate the orientation of camera.
pub orientation: OrientationValue,
/// The maximum possible value of pixel that the camera sensor could give.
pub maximum: u16,
/// The minimum possible value of pixel that the camera sensor could give.
///
/// Used to subtract the black level from the raw image.
pub black: SubtractBlack,
/// Information regarding the company and model of the camera.
pub camera_model: Option<CameraModel>,
/// White balance specified in the metadata of the raw file.
///
/// It represents the 4 values of CFA Grid which follows the same pattern as [`RawImage::cfa_pattern`].
pub camera_white_balance: Option<[f64; 4]>,
/// White balance of the raw image.
///
/// It is the same as [`RawImage::camera_white_balance`] if the raw file contains the metadata.
/// Otherwise it falls back to calculating the white balance from the color space conversion matrix.
///
/// It represents the 4 values of CFA Grid which follows the same pattern as [`RawImage::cfa_pattern`].
pub white_balance: Option<[f64; 4]>,
/// Color space conversion matrix to convert from camera's color space to sRGB.
pub camera_to_rgb: Option<[[f64; 3]; 3]>,
}
/// Represents the final RGB Image.
pub struct Image<T> {
/// Pixel data stored in a linear fashion.
pub data: Vec<T>,
/// Width of the image.
pub width: usize,
/// Height of the image.
pub height: usize,
/// The number of color channels in the image.
///
/// We can assume this will be 3 for all non-obscure, modern cameras.
/// See <https://github.com/GraphiteEditor/Graphite/pull/1923#discussion_r1725070342> for more information.
pub channels: u8,
/// The transformation required to orient the image correctly.
///
/// This will be [`OrientationValue::Horizontal`] after the orientation step is applied.
pub orientation: OrientationValue,
}
#[allow(dead_code)]
#[derive(Tag)]
struct ArwIfd {
image_width: ImageWidth,
image_height: ImageLength,
compression: Compression,
strip_byte_counts: StripByteCounts,
}
impl RawImage {
/// Create a [`RawImage`] from an input stream.
///
/// Decodes the contents of `reader` and extracts raw pixel data and metadata.
pub fn decode<R: Read + Seek>(reader: &mut R) -> Result<RawImage, DecoderError> {
let mut file = TiffRead::new(reader)?;
let ifd = Ifd::new_first_ifd(&mut file)?;
let camera_model = metadata::identify::identify_camera_model(&ifd, &mut file).unwrap();
let orientation = ifd.get_value::<Orientation, _>(&mut file)?;
let mut raw_image = if camera_model.model == "DSLR-A100" {
decoder::arw1::decode_a100(ifd, &mut file)
} else {
let sub_ifd = ifd.get_value::<SubIfd, _>(&mut file)?;
let arw_ifd = sub_ifd.get_value::<ArwIfd, _>(&mut file)?;
if arw_ifd.compression == CompressionValue::Uncompressed {
decoder::uncompressed::decode(sub_ifd, &mut file)
} else if arw_ifd.strip_byte_counts[0] == arw_ifd.image_width * arw_ifd.image_height {
decoder::arw2::decode(sub_ifd, &mut file)
} else {
// TODO: implement for arw 1.
todo!()
}
};
raw_image.camera_model = Some(camera_model);
raw_image.orientation = orientation;
raw_image.calculate_conversion_matrices();
Ok(raw_image)
}
/// Extracts the thumbnail image from the raw file.
pub fn extract_thumbnail<R: Read + Seek>(reader: &mut R) -> Result<ThumbnailImage, DecoderError> {
let mut file = TiffRead::new(reader)?;
let ifd = Ifd::new_first_ifd(&mut file)?;
// TODO: ARW files Store the thumbnail offset and length in the first IFD. Add support for other file types in the future.
let thumbnail_offset = ifd.get_value::<ThumbnailOffset, _>(&mut file)?;
let thumbnail_length = ifd.get_value::<ThumbnailLength, _>(&mut file)?;
file.seek_from_start(thumbnail_offset)?;
let mut thumbnail_data = vec![0; thumbnail_length as usize];
file.read_exact(&mut thumbnail_data)?;
// Check the first two bytes to determine the format of the thumbnail.
// JPEG format starts with 0xFF, 0xD8.
if thumbnail_data[0..2] == [0xFF, 0xD8] {
Ok(ThumbnailImage {
data: thumbnail_data,
format: ThumbnailFormat::Jpeg,
})
} else {
Err(DecoderError::UnsupportedThumbnailFormat)
}
}
/// Converts the [`RawImage`] to an [`Image`] with 8 bit resolution for each channel.
///
/// Applies all the processing steps to finally get RGB pixel data.
pub fn process_8bit(self) -> Image<u8> {
let image = self.process_16bit();
Image {
channels: image.channels,
data: image.data.iter().map(|x| (x >> 8) as u8).collect(),
width: image.width,
height: image.height,
orientation: image.orientation,
}
}
/// Converts the [`RawImage`] to an [`Image`] with 16 bit resolution for each channel.
///
/// Applies all the processing steps to finally get RGB pixel data.
pub fn process_16bit(self) -> Image<u16> {
let subtract_black = self.subtract_black_fn();
let scale_white_balance = self.scale_white_balance_fn();
let scale_to_16bit = self.scale_to_16bit_fn();
let raw_image = self.apply((subtract_black, scale_white_balance, scale_to_16bit));
let convert_to_rgb = raw_image.convert_to_rgb_fn();
let mut record_histogram = raw_image.record_histogram_fn();
let image = raw_image.demosaic_and_apply((convert_to_rgb, &mut record_histogram));
let gamma_correction = image.gamma_correction_fn(&record_histogram.histogram);
if image.orientation == OrientationValue::Horizontal {
image.apply(gamma_correction)
} else {
image.transform_and_apply(gamma_correction)
}
}
}
impl RawImage {
pub fn apply(mut self, mut transform: impl RawPixelTransform) -> RawImage {
for (index, value) in self.data.iter_mut().enumerate() {
let pixel = RawPixel {
value: *value,
row: index / self.width,
column: index % self.width,
};
*value = transform.apply(pixel);
}
self
}
pub fn demosaic_and_apply(self, mut transform: impl PixelTransform) -> Image<u16> {
let mut image = vec![0; self.width * self.height * 3];
for Pixel { values, row, column } in self.linear_demosaic_iter().map(|mut pixel| {
pixel.values = transform.apply(pixel);
pixel
}) {
let pixel_index = row * self.width + column;
image[3 * pixel_index..3 * (pixel_index + 1)].copy_from_slice(&values);
}
Image {
channels: 3,
data: image,
width: self.width,
height: self.height,
orientation: self.orientation,
}
}
}
impl Image<u16> {
pub fn apply(mut self, mut transform: impl PixelTransform) -> Image<u16> {
for (index, values) in self.data.chunks_exact_mut(3).enumerate() {
let pixel = Pixel {
values: values.try_into().unwrap(),
row: index / self.width,
column: index % self.width,
};
values.copy_from_slice(&transform.apply(pixel));
}
self
}
pub fn transform_and_apply(self, mut transform: impl PixelTransform) -> Image<u16> {
let mut image = vec![0; self.width * self.height * 3];
let (width, height, iter) = self.orientation_iter();
for Pixel { values, row, column } in iter.map(|mut pixel| {
pixel.values = transform.apply(pixel);
pixel
}) {
let pixel_index = row * width + column;
image[3 * pixel_index..3 * (pixel_index + 1)].copy_from_slice(&values);
}
Image {
channels: 3,
data: image,
width,
height,
orientation: OrientationValue::Horizontal,
}
}
}
#[derive(Error, Debug)]
pub enum DecoderError {
#[error("An error occurred when trying to parse the TIFF format")]
TiffError(#[from] TiffError),
#[error("An error occurred when converting integer from one type to another")]
ConversionError(#[from] std::num::TryFromIntError),
#[error("An IO Error ocurred")]
IoError(#[from] std::io::Error),
#[error("The thumbnail format is unsupported")]
UnsupportedThumbnailFormat,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/processing.rs | libraries/rawkit/src/processing.rs | use crate::CHANNELS_IN_RGB;
#[derive(Clone, Copy)]
pub struct RawPixel {
pub value: u16,
pub row: usize,
pub column: usize,
}
#[derive(Clone, Copy)]
pub struct Pixel {
pub values: [u16; CHANNELS_IN_RGB],
pub row: usize,
pub column: usize,
}
pub trait RawPixelTransform {
fn apply(&mut self, pixel: RawPixel) -> u16;
}
impl<T: Fn(RawPixel) -> u16> RawPixelTransform for T {
fn apply(&mut self, pixel: RawPixel) -> u16 {
self(pixel)
}
}
macro_rules! impl_raw_pixel_transform {
($($idx:tt $t:tt),+) => {
impl<$($t,)+> RawPixelTransform for ($($t,)+)
where
$($t: RawPixelTransform,)+
{
fn apply(&mut self, mut pixel: RawPixel) -> u16 {
$(pixel.value = self.$idx.apply(pixel);)*
pixel.value
}
}
};
}
impl_raw_pixel_transform!(0 A);
impl_raw_pixel_transform!(0 A, 1 B);
impl_raw_pixel_transform!(0 A, 1 B, 2 C);
impl_raw_pixel_transform!(0 A, 1 B, 2 C, 3 D);
impl_raw_pixel_transform!(0 A, 1 B, 2 C, 3 D, 4 E);
impl_raw_pixel_transform!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F);
impl_raw_pixel_transform!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G);
impl_raw_pixel_transform!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H);
pub trait PixelTransform {
fn apply(&mut self, pixel: Pixel) -> [u16; CHANNELS_IN_RGB];
}
impl<T: Fn(Pixel) -> [u16; CHANNELS_IN_RGB]> PixelTransform for T {
fn apply(&mut self, pixel: Pixel) -> [u16; CHANNELS_IN_RGB] {
self(pixel)
}
}
macro_rules! impl_pixel_transform {
($($idx:tt $t:tt),+) => {
impl<$($t,)+> PixelTransform for ($($t,)+)
where
$($t: PixelTransform,)+
{
fn apply(&mut self, mut pixel: Pixel) -> [u16; CHANNELS_IN_RGB] {
$(pixel.values = self.$idx.apply(pixel);)*
pixel.values
}
}
};
}
impl_pixel_transform!(0 A);
impl_pixel_transform!(0 A, 1 B);
impl_pixel_transform!(0 A, 1 B, 2 C);
impl_pixel_transform!(0 A, 1 B, 2 C, 3 D);
impl_pixel_transform!(0 A, 1 B, 2 C, 3 D, 4 E);
impl_pixel_transform!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F);
impl_pixel_transform!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G);
impl_pixel_transform!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H);
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/demosaicing/linear_demosaicing.rs | libraries/rawkit/src/demosaicing/linear_demosaicing.rs | use crate::{Pixel, RawImage};
fn average(data: &[u16], indexes: impl Iterator<Item = i64>) -> u16 {
let mut sum = 0;
let mut count = 0;
for index in indexes {
if index >= 0 && (index as usize) < data.len() {
sum += data[index as usize] as u32;
count += 1;
}
}
(sum / count) as u16
}
impl RawImage {
pub fn linear_demosaic_iter(&self) -> impl Iterator<Item = Pixel> + use<'_> {
match self.cfa_pattern {
[0, 1, 1, 2] => self.linear_demosaic_rggb_iter(),
_ => todo!(),
}
}
fn linear_demosaic_rggb_iter(&self) -> impl Iterator<Item = Pixel> + use<'_> {
let width = self.width as i64;
let height = self.height as i64;
(0..height).flat_map(move |row| {
let row_by_width = row * width;
(0..width).map(move |column| {
let pixel_index = row_by_width + column;
let vertical_indexes = [pixel_index + width, pixel_index - width];
let horizontal_indexes = [pixel_index + 1, pixel_index - 1];
let cross_indexes = [pixel_index + width, pixel_index - width, pixel_index + 1, pixel_index - 1];
let diagonal_indexes = [pixel_index + width + 1, pixel_index - width + 1, pixel_index + width - 1, pixel_index - width - 1];
let pixel_index = pixel_index as usize;
match (row % 2 == 0, column % 2 == 0) {
(true, true) => Pixel {
values: [
self.data[pixel_index],
average(&self.data, cross_indexes.into_iter()),
average(&self.data, diagonal_indexes.into_iter()),
],
row: row as usize,
column: column as usize,
},
(true, false) => Pixel {
values: [
average(&self.data, horizontal_indexes.into_iter()),
self.data[pixel_index],
average(&self.data, vertical_indexes.into_iter()),
],
row: row as usize,
column: column as usize,
},
(false, true) => Pixel {
values: [
average(&self.data, vertical_indexes.into_iter()),
self.data[pixel_index],
average(&self.data, horizontal_indexes.into_iter()),
],
row: row as usize,
column: column as usize,
},
(false, false) => Pixel {
values: [
average(&self.data, diagonal_indexes.into_iter()),
average(&self.data, cross_indexes.into_iter()),
self.data[pixel_index],
],
row: row as usize,
column: column as usize,
},
}
})
})
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/demosaicing/mod.rs | libraries/rawkit/src/demosaicing/mod.rs | pub mod linear_demosaicing;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/metadata/identify.rs | libraries/rawkit/src/metadata/identify.rs | use crate::tiff::file::TiffRead;
use crate::tiff::tags::{Make, Model, Tag};
use crate::tiff::{Ifd, TiffError};
use rawkit_proc_macros::Tag;
use std::io::{Read, Seek};
const COMPANY_NAMES: [&str; 22] = [
"AgfaPhoto",
"Canon",
"Casio",
"Epson",
"Fujifilm",
"Mamiya",
"Minolta",
"Motorola",
"Kodak",
"Konica",
"Leica",
"Nikon",
"Nokia",
"Olympus",
"Ricoh",
"Pentax",
"Phase One",
"Samsung",
"Sigma",
"Sinar",
"Sony",
"YI",
];
#[allow(dead_code)]
#[derive(Tag)]
struct CameraModelIfd {
make: Make,
model: Model,
}
pub struct CameraModel {
pub make: String,
pub model: String,
}
pub fn identify_camera_model<R: Read + Seek>(ifd: &Ifd, file: &mut TiffRead<R>) -> Option<CameraModel> {
let mut ifd = ifd.get_value::<CameraModelIfd, _>(file).unwrap();
ifd.make.make_ascii_lowercase();
for company_name in COMPANY_NAMES {
let lowercase_company_name = company_name.to_ascii_lowercase();
if ifd.make.contains(&lowercase_company_name) {
return Some(CameraModel {
make: company_name.to_string(),
model: ifd.model,
});
}
}
None
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/metadata/camera_data.rs | libraries/rawkit/src/metadata/camera_data.rs | use crate::RawImage;
use rawkit_proc_macros::build_camera_data;
pub struct CameraData {
pub black: u16,
pub maximum: u16,
pub xyz_to_camera: [i16; 9],
}
impl CameraData {
const DEFAULT: CameraData = CameraData {
black: 0,
maximum: 0,
xyz_to_camera: [0; 9],
};
}
const CAMERA_DATA: [(&str, CameraData); 40] = build_camera_data!();
const RGB_TO_XYZ: [[f64; 3]; 3] = [
// Matrix:
[0.412453, 0.357580, 0.180423],
[0.212671, 0.715160, 0.072169],
[0.019334, 0.119193, 0.950227],
];
impl RawImage {
pub fn calculate_conversion_matrices(&mut self) {
let Some(ref camera_model) = self.camera_model else { return };
let camera_name_needle = camera_model.make.to_owned() + " " + &camera_model.model;
let xyz_to_camera = CAMERA_DATA
.iter()
.find(|(camera_name_haystack, _)| camera_name_needle == *camera_name_haystack)
.map(|(_, data)| data.xyz_to_camera.map(|x| (x as f64) / 10_000.));
let Some(xyz_to_camera) = xyz_to_camera else { return };
let mut rgb_to_camera = [[0.; 3]; 3];
for i in 0..3 {
for j in 0..3 {
for k in 0..3 {
rgb_to_camera[i][j] += RGB_TO_XYZ[k][j] * xyz_to_camera[i * 3 + k];
}
}
}
let white_balance_multiplier = rgb_to_camera.map(|x| 1. / x.iter().sum::<f64>());
for (index, row) in rgb_to_camera.iter_mut().enumerate() {
*row = row.map(|x| x * white_balance_multiplier[index]);
}
let camera_to_rgb = transpose(pseudoinverse(rgb_to_camera));
let cfa_white_balance_multiplier = if let Some(white_balance) = self.camera_white_balance {
white_balance
} else {
self.cfa_pattern.map(|index| white_balance_multiplier[index as usize])
};
self.white_balance = Some(cfa_white_balance_multiplier);
self.camera_to_rgb = Some(camera_to_rgb);
}
}
#[allow(clippy::needless_range_loop)]
fn pseudoinverse<const N: usize>(matrix: [[f64; 3]; N]) -> [[f64; 3]; N] {
let mut output_matrix = [[0.; 3]; N];
let mut work = [[0.; 6]; 3];
for i in 0..3 {
for j in 0..6 {
work[i][j] = if j == i + 3 { 1. } else { 0. };
}
for j in 0..3 {
for k in 0..N {
work[i][j] += matrix[k][i] * matrix[k][j];
}
}
}
for i in 0..3 {
let num = work[i][i];
for j in 0..6 {
work[i][j] /= num;
}
for k in 0..3 {
if k == i {
continue;
}
let num = work[k][i];
for j in 0..6 {
work[k][j] -= work[i][j] * num;
}
}
}
for i in 0..N {
for j in 0..3 {
output_matrix[i][j] = 0.;
for k in 0..3 {
output_matrix[i][j] += work[j][k + 3] * matrix[i][k];
}
}
}
output_matrix
}
fn transpose<const N: usize>(matrix: [[f64; 3]; N]) -> [[f64; N]; 3] {
let mut output_matrix = [[0.; N]; 3];
for (i, row) in matrix.iter().enumerate() {
for (j, &value) in row.iter().enumerate() {
output_matrix[j][i] = value;
}
}
output_matrix
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/metadata/mod.rs | libraries/rawkit/src/metadata/mod.rs | pub mod camera_data;
pub mod identify;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/preprocessing/scale_to_16bit.rs | libraries/rawkit/src/preprocessing/scale_to_16bit.rs | use crate::{RawImage, RawPixel, SubtractBlack};
impl RawImage {
pub fn scale_to_16bit_fn(&self) -> impl Fn(RawPixel) -> u16 + use<> {
let black_level = match self.black {
SubtractBlack::CfaGrid(x) => x,
_ => unreachable!(),
};
let maximum = self.maximum - black_level.iter().max().unwrap();
let scale_to_16bit_multiplier = if maximum > 0 { u16::MAX as f64 / maximum as f64 } else { 1. };
move |pixel: RawPixel| ((pixel.value as f64) * scale_to_16bit_multiplier).min(u16::MAX as f64).max(0.) as u16
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/preprocessing/mod.rs | libraries/rawkit/src/preprocessing/mod.rs | pub mod scale_to_16bit;
pub mod scale_white_balance;
pub mod subtract_black;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/preprocessing/scale_white_balance.rs | libraries/rawkit/src/preprocessing/scale_white_balance.rs | use crate::{RawImage, RawPixel};
impl RawImage {
pub fn scale_white_balance_fn(&self) -> impl Fn(RawPixel) -> u16 + use<> {
let Some(mut white_balance) = self.white_balance else { todo!() };
if white_balance[1] == 0. {
white_balance[1] = 1.;
}
// TODO: Move this at its correct location when highlights are implemented correctly.
let highlight = 0;
let normalization_factor = if highlight == 0 {
white_balance.into_iter().fold(f64::INFINITY, f64::min)
} else {
white_balance.into_iter().fold(f64::NEG_INFINITY, f64::max)
};
let normalized_white_balance = if normalization_factor > 0.00001 {
white_balance.map(|x| x / normalization_factor)
} else {
[1., 1., 1., 1.]
};
move |pixel: RawPixel| {
let cfa_index = 2 * (pixel.row % 2) + (pixel.column % 2);
((pixel.value as f64) * normalized_white_balance[cfa_index]).min(u16::MAX as f64).max(0.) as u16
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/preprocessing/subtract_black.rs | libraries/rawkit/src/preprocessing/subtract_black.rs | use crate::RawPixel;
use crate::{RawImage, SubtractBlack};
impl RawImage {
pub fn subtract_black_fn(&self) -> impl Fn(RawPixel) -> u16 + use<> {
match self.black {
SubtractBlack::CfaGrid(black_levels) => move |pixel: RawPixel| pixel.value.saturating_sub(black_levels[2 * (pixel.row % 2) + (pixel.column % 2)]),
_ => todo!(),
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/decoder/arw2.rs | libraries/rawkit/src/decoder/arw2.rs | use crate::tiff::file::{Endian, TiffRead};
use crate::tiff::tags::{BitsPerSample, CfaPattern, CfaPatternDim, Compression, ImageLength, ImageWidth, SonyToneCurve, StripByteCounts, StripOffsets, Tag, WhiteBalanceRggbLevels};
use crate::tiff::values::{CompressionValue, CurveLookupTable};
use crate::tiff::{Ifd, TiffError};
use crate::{OrientationValue, RawImage, SubtractBlack};
use rawkit_proc_macros::Tag;
use std::io::{Read, Seek};
#[allow(dead_code)]
#[derive(Tag)]
struct Arw2Ifd {
image_width: ImageWidth,
image_height: ImageLength,
bits_per_sample: BitsPerSample,
compression: Compression,
cfa_pattern: CfaPattern,
cfa_pattern_dim: CfaPatternDim,
strip_offsets: StripOffsets,
strip_byte_counts: StripByteCounts,
sony_tone_curve: SonyToneCurve,
white_balance_levels: Option<WhiteBalanceRggbLevels>,
}
pub fn decode<R: Read + Seek>(ifd: Ifd, file: &mut TiffRead<R>) -> RawImage {
let ifd = ifd.get_value::<Arw2Ifd, _>(file).unwrap();
assert!(ifd.strip_offsets.len() == ifd.strip_byte_counts.len());
assert!(ifd.strip_offsets.len() == 1);
assert!(ifd.compression == CompressionValue::Sony_ARW_Compressed);
let image_width: usize = ifd.image_width.try_into().unwrap();
let image_height: usize = ifd.image_height.try_into().unwrap();
let bits_per_sample: usize = ifd.bits_per_sample.into();
assert!(bits_per_sample == 12);
let [cfa_pattern_width, cfa_pattern_height] = ifd.cfa_pattern_dim;
assert!(cfa_pattern_width == 2 && cfa_pattern_height == 2);
file.seek_from_start(ifd.strip_offsets[0]).unwrap();
let mut image = sony_arw2_load_raw(image_width, image_height, ifd.sony_tone_curve, file).unwrap();
// Converting the bps from 12 to 14 so that ARW 2.3.1 and 2.3.5 have the same 14 bps.
image.iter_mut().for_each(|x| *x <<= 2);
RawImage {
data: image,
width: image_width,
height: image_height,
cfa_pattern: ifd.cfa_pattern.try_into().unwrap(),
maximum: (1 << 14) - 1,
black: SubtractBlack::CfaGrid([512, 512, 512, 512]), // TODO: Find the correct way to do this
orientation: OrientationValue::Horizontal,
camera_model: None,
camera_white_balance: ifd.white_balance_levels.map(|arr| arr.map(|x| x as f64)),
white_balance: None,
camera_to_rgb: None,
}
}
fn as_u32(buffer: &[u8], endian: Endian) -> Option<u32> {
Some(match endian {
Endian::Little => u32::from_le_bytes(buffer.try_into().ok()?),
Endian::Big => u32::from_be_bytes(buffer.try_into().ok()?),
})
}
fn as_u16(buffer: &[u8], endian: Endian) -> Option<u16> {
Some(match endian {
Endian::Little => u16::from_le_bytes(buffer.try_into().ok()?),
Endian::Big => u16::from_be_bytes(buffer.try_into().ok()?),
})
}
fn sony_arw2_load_raw<R: Read + Seek>(width: usize, height: usize, curve: CurveLookupTable, file: &mut TiffRead<R>) -> Option<Vec<u16>> {
let mut image = vec![0_u16; height * width];
let mut data = vec![0_u8; width + 1];
for row in 0..height {
file.read_exact(&mut data[0..width]).unwrap();
let mut column = 0;
let mut data_index = 0;
while column < width - 30 {
let data_value = as_u32(&data[data_index..][..4], file.endian()).unwrap();
let max = (0x7ff & data_value) as u16;
let min = (0x7ff & data_value >> 11) as u16;
let index_to_set_max = 0x0f & data_value >> 22;
let index_to_set_min = 0x0f & data_value >> 26;
let max_minus_min = max as i32 - min as i32;
let shift_by_bits = (0..4).find(|&shift| (0x80 << shift) > max_minus_min).unwrap_or(4);
let mut pixels = [0_u16; 16];
let mut bit = 30;
for (i, pixel) in pixels.iter_mut().enumerate() {
*pixel = match () {
_ if i as u32 == index_to_set_max => max,
_ if i as u32 == index_to_set_min => min,
_ => {
let result = as_u16(&data[(data_index + (bit >> 3))..][..2], file.endian()).unwrap();
let result = ((result >> (bit & 7)) & 0x07f) << shift_by_bits;
bit += 7;
(result + min).min(0x7ff)
}
};
}
for value in pixels {
image[row * width + column] = curve.get((value << 1).into()) >> 2;
// Skip between interlaced columns
column += 2;
}
// Switch to the opposite interlaced columns
column -= if column & 1 == 0 { 31 } else { 1 };
data_index += 16;
}
}
Some(image)
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/decoder/uncompressed.rs | libraries/rawkit/src/decoder/uncompressed.rs | use crate::tiff::file::TiffRead;
use crate::tiff::tags::{BitsPerSample, BlackLevel, CfaPattern, CfaPatternDim, Compression, ImageLength, ImageWidth, RowsPerStrip, StripByteCounts, StripOffsets, Tag, WhiteBalanceRggbLevels};
use crate::tiff::values::CompressionValue;
use crate::tiff::{Ifd, TiffError};
use crate::{OrientationValue, RawImage, SubtractBlack};
use rawkit_proc_macros::Tag;
use std::io::{Read, Seek};
#[allow(dead_code)]
#[derive(Tag)]
struct ArwUncompressedIfd {
image_width: ImageWidth,
image_height: ImageLength,
rows_per_strip: RowsPerStrip,
bits_per_sample: BitsPerSample,
compression: Compression,
black_level: BlackLevel,
cfa_pattern: CfaPattern,
cfa_pattern_dim: CfaPatternDim,
strip_offsets: StripOffsets,
strip_byte_counts: StripByteCounts,
white_balance_levels: Option<WhiteBalanceRggbLevels>,
}
pub fn decode<R: Read + Seek>(ifd: Ifd, file: &mut TiffRead<R>) -> RawImage {
let ifd = ifd.get_value::<ArwUncompressedIfd, _>(file).unwrap();
assert!(ifd.strip_offsets.len() == ifd.strip_byte_counts.len());
assert!(ifd.strip_offsets.len() == 1);
assert!(ifd.compression == CompressionValue::Uncompressed);
let image_width: usize = ifd.image_width.try_into().unwrap();
let image_height: usize = ifd.image_height.try_into().unwrap();
let rows_per_strip: usize = ifd.rows_per_strip.try_into().unwrap();
let bits_per_sample: usize = ifd.bits_per_sample.into();
let [cfa_pattern_width, cfa_pattern_height] = ifd.cfa_pattern_dim;
assert!(cfa_pattern_width == 2 && cfa_pattern_height == 2);
let mut image: Vec<u16> = Vec::with_capacity(image_height * image_width);
for i in 0..ifd.strip_offsets.len() {
file.seek_from_start(ifd.strip_offsets[i]).unwrap();
let last = i == ifd.strip_offsets.len();
let rows = if last { image_height % rows_per_strip } else { rows_per_strip };
for _ in 0..rows {
for _ in 0..image_width {
image.push(file.read_u16().unwrap());
}
}
}
RawImage {
data: image,
width: image_width,
height: image_height,
cfa_pattern: ifd.cfa_pattern.try_into().unwrap(),
maximum: if bits_per_sample == 16 { u16::MAX } else { (1 << bits_per_sample) - 1 },
black: SubtractBlack::CfaGrid(ifd.black_level),
orientation: OrientationValue::Horizontal,
camera_model: None,
camera_white_balance: ifd.white_balance_levels.map(|arr| arr.map(|x| x as f64)),
white_balance: None,
camera_to_rgb: None,
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/decoder/mod.rs | libraries/rawkit/src/decoder/mod.rs | pub mod arw1;
pub mod arw2;
pub mod uncompressed;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/decoder/arw1.rs | libraries/rawkit/src/decoder/arw1.rs | use crate::tiff::Ifd;
use crate::tiff::file::TiffRead;
use crate::tiff::tags::SonyDataOffset;
use crate::{OrientationValue, RawImage, SubtractBlack};
use bitstream_io::{BE, BitRead, BitReader, Endianness};
use std::io::{Read, Seek};
pub fn decode_a100<R: Read + Seek>(ifd: Ifd, file: &mut TiffRead<R>) -> RawImage {
let data_offset = ifd.get_value::<SonyDataOffset, _>(file).unwrap();
let image_width = 3881;
let image_height = 2608;
file.seek_from_start(data_offset).unwrap();
let mut image = sony_arw_load_raw(image_width, image_height, &mut BitReader::<_, BE>::new(file)).unwrap();
let len = image.len();
image[len - image_width..].fill(0);
RawImage {
data: image,
width: image_width,
height: image_height,
cfa_pattern: todo!(),
#[allow(unreachable_code)]
maximum: (1 << 12) - 1,
black: SubtractBlack::None,
orientation: OrientationValue::Horizontal,
camera_model: None,
camera_white_balance: None,
white_balance: None,
camera_to_rgb: None,
}
}
fn read_and_huffman_decode_file<R: Read + Seek, E: Endianness>(huff: &[u16], file: &mut BitReader<R, E>) -> u32 {
let number_of_bits = huff[0].into();
let huffman_table = &huff[1..];
// `number_of_bits` will be no more than 32, so the result is put into a u32
let bits: u32 = file.read_var(number_of_bits).unwrap();
let bits = bits as usize;
let bits_to_seek_from = huffman_table[bits].to_le_bytes()[1] as i64 - number_of_bits as i64;
file.seek_bits(std::io::SeekFrom::Current(bits_to_seek_from)).unwrap();
huffman_table[bits].to_le_bytes()[0].into()
}
fn read_n_bits_from_file<R: Read + Seek, E: Endianness>(number_of_bits: u32, file: &mut BitReader<R, E>) -> u32 {
// `number_of_bits` will be no more than 32, so the result is put into a u32
file.read_var(number_of_bits).unwrap()
}
/// ljpeg is a lossless variant of JPEG which gets used for decoding the embedded (thumbnail) preview images in raw files
fn ljpeg_diff<R: Read + Seek, E: Endianness>(huff: &[u16], file: &mut BitReader<R, E>, dng_version: Option<u32>) -> i32 {
let length = read_and_huffman_decode_file(huff, file);
if length == 16 && dng_version.map(|x| x >= 0x1010000).unwrap_or(true) {
return -32768;
}
let diff = read_n_bits_from_file(length, file) as i32;
if length == 0 || (diff & (1 << (length - 1))) == 0 { diff - (1 << length) - 1 } else { diff }
}
fn sony_arw_load_raw<R: Read + Seek>(width: usize, height: usize, file: &mut BitReader<R, BE>) -> Option<Vec<u16>> {
const TABLE: [u16; 18] = [
0x0f11, 0x0f10, 0x0e0f, 0x0d0e, 0x0c0d, 0x0b0c, 0x0a0b, 0x090a, 0x0809, 0x0708, 0x0607, 0x0506, 0x0405, 0x0304, 0x0303, 0x0300, 0x0202, 0x0201,
];
let mut huffman_table = [0_u16; 32770];
// The first element is the number of bits to read
huffman_table[0] = 15;
let mut n = 0;
for x in TABLE {
let first_byte = x >> 8;
let repeats = 0x8000 >> first_byte;
for _ in 0_u16..repeats {
n += 1;
huffman_table[n] = x;
}
}
let mut sum = 0;
let mut image = vec![0_u16; width * height];
for column in (0..width).rev() {
for row in (0..height).step_by(2).chain((1..height).step_by(2)) {
sum += ljpeg_diff(&huffman_table, file, None);
if (sum >> 12) != 0 {
return None;
}
if row < height {
image[row * width + column] = sum as u16;
}
}
}
Some(image)
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/tiff/values.rs | libraries/rawkit/src/tiff/values.rs | use num_enum::{IntoPrimitive, TryFromPrimitive};
pub trait ToFloat {
fn to_float(&self) -> f64;
}
impl ToFloat for u32 {
fn to_float(&self) -> f64 {
*self as f64
}
}
impl ToFloat for i32 {
fn to_float(&self) -> f64 {
*self as f64
}
}
pub struct Rational<T: ToFloat> {
pub numerator: T,
pub denominator: T,
}
impl<T: ToFloat> ToFloat for Rational<T> {
fn to_float(&self) -> f64 {
self.numerator.to_float() / self.denominator.to_float()
}
}
pub struct CurveLookupTable {
table: Vec<u16>,
}
impl CurveLookupTable {
pub fn from_sony_tone_table(values: [u16; 4]) -> CurveLookupTable {
let mut sony_curve = [0, 0, 0, 0, 0, 4095];
for i in 0..4 {
sony_curve[i + 1] = values[i] >> 2 & 0xfff;
}
let mut table = vec![0_u16; (sony_curve[5] + 1).into()];
for i in 0..5 {
for j in (sony_curve[i] + 1)..=sony_curve[i + 1] {
table[j as usize] = table[(j - 1) as usize] + (1 << i);
}
}
CurveLookupTable { table }
}
pub fn get(&self, x: usize) -> u16 {
self.table[x]
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug, IntoPrimitive, TryFromPrimitive)]
#[repr(u16)]
pub enum OrientationValue {
Horizontal = 1,
MirrorHorizontal = 2,
Rotate180 = 3,
MirrorVertical = 4,
MirrorHorizontalRotate270 = 5,
Rotate90 = 6,
MirrorHorizontalRotate90 = 7,
Rotate270 = 8,
}
impl OrientationValue {
pub fn is_identity(&self) -> bool {
*self == Self::Horizontal
}
pub fn will_swap_coordinates(&self) -> bool {
match *self {
Self::Horizontal | Self::MirrorHorizontal | Self::Rotate180 | Self::MirrorVertical => false,
Self::MirrorHorizontalRotate270 | Self::Rotate90 | Self::MirrorHorizontalRotate90 | Self::Rotate270 => true,
}
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy, IntoPrimitive, TryFromPrimitive)]
#[repr(u16)]
#[allow(non_camel_case_types)]
pub enum CompressionValue {
Uncompressed = 1,
CCITT_1D = 2,
T4 = 3,
T6 = 4,
LZW = 5,
JPEG_Old = 6,
JPEG = 7,
AdobeDeflate = 8,
JBIG_BW = 9,
JBIG_Color = 10,
KODAK_626 = 262,
Next = 32766,
Sony_ARW_Compressed = 32767,
Packed_Raw = 32769,
Samsung_SRW_Compressed = 32770,
CCIRLEW = 32771,
Samsung_SRW_Compressed_2 = 32772,
PackedBits = 32773,
Thunderscan = 32809,
Kodak_KDC_Compressed = 32867,
IT8CTPAD = 32895,
IT8LW = 32896,
IT8MP = 32897,
IT8BL = 32898,
PixarFilm = 32908,
PixarLog = 32909,
Deflate = 32946,
DCS = 32947,
AperioJPEG2K_YCbCr = 33003,
AperioJPEG2K_RGB = 33005,
JBIG = 34661,
SGILog = 34676,
SGILog24 = 34677,
JPEG2K = 34712,
NikonNEFCompressed = 34713,
JBIG2_TIFF_FX = 34715,
ESRI_Lerc = 34887,
LossyJPEG = 34892,
LZMA2 = 34925,
PNG = 34933,
JPEG_XR = 34934,
Zstd = 50000,
WebP = 50001,
JPEG_XL = 52546,
Kodak_DCR_Compressed = 65000,
Pentax_PEF_Compressed = 65535,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/tiff/file.rs | libraries/rawkit/src/tiff/file.rs | use std::io::{Error, ErrorKind, Read, Result, Seek, SeekFrom};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Endian {
Little,
Big,
}
pub struct TiffRead<R: Read + Seek> {
reader: R,
endian: Endian,
}
impl<R: Read + Seek> TiffRead<R> {
pub fn new(mut reader: R) -> Result<Self> {
let error = Error::new(ErrorKind::InvalidData, "Invalid Tiff format");
let mut data = [0_u8; 2];
reader.read_exact(&mut data)?;
let endian = if data[0] == 0x49 && data[1] == 0x49 {
Endian::Little
} else if data[0] == 0x4d && data[1] == 0x4d {
Endian::Big
} else {
return Err(error);
};
reader.read_exact(&mut data)?;
let magic_number = match endian {
Endian::Little => u16::from_le_bytes(data),
Endian::Big => u16::from_be_bytes(data),
};
if magic_number != 42 {
return Err(error);
}
Ok(Self { reader, endian })
}
pub fn endian(&self) -> Endian {
self.endian
}
}
impl<R: Read + Seek> Read for TiffRead<R> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
self.reader.read(buf)
}
}
impl<R: Read + Seek> Seek for TiffRead<R> {
fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
self.reader.seek(pos)
}
}
impl<R: Read + Seek> TiffRead<R> {
pub fn seek_from_start(&mut self, offset: u32) -> Result<u64> {
self.reader.seek(SeekFrom::Start(offset.into()))
}
pub fn read_ascii(&mut self) -> Result<char> {
let data = self.read_n::<1>()?;
Ok(data[0] as char)
}
pub fn read_n<const N: usize>(&mut self) -> Result<[u8; N]> {
let mut data = [0_u8; N];
self.read_exact(&mut data)?;
Ok(data)
}
pub fn read_u8(&mut self) -> Result<u8> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(u8::from_le_bytes(data)),
Endian::Big => Ok(u8::from_be_bytes(data)),
}
}
pub fn read_u16(&mut self) -> Result<u16> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(u16::from_le_bytes(data)),
Endian::Big => Ok(u16::from_be_bytes(data)),
}
}
pub fn read_u32(&mut self) -> Result<u32> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(u32::from_le_bytes(data)),
Endian::Big => Ok(u32::from_be_bytes(data)),
}
}
pub fn read_u64(&mut self) -> Result<u64> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(u64::from_le_bytes(data)),
Endian::Big => Ok(u64::from_be_bytes(data)),
}
}
pub fn read_i8(&mut self) -> Result<i8> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(i8::from_le_bytes(data)),
Endian::Big => Ok(i8::from_be_bytes(data)),
}
}
pub fn read_i16(&mut self) -> Result<i16> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(i16::from_le_bytes(data)),
Endian::Big => Ok(i16::from_be_bytes(data)),
}
}
pub fn read_i32(&mut self) -> Result<i32> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(i32::from_le_bytes(data)),
Endian::Big => Ok(i32::from_be_bytes(data)),
}
}
pub fn read_i64(&mut self) -> Result<i64> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(i64::from_le_bytes(data)),
Endian::Big => Ok(i64::from_be_bytes(data)),
}
}
pub fn read_f32(&mut self) -> Result<f32> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(f32::from_le_bytes(data)),
Endian::Big => Ok(f32::from_be_bytes(data)),
}
}
pub fn read_f64(&mut self) -> Result<f64> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(f64::from_le_bytes(data)),
Endian::Big => Ok(f64::from_be_bytes(data)),
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/tiff/types.rs | libraries/rawkit/src/tiff/types.rs | use super::file::TiffRead;
use super::values::{CompressionValue, CurveLookupTable, OrientationValue, Rational};
use super::{Ifd, IfdTagType, TiffError};
use std::io::{Read, Seek};
pub struct TypeAscii;
pub struct TypeByte;
pub struct TypeShort;
pub struct TypeLong;
pub struct TypeRational;
pub struct TypeSByte;
pub struct TypeSShort;
pub struct TypeSLong;
pub struct TypeSRational;
pub struct TypeFloat;
pub struct TypeDouble;
pub struct TypeUndefined;
pub struct TypeNumber;
pub struct TypeSNumber;
pub struct TypeIfd;
pub trait PrimitiveType {
type Output;
fn get_size(the_type: IfdTagType) -> Option<u32>;
fn read_primitive<R: Read + Seek>(the_type: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError>;
}
impl PrimitiveType for TypeAscii {
type Output = char;
fn get_size(the_type: IfdTagType) -> Option<u32> {
match the_type {
IfdTagType::Ascii => Some(1),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let value = file.read_ascii()?;
if value.is_ascii() { Ok(value) } else { Err(TiffError::InvalidValue) }
}
}
impl PrimitiveType for TypeByte {
type Output = u8;
fn get_size(the_type: IfdTagType) -> Option<u32> {
match the_type {
IfdTagType::Byte => Some(1),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_u8()?)
}
}
impl PrimitiveType for TypeShort {
type Output = u16;
fn get_size(the_type: IfdTagType) -> Option<u32> {
match the_type {
IfdTagType::Short => Some(2),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_u16()?)
}
}
impl PrimitiveType for TypeLong {
type Output = u32;
fn get_size(the_type: IfdTagType) -> Option<u32> {
match the_type {
IfdTagType::Long => Some(4),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_u32()?)
}
}
impl PrimitiveType for TypeRational {
type Output = Rational<u32>;
fn get_size(the_type: IfdTagType) -> Option<u32> {
match the_type {
IfdTagType::Rational => Some(8),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(the_type: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let numerator = TypeLong::read_primitive(the_type, file)?;
let denominator = TypeLong::read_primitive(the_type, file)?;
Ok(Rational { numerator, denominator })
}
}
impl PrimitiveType for TypeSByte {
type Output = i8;
fn get_size(the_type: IfdTagType) -> Option<u32> {
match the_type {
IfdTagType::SByte => Some(1),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_i8()?)
}
}
impl PrimitiveType for TypeSShort {
type Output = i16;
fn get_size(the_type: IfdTagType) -> Option<u32> {
match the_type {
IfdTagType::SShort => Some(2),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_i16()?)
}
}
impl PrimitiveType for TypeSLong {
type Output = i32;
fn get_size(the_type: IfdTagType) -> Option<u32> {
match the_type {
IfdTagType::SLong => Some(4),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_i32()?)
}
}
impl PrimitiveType for TypeSRational {
type Output = Rational<i32>;
fn get_size(the_type: IfdTagType) -> Option<u32> {
match the_type {
IfdTagType::SRational => Some(8),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(the_type: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let numerator = TypeSLong::read_primitive(the_type, file)?;
let denominator = TypeSLong::read_primitive(the_type, file)?;
Ok(Rational { numerator, denominator })
}
}
impl PrimitiveType for TypeFloat {
type Output = f32;
fn get_size(the_type: IfdTagType) -> Option<u32> {
match the_type {
IfdTagType::Float => Some(4),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_f32()?)
}
}
impl PrimitiveType for TypeDouble {
type Output = f64;
fn get_size(the_type: IfdTagType) -> Option<u32> {
match the_type {
IfdTagType::Double => Some(8),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_f64()?)
}
}
impl PrimitiveType for TypeUndefined {
type Output = ();
fn get_size(_: IfdTagType) -> Option<u32> {
todo!()
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, _: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
todo!()
}
}
impl PrimitiveType for TypeNumber {
type Output = u32;
fn get_size(the_type: IfdTagType) -> Option<u32> {
match the_type {
IfdTagType::Byte => TypeByte::get_size(the_type),
IfdTagType::Short => TypeShort::get_size(the_type),
IfdTagType::Long => TypeLong::get_size(the_type),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(the_type: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(match the_type {
IfdTagType::Byte => TypeByte::read_primitive(the_type, file)?.into(),
IfdTagType::Short => TypeShort::read_primitive(the_type, file)?.into(),
IfdTagType::Long => TypeLong::read_primitive(the_type, file)?,
_ => unreachable!(),
})
}
}
impl PrimitiveType for TypeSNumber {
type Output = i32;
fn get_size(the_type: IfdTagType) -> Option<u32> {
match the_type {
IfdTagType::SByte => TypeSByte::get_size(the_type),
IfdTagType::SShort => TypeSShort::get_size(the_type),
IfdTagType::SLong => TypeSLong::get_size(the_type),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(the_type: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(match the_type {
IfdTagType::SByte => TypeSByte::read_primitive(the_type, file)?.into(),
IfdTagType::SShort => TypeSShort::read_primitive(the_type, file)?.into(),
IfdTagType::SLong => TypeSLong::read_primitive(the_type, file)?,
_ => unreachable!(),
})
}
}
impl PrimitiveType for TypeIfd {
type Output = Ifd;
fn get_size(the_type: IfdTagType) -> Option<u32> {
TypeLong::get_size(the_type)
}
fn read_primitive<R: Read + Seek>(the_type: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let offset = TypeLong::read_primitive(the_type, file)?;
Ifd::new_from_offset(file, offset)
}
}
pub trait TagType {
type Output;
fn read<R: Read + Seek>(file: &mut TiffRead<R>) -> Result<Self::Output, TiffError>;
}
impl<T: PrimitiveType> TagType for T {
type Output = T::Output;
fn read<R: Read + Seek>(file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let the_type = IfdTagType::from(file.read_u16()?);
let count = file.read_u32()?;
if count != 1 {
return Err(TiffError::InvalidCount);
}
let size = T::get_size(the_type).ok_or(TiffError::InvalidType)?;
if count * size > 4 {
let offset = file.read_u32()?;
file.seek_from_start(offset)?;
}
T::read_primitive(the_type, file)
}
}
pub struct Array<T: PrimitiveType> {
primitive_type: std::marker::PhantomData<T>,
}
pub struct ConstArray<T: PrimitiveType, const N: usize> {
primitive_type: std::marker::PhantomData<T>,
}
impl<T: PrimitiveType> TagType for Array<T> {
type Output = Vec<T::Output>;
fn read<R: Read + Seek>(file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let the_type = IfdTagType::from(file.read_u16()?);
let count = file.read_u32()?;
let size = T::get_size(the_type).ok_or(TiffError::InvalidType)?;
if count * size > 4 {
let offset = file.read_u32()?;
file.seek_from_start(offset)?;
}
let mut ans = Vec::with_capacity(count.try_into()?);
for _ in 0..count {
ans.push(T::read_primitive(the_type, file)?);
}
Ok(ans)
}
}
impl<T: PrimitiveType, const N: usize> TagType for ConstArray<T, N> {
type Output = [T::Output; N];
fn read<R: Read + Seek>(file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let the_type = IfdTagType::from(file.read_u16()?);
let count = file.read_u32()?;
if count != N.try_into()? {
return Err(TiffError::InvalidCount);
}
let size = T::get_size(the_type).ok_or(TiffError::InvalidType)?;
if count * size > 4 {
let offset = file.read_u32()?;
file.seek_from_start(offset)?;
}
let mut ans = Vec::with_capacity(count.try_into()?);
for _ in 0..count {
ans.push(T::read_primitive(the_type, file)?);
}
ans.try_into().map_err(|_| TiffError::InvalidCount)
}
}
pub struct TypeCompression;
pub struct TypeString;
pub struct TypeSonyToneCurve;
pub struct TypeOrientation;
impl TagType for TypeString {
type Output = String;
fn read<R: Read + Seek>(file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let string = Array::<TypeAscii>::read(file)?;
// Skip the NUL character at the end
let len = string.len();
Ok(string.into_iter().take(len - 1).collect())
}
}
impl TagType for TypeSonyToneCurve {
type Output = CurveLookupTable;
fn read<R: Read + Seek>(file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let values = ConstArray::<TypeShort, 4>::read(file)?;
Ok(CurveLookupTable::from_sony_tone_table(values))
}
}
impl TagType for TypeOrientation {
type Output = OrientationValue;
fn read<R: Read + Seek>(file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
OrientationValue::try_from(TypeShort::read(file)?).map_err(|_| TiffError::InvalidValue)
}
}
impl TagType for TypeCompression {
type Output = CompressionValue;
fn read<R: Read + Seek>(file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
CompressionValue::try_from(TypeShort::read(file)?).map_err(|_| TiffError::InvalidValue)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/tiff/mod.rs | libraries/rawkit/src/tiff/mod.rs | pub mod file;
pub mod tags;
mod types;
pub mod values;
use file::TiffRead;
use num_enum::{FromPrimitive, IntoPrimitive};
use std::fmt::Display;
use std::io::{Read, Seek};
use tags::Tag;
use thiserror::Error;
#[derive(Copy, Clone, Debug, PartialEq, Eq, FromPrimitive, IntoPrimitive)]
#[repr(u16)]
pub enum TagId {
ImageWidth = 0x100,
ImageLength = 0x101,
BitsPerSample = 0x102,
Compression = 0x103,
PhotometricInterpretation = 0x104,
Make = 0x10f,
Model = 0x110,
StripOffsets = 0x111,
Orientation = 0x112,
SamplesPerPixel = 0x115,
RowsPerStrip = 0x116,
StripByteCounts = 0x117,
SubIfd = 0x14a,
ThumbnailOffset = 0x201,
ThumbnailLength = 0x202,
SonyToneCurve = 0x7010,
BlackLevel = 0x7310,
WhiteBalanceRggbLevels = 0x7313,
CfaPatternDim = 0x828d,
CfaPattern = 0x828e,
ColorMatrix1 = 0xc621,
ColorMatrix2 = 0xc622,
#[num_enum(catch_all)]
Unknown(u16),
}
#[repr(u16)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, FromPrimitive, IntoPrimitive)]
pub enum IfdTagType {
Byte = 1,
Ascii = 2,
Short = 3,
Long = 4,
Rational = 5,
SByte = 6,
Undefined = 7,
SShort = 8,
SLong = 9,
SRational = 10,
Float = 11,
Double = 12,
#[num_enum(catch_all)]
Unknown(u16),
}
#[derive(Copy, Clone, Debug)]
pub struct IfdEntry {
tag: TagId,
the_type: IfdTagType,
count: u32,
value: u32,
}
#[derive(Clone, Debug)]
pub struct Ifd {
current_ifd_offset: u32,
ifd_entries: Vec<IfdEntry>,
next_ifd_offset: Option<u32>,
}
impl Ifd {
pub fn new_first_ifd<R: Read + Seek>(file: &mut TiffRead<R>) -> Result<Self, TiffError> {
file.seek_from_start(4)?;
let current_ifd_offset = file.read_u32()?;
Ifd::new_from_offset(file, current_ifd_offset)
}
pub fn new_from_offset<R: Read + Seek>(file: &mut TiffRead<R>, offset: u32) -> Result<Self, TiffError> {
if offset == 0 {
return Err(TiffError::InvalidOffset);
}
file.seek_from_start(offset)?;
let num_entries = file.read_u16()?;
let mut ifd_entries = Vec::with_capacity(num_entries.into());
for _ in 0..num_entries {
let tag = file.read_u16()?.into();
let the_type = file.read_u16()?.into();
let count = file.read_u32()?;
let value = file.read_u32()?;
ifd_entries.push(IfdEntry { tag, the_type, count, value });
}
let next_ifd_offset = file.read_u32()?;
let next_ifd_offset = if next_ifd_offset == 0 { None } else { Some(next_ifd_offset) };
Ok(Ifd {
current_ifd_offset: offset,
ifd_entries,
next_ifd_offset,
})
}
fn _next_ifd<R: Read + Seek>(&self, file: &mut TiffRead<R>) -> Result<Self, TiffError> {
Ifd::new_from_offset(file, self.next_ifd_offset.unwrap_or(0))
}
pub fn ifd_entries(&self) -> &[IfdEntry] {
&self.ifd_entries
}
pub fn iter(&self) -> impl Iterator<Item = &IfdEntry> {
self.ifd_entries.iter()
}
pub fn get_value<T: Tag, R: Read + Seek>(&self, file: &mut TiffRead<R>) -> Result<T::Output, TiffError> {
T::get(self, file)
}
}
impl Display for Ifd {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("IFD offset: ")?;
self.current_ifd_offset.fmt(f)?;
f.write_str("\n")?;
for ifd_entry in self.ifd_entries() {
f.write_fmt(format_args!(
"|- Tag: {:x?}, Type: {:?}, Count: {}, Value: {:x}\n",
ifd_entry.tag, ifd_entry.the_type, ifd_entry.count, ifd_entry.value
))?;
}
f.write_str("Next IFD offset: ")?;
if let Some(offset) = self.next_ifd_offset {
offset.fmt(f)?;
} else {
f.write_str("None")?;
}
f.write_str("\n")?;
Ok(())
}
}
#[derive(Error, Debug)]
pub enum TiffError {
#[error("The value was invalid")]
InvalidValue,
#[error("The type was invalid")]
InvalidType,
#[error("The count was invalid")]
InvalidCount,
#[error("The tag was missing")]
MissingTag,
#[error("The offset was invalid or zero")]
InvalidOffset,
#[error("An error occurred when converting integer from one type to another")]
ConversionError(#[from] std::num::TryFromIntError),
#[error("An IO Error ocurred")]
IoError(#[from] std::io::Error),
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/tiff/tags.rs | libraries/rawkit/src/tiff/tags.rs | use super::types::{Array, ConstArray, TagType, TypeByte, TypeCompression, TypeIfd, TypeLong, TypeNumber, TypeOrientation, TypeSRational, TypeSShort, TypeShort, TypeSonyToneCurve, TypeString};
use super::{Ifd, TagId, TiffError, TiffRead};
use std::io::{Read, Seek};
pub trait SimpleTag {
type Type: TagType;
const ID: TagId;
const NAME: &'static str;
}
pub struct ImageWidth;
pub struct ImageLength;
pub struct BitsPerSample;
pub struct Compression;
pub struct PhotometricInterpretation;
pub struct Make;
pub struct Model;
pub struct StripOffsets;
pub struct Orientation;
pub struct SamplesPerPixel;
pub struct RowsPerStrip;
pub struct StripByteCounts;
pub struct SubIfd;
pub struct ThumbnailOffset;
pub struct ThumbnailLength;
pub struct SonyDataOffset;
pub struct SonyToneCurve;
pub struct BlackLevel;
pub struct WhiteBalanceRggbLevels;
pub struct CfaPatternDim;
pub struct CfaPattern;
pub struct ColorMatrix1;
pub struct ColorMatrix2;
impl SimpleTag for ImageWidth {
type Type = TypeNumber;
const ID: TagId = TagId::ImageWidth;
const NAME: &'static str = "Image Width";
}
impl SimpleTag for ImageLength {
type Type = TypeNumber;
const ID: TagId = TagId::ImageLength;
const NAME: &'static str = "Image Length";
}
impl SimpleTag for BitsPerSample {
type Type = TypeShort;
const ID: TagId = TagId::BitsPerSample;
const NAME: &'static str = "Bits per Sample";
}
impl SimpleTag for Compression {
type Type = TypeCompression;
const ID: TagId = TagId::Compression;
const NAME: &'static str = "Compression";
}
impl SimpleTag for PhotometricInterpretation {
type Type = TypeShort;
const ID: TagId = TagId::PhotometricInterpretation;
const NAME: &'static str = "Photometric Interpretation";
}
impl SimpleTag for Make {
type Type = TypeString;
const ID: TagId = TagId::Make;
const NAME: &'static str = "Make";
}
impl SimpleTag for Model {
type Type = TypeString;
const ID: TagId = TagId::Model;
const NAME: &'static str = "Model";
}
impl SimpleTag for StripOffsets {
type Type = Array<TypeNumber>;
const ID: TagId = TagId::StripOffsets;
const NAME: &'static str = "Strip Offsets";
}
impl SimpleTag for Orientation {
type Type = TypeOrientation;
const ID: TagId = TagId::Orientation;
const NAME: &'static str = "Orientation";
}
impl SimpleTag for SamplesPerPixel {
type Type = TypeShort;
const ID: TagId = TagId::SamplesPerPixel;
const NAME: &'static str = "Samples per Pixel";
}
impl SimpleTag for RowsPerStrip {
type Type = TypeNumber;
const ID: TagId = TagId::RowsPerStrip;
const NAME: &'static str = "Rows per Strip";
}
impl SimpleTag for StripByteCounts {
type Type = Array<TypeNumber>;
const ID: TagId = TagId::StripByteCounts;
const NAME: &'static str = "Strip Byte Counts";
}
impl SimpleTag for SubIfd {
type Type = TypeIfd;
const ID: TagId = TagId::SubIfd;
const NAME: &'static str = "SubIFD";
}
impl SimpleTag for ThumbnailOffset {
type Type = TypeLong;
const ID: TagId = TagId::ThumbnailOffset;
const NAME: &'static str = "Jpeg Offset";
}
impl SimpleTag for ThumbnailLength {
type Type = TypeLong;
const ID: TagId = TagId::ThumbnailLength;
const NAME: &'static str = "Jpeg Length";
}
impl SimpleTag for CfaPatternDim {
type Type = ConstArray<TypeShort, 2>;
const ID: TagId = TagId::CfaPatternDim;
const NAME: &'static str = "CFA Pattern Dimension";
}
impl SimpleTag for CfaPattern {
type Type = Array<TypeByte>;
const ID: TagId = TagId::CfaPattern;
const NAME: &'static str = "CFA Pattern";
}
impl SimpleTag for ColorMatrix1 {
type Type = Array<TypeSRational>;
const ID: TagId = TagId::ColorMatrix1;
const NAME: &'static str = "Color Matrix 1";
}
impl SimpleTag for ColorMatrix2 {
type Type = Array<TypeSRational>;
const ID: TagId = TagId::ColorMatrix2;
const NAME: &'static str = "Color Matrix 2";
}
impl SimpleTag for SonyDataOffset {
type Type = TypeLong;
const ID: TagId = TagId::SubIfd;
const NAME: &'static str = "Sony Data Offset";
}
impl SimpleTag for SonyToneCurve {
type Type = TypeSonyToneCurve;
const ID: TagId = TagId::SonyToneCurve;
const NAME: &'static str = "Sony Tone Curve";
}
impl SimpleTag for BlackLevel {
type Type = ConstArray<TypeShort, 4>;
const ID: TagId = TagId::BlackLevel;
const NAME: &'static str = "Black Level";
}
impl SimpleTag for WhiteBalanceRggbLevels {
type Type = ConstArray<TypeSShort, 4>;
const ID: TagId = TagId::WhiteBalanceRggbLevels;
const NAME: &'static str = "White Balance Levels (RGGB)";
}
pub trait Tag {
type Output;
fn get<R: Read + Seek>(ifd: &Ifd, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError>;
}
impl<T: SimpleTag> Tag for T {
type Output = <T::Type as TagType>::Output;
fn get<R: Read + Seek>(ifd: &Ifd, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let tag_id = T::ID;
let index: u32 = ifd.iter().position(|x| x.tag == tag_id).ok_or(TiffError::MissingTag)?.try_into()?;
file.seek_from_start(ifd.current_ifd_offset + 2 + 12 * index + 2)?;
T::Type::read(file)
}
}
impl<T: Tag> Tag for Option<T> {
type Output = Option<T::Output>;
fn get<R: Read + Seek>(ifd: &Ifd, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let result = T::get(ifd, file);
match result {
Err(TiffError::MissingTag) => Ok(None),
Ok(x) => Ok(Some(x)),
Err(x) => Err(x),
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/postprocessing/transform.rs | libraries/rawkit/src/postprocessing/transform.rs | use crate::{Image, OrientationValue, Pixel};
impl Image<u16> {
pub fn orientation_iter(&self) -> (usize, usize, impl Iterator<Item = Pixel> + use<'_>) {
let (final_width, final_height) = if self.orientation.will_swap_coordinates() {
(self.height, self.width)
} else {
(self.width, self.height)
};
let index_0_0 = inverse_orientation_index(self.orientation, 0, 0, self.width, self.height);
let index_0_1 = inverse_orientation_index(self.orientation, 0, 1, self.width, self.height);
let index_1_0 = inverse_orientation_index(self.orientation, 1, 0, self.width, self.height);
let column_step = (index_0_1.0 - index_0_0.0, index_0_1.1 - index_0_0.1);
let row_step = (index_1_0.0 - index_0_0.0, index_1_0.1 - index_0_0.1);
let mut index = index_0_0;
let channels = self.channels as usize;
(
final_width,
final_height,
(0..final_height).flat_map(move |row| {
let temp = (0..final_width).map(move |column| {
let initial_index = (self.width as i64 * index.0 + index.1) as usize;
let pixel = &self.data[channels * initial_index..channels * (initial_index + 1)];
index = (index.0 + column_step.0, index.1 + column_step.1);
Pixel {
values: pixel.try_into().unwrap(),
row,
column,
}
});
index = (index.0 + row_step.0, index.1 + row_step.1);
temp
}),
)
}
}
pub fn inverse_orientation_index(orientation: OrientationValue, mut row: usize, mut column: usize, width: usize, height: usize) -> (i64, i64) {
let value = match orientation {
OrientationValue::Horizontal => 0,
OrientationValue::MirrorHorizontal => 1,
OrientationValue::Rotate180 => 3,
OrientationValue::MirrorVertical => 2,
OrientationValue::MirrorHorizontalRotate270 => 4,
OrientationValue::Rotate90 => 6,
OrientationValue::MirrorHorizontalRotate90 => 7,
OrientationValue::Rotate270 => 5,
};
if value & 4 != 0 {
std::mem::swap(&mut row, &mut column)
}
if value & 2 != 0 {
row = height - 1 - row;
}
if value & 1 != 0 {
column = width - 1 - column;
}
(row as i64, column as i64)
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/postprocessing/gamma_correction.rs | libraries/rawkit/src/postprocessing/gamma_correction.rs | use crate::{CHANNELS_IN_RGB, Histogram, Image, Pixel};
use std::f64::consts::E;
impl Image<u16> {
pub fn gamma_correction_fn(&self, histogram: &Histogram) -> impl Fn(Pixel) -> [u16; CHANNELS_IN_RGB] + use<> {
let percentage = self.width * self.height;
let mut white = 0;
for channel_histogram in histogram {
let mut total = 0;
for i in (0x20..0x2000).rev() {
total += channel_histogram[i] as u64;
if total * 100 > percentage as u64 {
white = white.max(i);
break;
}
}
}
let curve = generate_gamma_curve(0.45, 4.5, (white << 3) as f64);
move |pixel: Pixel| pixel.values.map(|value| curve[value as usize])
}
}
/// `max_intensity` must be non-zero.
fn generate_gamma_curve(power: f64, threshold: f64, max_intensity: f64) -> Vec<u16> {
debug_assert!(max_intensity != 0.);
let (mut bound_start, mut bound_end) = if threshold >= 1. { (0., 1.) } else { (1., 0.) };
let mut transition_point = 0.;
let mut transition_ratio = 0.;
let mut curve_adjustment = 0.;
if threshold != 0. && (threshold - 1.) * (power - 1.) <= 0. {
for _ in 0..48 {
transition_point = (bound_start + bound_end) / 2.;
if power != 0. {
let temp_transition_ratio = transition_point / threshold;
let exponential_power = temp_transition_ratio.powf(-power);
let normalized_exponential_power = (exponential_power - 1.) / power;
let comparison_result = normalized_exponential_power - (1. / transition_point);
let bound_to_update = if comparison_result > -1. { &mut bound_end } else { &mut bound_start };
*bound_to_update = transition_point;
} else {
let adjusted_transition_point = E.powf(1. - 1. / transition_point);
let transition_point_ratio = transition_point / adjusted_transition_point;
let bound_to_update = if transition_point_ratio < threshold { &mut bound_end } else { &mut bound_start };
*bound_to_update = transition_point;
}
}
transition_ratio = transition_point / threshold;
if power != 0. {
curve_adjustment = transition_point * ((1. / power) - 1.);
}
}
let mut curve = vec![0xffff; 0x1_0000];
let length = curve.len() as f64;
for (i, entry) in curve.iter_mut().enumerate() {
let ratio = (i as f64) / max_intensity;
if ratio < 1. {
let altered_ratio = if ratio < transition_ratio {
ratio * threshold
} else if power != 0. {
ratio.powf(power) * (1. + curve_adjustment) - curve_adjustment
} else {
ratio.ln() * transition_point + 1.
};
*entry = (length * altered_ratio) as u16;
}
}
curve
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/postprocessing/mod.rs | libraries/rawkit/src/postprocessing/mod.rs | pub mod convert_to_rgb;
pub mod gamma_correction;
pub mod record_histogram;
pub mod transform;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/postprocessing/convert_to_rgb.rs | libraries/rawkit/src/postprocessing/convert_to_rgb.rs | use crate::{CHANNELS_IN_RGB, Pixel, RawImage};
impl RawImage {
pub fn convert_to_rgb_fn(&self) -> impl Fn(Pixel) -> [u16; CHANNELS_IN_RGB] + use<> {
let Some(camera_to_rgb) = self.camera_to_rgb else { todo!() };
move |pixel: Pixel| {
std::array::from_fn(|i| i)
.map(|i| camera_to_rgb[i].iter().zip(pixel.values.iter()).map(|(&coeff, &value)| coeff * value as f64).sum())
.map(|x: f64| (x as u16).clamp(0, u16::MAX))
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/src/postprocessing/record_histogram.rs | libraries/rawkit/src/postprocessing/record_histogram.rs | use crate::{CHANNELS_IN_RGB, Histogram, Pixel, PixelTransform, RawImage};
impl RawImage {
pub fn record_histogram_fn(&self) -> RecordHistogram {
RecordHistogram::new()
}
}
pub struct RecordHistogram {
pub histogram: Histogram,
}
impl RecordHistogram {
fn new() -> RecordHistogram {
RecordHistogram {
histogram: [[0; 0x2000]; CHANNELS_IN_RGB],
}
}
}
impl PixelTransform for &mut RecordHistogram {
fn apply(&mut self, pixel: Pixel) -> [u16; CHANNELS_IN_RGB] {
self.histogram
.iter_mut()
.zip(pixel.values.iter())
.for_each(|(histogram, &value)| histogram[value as usize >> CHANNELS_IN_RGB] += 1);
pixel.values
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/tests/tests.rs | libraries/rawkit/tests/tests.rs | // Only compile this file if the feature "rawkit-tests" is enabled
#![cfg(feature = "rawkit-tests")]
use image::codecs::png::{CompressionType, FilterType, PngEncoder};
use image::{ColorType, ImageEncoder};
use libraw::Processor;
use rawkit::RawImage;
use rayon::prelude::*;
use std::collections::HashMap;
use std::fmt::Write;
use std::fs::{File, create_dir, metadata, read_dir};
use std::io::{BufWriter, Cursor, Read};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
const TEST_FILES: [&str; 3] = ["ILCE-7M3-ARW2.3.5-blossoms.arw", "ILCE-7RM4-ARW2.3.5-kestrel.arw", "ILCE-6000-ARW2.3.1-windsock.arw"];
const BASE_URL: &str = "https://static.graphite.art/test-data/libraries/rawkit/";
const BASE_PATH: &str = "./tests/images/";
#[test]
fn test_images_match_with_libraw() {
download_images();
let paths: Vec<_> = read_dir(BASE_PATH)
.unwrap()
.map(|dir_entry| dir_entry.unwrap().path())
.filter(|path| path.is_file() && path.file_name().map(|file_name| file_name != ".gitkeep").unwrap_or(false))
.collect();
let failed_tests = if std::env::var("RAWKIT_TEST_RUN_SEQUENTIALLY").is_ok() {
let mut failed_tests = 0;
paths.iter().for_each(|path| {
if !test_image(path) {
failed_tests += 1;
}
});
failed_tests
} else {
let failed_tests = AtomicUsize::new(0);
paths.par_iter().for_each(|path| {
if !test_image(path) {
failed_tests.fetch_add(1, Ordering::SeqCst);
}
});
failed_tests.load(Ordering::SeqCst)
};
if failed_tests != 0 {
panic!("{} images have failed the tests", failed_tests);
}
}
fn test_image(path: &Path) -> bool {
let mut f = File::open(path).unwrap();
let mut content = vec![];
f.read_to_end(&mut content).unwrap();
let raw_image = match test_raw_data(&content) {
Err(err_msg) => {
println!("{} => {}", path.display(), err_msg);
return false;
}
Ok(raw_image) => raw_image,
};
// TODO: The code below is kept commented because raw data to final image processing is
// incomplete. Remove this once it is done.
// if let Err(err_msg) = test_final_image(&content, raw_image) {
// failed_tests += 1;
// return println!("{}", err_msg);
// };
println!("{} => Passed", path.display());
// TODO: Remove this later
let mut image = raw_image.process_8bit();
store_image(path, "rawkit", &mut image.data, image.width, image.height);
let processor = Processor::new();
let libraw_image = processor.process_8bit(&content).unwrap();
let mut data = Vec::from_iter(libraw_image.iter().copied());
store_image(path, "libraw_rs", &mut data[..], libraw_image.width() as usize, libraw_image.height() as usize);
true
}
fn store_image(path: &Path, suffix: &str, data: &mut [u8], width: usize, height: usize) {
let mut output_path = PathBuf::new();
if let Some(parent) = path.parent() {
output_path.push(parent);
}
output_path.push("output");
if metadata(&output_path).is_err() {
create_dir(&output_path).unwrap();
}
if let Some(filename) = path.file_stem() {
let new_filename = format!("{}_{}.{}", filename.to_string_lossy(), suffix, "png");
output_path.push(new_filename);
}
output_path.set_extension("png");
let file = BufWriter::new(File::create(output_path).unwrap());
let png_encoder = PngEncoder::new_with_quality(file, CompressionType::Fast, FilterType::Adaptive);
png_encoder.write_image(data, width as u32, height as u32, ColorType::Rgb8.into()).unwrap();
}
fn download_images() {
let mut path = Path::new(BASE_PATH).to_owned();
let client = reqwest::blocking::Client::builder().timeout(Duration::from_secs(60 * 5)).build().unwrap();
for filename in TEST_FILES {
path.push(filename);
if !path.exists() {
let url = BASE_URL.to_owned() + filename;
let mut response = client.get(url).send().unwrap();
let mut file = File::create(BASE_PATH.to_owned() + filename).unwrap();
std::io::copy(&mut response, &mut file).unwrap();
}
path.pop();
}
}
fn test_raw_data(content: &[u8]) -> Result<RawImage, String> {
let processor = libraw::Processor::new();
let libraw_raw_image = processor.decode(content).unwrap();
let mut content = Cursor::new(content);
let raw_image = RawImage::decode(&mut content).unwrap();
if libraw_raw_image.sizes().raw_height as usize != raw_image.height {
return Err(format!(
"The height of raw image is {} but the expected value was {}",
raw_image.height,
libraw_raw_image.sizes().raw_height
));
}
if libraw_raw_image.sizes().raw_width as usize != raw_image.width {
return Err(format!(
"The width of raw image is {} but the expected value was {}",
raw_image.width,
libraw_raw_image.sizes().raw_width
));
}
if (*libraw_raw_image).len() != raw_image.data.len() {
return Err(format!(
"The size of data of raw image is {} but the expected value was {}",
raw_image.data.len(),
(*libraw_raw_image).len()
));
}
if (*libraw_raw_image) != raw_image.data {
let mut err_msg = String::new();
write!(&mut err_msg, "The raw data does not match").unwrap();
if std::env::var("RAWKIT_TEST_PRINT_HISTOGRAM").is_ok() {
writeln!(err_msg).unwrap();
let mut histogram: HashMap<i32, usize> = HashMap::new();
let mut non_zero_count: usize = 0;
(*libraw_raw_image)
.iter()
.zip(raw_image.data.iter())
.map(|(&a, &b)| {
let a: i32 = a.into();
let b: i32 = b.into();
a - b
})
.filter(|&x| x != 0)
.for_each(|x| {
*histogram.entry(x).or_default() += 1;
non_zero_count += 1;
});
let total_pixels = raw_image.height * raw_image.width;
writeln!(err_msg, "{} ({:.5}%) pixels are different from expected", non_zero_count, non_zero_count as f64 / total_pixels as f64).unwrap();
writeln!(err_msg, "Diff Histogram:").unwrap();
let mut items: Vec<_> = histogram.iter().map(|(&a, &b)| (a, b)).collect();
items.sort();
for (key, value) in items {
writeln!(err_msg, "{:05}: {:05} ({:02.5}%)", key, value, value as f64 / total_pixels as f64).unwrap();
}
}
return Err(err_msg);
}
Ok(raw_image)
}
fn _test_final_image(content: &[u8], raw_image: RawImage) -> Result<(), String> {
let processor = libraw::Processor::new();
let libraw_image = processor.process_8bit(content).unwrap();
let image = raw_image.process_8bit();
if libraw_image.height() as usize != image.height {
return Err(format!("The height of image is {} but the expected value was {}", image.height, libraw_image.height()));
}
if libraw_image.width() as usize != image.width {
return Err(format!("The width of image is {} but the expected value was {}", image.width, libraw_image.width()));
}
if (*libraw_image).len() != image.data.len() {
return Err(format!("The size of data of image is {} but the expected value was {}", image.data.len(), (*libraw_image).len()));
}
if (*libraw_image) != image.data {
let mut err_msg = String::new();
write!(&mut err_msg, "The final image does not match").unwrap();
if std::env::var("RAWKIT_TEST_PRINT_HISTOGRAM").is_ok() {
writeln!(err_msg).unwrap();
let mut histogram_red: HashMap<i16, usize> = HashMap::new();
let mut histogram_green: HashMap<i16, usize> = HashMap::new();
let mut histogram_blue: HashMap<i16, usize> = HashMap::new();
let mut non_zero_count: usize = 0;
let mut non_zero_count_red: usize = 0;
let mut non_zero_count_green: usize = 0;
let mut non_zero_count_blue: usize = 0;
(*libraw_image)
.chunks_exact(3)
.zip(image.data.chunks_exact(3))
.map(|(a, b)| {
let a: [u8; 3] = a.try_into().unwrap();
let b: [u8; 3] = b.try_into().unwrap();
(a, b)
})
.map(|([r1, g1, b1], [r2, g2, b2])| {
let r1: i16 = r1.into();
let g1: i16 = g1.into();
let b1: i16 = b1.into();
let r2: i16 = r2.into();
let g2: i16 = g2.into();
let b2: i16 = b2.into();
[r1 - r2, g1 - g2, b1 - b2]
})
.filter(|&[r, g, b]| r != 0 || g != 0 || b != 0)
.for_each(|[r, g, b]| {
non_zero_count += 1;
if r != 0 {
*histogram_red.entry(r).or_default() += 1;
non_zero_count_red += 1;
}
if g != 0 {
*histogram_green.entry(g).or_default() += 1;
non_zero_count_green += 1;
}
if b != 0 {
*histogram_blue.entry(b).or_default() += 1;
non_zero_count_blue += 1;
}
});
let total_pixels = image.height * image.width;
writeln!(err_msg, "{} ({:.5}%) pixels are different from expected", non_zero_count, non_zero_count as f64 / total_pixels as f64,).unwrap();
writeln!(
err_msg,
"{} ({:.5}%) red pixels are different from expected",
non_zero_count_red,
non_zero_count_red as f64 / total_pixels as f64,
)
.unwrap();
writeln!(
err_msg,
"{} ({:.5}%) green pixels are different from expected",
non_zero_count_green,
non_zero_count_green as f64 / total_pixels as f64,
)
.unwrap();
writeln!(
err_msg,
"{} ({:.5}%) blue pixels are different from expected",
non_zero_count_blue,
non_zero_count_blue as f64 / total_pixels as f64,
)
.unwrap();
writeln!(err_msg, "Diff Histogram for Red pixels:").unwrap();
let mut items: Vec<_> = histogram_red.iter().map(|(&a, &b)| (a, b)).collect();
items.sort();
for (key, value) in items {
writeln!(err_msg, "{:05}: {:05} ({:02.5}%)", key, value, value as f64 / total_pixels as f64).unwrap();
}
writeln!(err_msg, "Diff Histogram for Green pixels:").unwrap();
let mut items: Vec<_> = histogram_green.iter().map(|(&a, &b)| (a, b)).collect();
items.sort();
for (key, value) in items {
writeln!(err_msg, "{:05}: {:05} ({:02.5}%)", key, value, value as f64 / total_pixels as f64).unwrap();
}
writeln!(err_msg, "Diff Histogram for Blue pixels:").unwrap();
let mut items: Vec<_> = histogram_blue.iter().map(|(&a, &b)| (a, b)).collect();
items.sort();
for (key, value) in items {
writeln!(err_msg, "{:05}: {:05} ({:02.5}%)", key, value, value as f64 / total_pixels as f64).unwrap();
}
}
return Err(err_msg);
}
Ok(())
}
#[ignore]
#[test]
fn extract_data_from_dng_images() {
read_dir(BASE_PATH)
.unwrap()
.map(|dir_entry| dir_entry.unwrap().path())
.filter(|path| path.is_file() && path.file_name().map(|file_name| file_name != ".gitkeep").unwrap_or(false))
.for_each(|path| {
extract_data_from_dng_image(&path);
});
}
fn extract_data_from_dng_image(path: &Path) {
use rawkit::tiff::Ifd;
use rawkit::tiff::file::TiffRead;
use rawkit::tiff::tags::{ColorMatrix2, Make, Model};
use rawkit::tiff::values::ToFloat;
use std::io::{BufReader, Write};
let reader = BufReader::new(File::open(path).unwrap());
let mut file = TiffRead::new(reader).unwrap();
let ifd = Ifd::new_first_ifd(&mut file).unwrap();
let make = ifd.get_value::<Make, _>(&mut file).unwrap();
let model = ifd.get_value::<Model, _>(&mut file).unwrap();
let matrix = ifd.get_value::<ColorMatrix2, _>(&mut file).unwrap();
if model == "MODEL-NAME" {
println!("{}", path.display());
return;
}
let output_folder = path.parent().unwrap().join(make);
std::fs::create_dir_all(&output_folder).unwrap();
let mut output_file = File::create(output_folder.join(model + ".toml")).unwrap();
let matrix: Vec<_> = matrix.iter().map(|x| x.to_float()).collect();
writeln!(output_file, "camera_to_xyz = {:.4?}", matrix).unwrap();
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/rawkit-proc-macros/src/lib.rs | libraries/rawkit/rawkit-proc-macros/src/lib.rs | extern crate proc_macro;
mod build_camera_data;
mod tag_derive;
use proc_macro::TokenStream;
#[proc_macro_derive(Tag)]
pub fn tag_derive(input: TokenStream) -> TokenStream {
tag_derive::tag_derive(input)
}
#[proc_macro]
pub fn build_camera_data(_: TokenStream) -> TokenStream {
build_camera_data::build_camera_data()
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/rawkit-proc-macros/src/build_camera_data.rs | libraries/rawkit/rawkit-proc-macros/src/build_camera_data.rs | use proc_macro::TokenStream;
use quote::{ToTokens, quote};
use std::fs;
use std::path::Path;
use toml::{Table, Value};
enum CustomValue {
String(String),
Integer(i64),
Float(f64),
Boolean(bool),
Array(Vec<CustomValue>),
}
impl ToTokens for CustomValue {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
match self {
CustomValue::String(x) => x.to_tokens(tokens),
CustomValue::Integer(x) => {
let x: proc_macro2::TokenStream = format!("{:?}", x).parse().unwrap();
x.to_tokens(tokens)
}
CustomValue::Float(x) => {
let x: proc_macro2::TokenStream = format!("{:?}", x).parse().unwrap();
x.to_tokens(tokens)
}
CustomValue::Boolean(x) => x.to_tokens(tokens),
CustomValue::Array(x) => quote! { [ #( #x ),* ] }.to_tokens(tokens),
}
}
}
impl From<Value> for CustomValue {
fn from(value: Value) -> Self {
match value {
Value::String(x) => CustomValue::String(x),
Value::Integer(x) => CustomValue::Integer(x),
Value::Float(x) => CustomValue::Float(x),
Value::Boolean(x) => CustomValue::Boolean(x),
Value::Array(x) => CustomValue::Array(x.into_iter().map(|x| x.into()).collect()),
_ => panic!("Unsupported data type"),
}
}
}
pub fn build_camera_data() -> TokenStream {
let mut camera_data: Vec<(String, Table)> = Vec::new();
let mut path = Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap()).to_path_buf();
path.push("camera_data");
fs::read_dir(path).unwrap().for_each(|entry| {
let company_name_path = entry.unwrap().path();
if !company_name_path.is_dir() {
panic!("camera_data should only contain folders of company names")
}
let company_name = company_name_path.file_name().unwrap().to_str().unwrap().to_string();
fs::read_dir(company_name_path).unwrap().for_each(|entry| {
let model_path = entry.unwrap().path();
if !model_path.is_file() || model_path.extension().unwrap() != "toml" {
panic!("The folders within camera_data should only contain toml files")
}
let name = company_name.clone() + " " + model_path.file_stem().unwrap().to_str().unwrap();
let mut values: Table = toml::from_str(&fs::read_to_string(model_path).unwrap()).unwrap();
if let Some(val) = values.get_mut("xyz_to_camera") {
*val = Value::Array(val.as_array().unwrap().iter().map(|x| Value::Integer((x.as_float().unwrap() * 10_000.) as i64)).collect());
}
camera_data.push((name, values))
});
});
let x: Vec<_> = camera_data
.iter()
.map(|(name, camera_data)| {
let keys: Vec<_> = camera_data.keys().map(|key| syn::Ident::new(key, proc_macro2::Span::call_site())).collect();
let values: Vec<CustomValue> = camera_data.values().cloned().map(|x| x.into()).collect();
quote! {
(
#name,
CameraData {
#( #keys: #values, )*
..CameraData::DEFAULT
}
)
}
})
.collect();
quote!([ #(#x),* ]).into()
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/rawkit/rawkit-proc-macros/src/tag_derive.rs | libraries/rawkit/rawkit-proc-macros/src/tag_derive.rs | use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{Data, DeriveInput, Fields};
pub fn tag_derive(input: TokenStream) -> TokenStream {
let ast: DeriveInput = syn::parse(input).unwrap();
let name = &ast.ident;
let data_struct = if let Data::Struct(data_struct) = ast.data {
data_struct
} else {
panic!("Tag trait can only be derived for structs")
};
let named_fields = if let Fields::Named(named_fields) = data_struct.fields {
named_fields
} else {
panic!("Tag trait can only be derived for structs with named_fields")
};
let struct_idents: Vec<_> = named_fields.named.iter().map(|field| field.ident.clone().unwrap()).collect();
let struct_types: Vec<_> = named_fields.named.iter().map(|field| field.ty.clone()).collect();
let new_name = format_ident!("_{}", name);
let r#gen = quote! {
struct #new_name {
#( #struct_idents: <#struct_types as Tag>::Output ),*
}
impl Tag for #name {
type Output = #new_name;
fn get<R: Read + Seek>(ifd: &Ifd, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
#( let #struct_idents = <#struct_types as Tag>::get(ifd, file)?; )*
Ok(#new_name { #( #struct_idents ),* })
}
}
};
r#gen.into()
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/math-parser/src/ast.rs | libraries/math-parser/src/ast.rs | use crate::value::Complex;
#[derive(Debug, PartialEq, Eq)]
pub struct Unit {
// Exponent of length unit (meters)
pub length: i32,
// Exponent of mass unit (kilograms)
pub mass: i32,
// Exponent of time unit (seconds)
pub time: i32,
}
impl Default for Unit {
fn default() -> Self {
Self::BASE_UNIT
}
}
impl Unit {
pub const BASE_UNIT: Unit = Unit { length: 0, mass: 0, time: 0 };
pub const LENGTH: Unit = Unit { length: 1, mass: 0, time: 0 };
pub const MASS: Unit = Unit { length: 0, mass: 1, time: 0 };
pub const TIME: Unit = Unit { length: 0, mass: 0, time: 1 };
pub const VELOCITY: Unit = Unit { length: 1, mass: 0, time: -1 };
pub const ACCELERATION: Unit = Unit { length: 1, mass: 0, time: -2 };
pub const FORCE: Unit = Unit { length: 1, mass: 1, time: -2 };
pub fn base_unit() -> Self {
Self::BASE_UNIT
}
pub fn is_base(&self) -> bool {
*self == Self::BASE_UNIT
}
}
#[derive(Debug, PartialEq)]
pub enum Literal {
Float(f64),
Complex(Complex),
}
impl From<f64> for Literal {
fn from(value: f64) -> Self {
Self::Float(value)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BinaryOp {
Add,
Sub,
Mul,
Div,
Pow,
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum UnaryOp {
Neg,
Sqrt,
Fac,
}
#[derive(Debug, PartialEq)]
pub enum Node {
Lit(Literal),
Var(String),
FnCall { name: String, expr: Vec<Node> },
BinOp { lhs: Box<Node>, op: BinaryOp, rhs: Box<Node> },
UnaryOp { expr: Box<Node>, op: UnaryOp },
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/math-parser/src/lib.rs | libraries/math-parser/src/lib.rs | #![allow(unused)]
pub mod ast;
mod constants;
pub mod context;
pub mod executer;
pub mod parser;
pub mod value;
use ast::Unit;
use context::{EvalContext, ValueMap};
use executer::EvalError;
use parser::ParseError;
use value::Value;
pub fn evaluate(expression: &str) -> Result<(Result<Value, EvalError>, Unit), ParseError> {
let expr = ast::Node::try_parse_from_str(expression);
let context = EvalContext::default();
expr.map(|(node, unit)| (node.eval(&context), unit))
}
#[cfg(test)]
mod tests {
use super::*;
use ast::Unit;
use value::Number;
const EPSILON: f64 = 1e-10_f64;
macro_rules! test_end_to_end{
($($name:ident: $input:expr_2021 => ($expected_value:expr_2021, $expected_unit:expr_2021)),* $(,)?) => {
$(
#[test]
fn $name() {
let expected_value = $expected_value;
let expected_unit = $expected_unit;
let expr = ast::Node::try_parse_from_str($input);
let context = EvalContext::default();
let (actual_value, actual_unit) = expr.map(|(node, unit)| (node.eval(&context), unit)).unwrap();
let actual_value = actual_value.unwrap();
assert!(actual_unit == expected_unit, "Expected unit {:?} but found unit {:?}", expected_unit, actual_unit);
let expected_value = expected_value.into();
match (actual_value, expected_value) {
(Value::Number(Number::Complex(actual_c)), Value::Number(Number::Complex(expected_c))) => {
assert!(
(actual_c.re.is_infinite() && expected_c.re.is_infinite()) || (actual_c.re - expected_c.re).abs() < EPSILON,
"Expected real part {}, but got {}",
expected_c.re,
actual_c.re
);
assert!(
(actual_c.im.is_infinite() && expected_c.im.is_infinite()) || (actual_c.im - expected_c.im).abs() < EPSILON,
"Expected imaginary part {}, but got {}",
expected_c.im,
actual_c.im
);
}
(Value::Number(Number::Real(actual_f)), Value::Number(Number::Real(expected_f))) => {
if actual_f.is_infinite() || expected_f.is_infinite() {
assert!(
actual_f.is_infinite() && expected_f.is_infinite() && actual_f == expected_f,
"Expected infinite value {}, but got {}",
expected_f,
actual_f
);
} else if actual_f.is_nan() || expected_f.is_nan() {
assert!(actual_f.is_nan() && expected_f.is_nan(), "Expected NaN, but got {}", actual_f);
} else {
assert!((actual_f - expected_f).abs() < EPSILON, "Expected {}, but got {}", expected_f, actual_f);
}
}
// Handle mismatched types
_ => panic!("Mismatched types: expected {:?}, got {:?}", expected_value, actual_value),
}
}
)*
};
}
test_end_to_end! {
// Basic arithmetic and units
infix_addition: "5 + 5" => (10., Unit::BASE_UNIT),
infix_subtraction_units: "5m - 3m" => (2., Unit::LENGTH),
infix_multiplication_units: "4s * 4s" => (16., Unit { length: 0, mass: 0, time: 2 }),
infix_division_units: "8m/2s" => (4., Unit::VELOCITY),
// Order of operations
order_of_operations_negative_prefix: "-10 + 5" => (-5., Unit::BASE_UNIT),
order_of_operations_add_multiply: "5+1*1+5" => (11., Unit::BASE_UNIT),
order_of_operations_add_negative_multiply: "5+(-1)*1+5" => (9., Unit::BASE_UNIT),
order_of_operations_sqrt: "sqrt25 + 11" => (16., Unit::BASE_UNIT),
order_of_operations_sqrt_expression: "sqrt(25+11)" => (6., Unit::BASE_UNIT),
// Parentheses and nested expressions
parentheses_nested_multiply: "(5 + 3) * (2 + 6)" => (64., Unit::BASE_UNIT),
parentheses_mixed_operations: "2 * (3 + 5 * (2 + 1))" => (36., Unit::BASE_UNIT),
parentheses_divide_add_multiply: "10 / (2 + 3) + (7 * 2)" => (16., Unit::BASE_UNIT),
// Square root and nested square root
sqrt_chain_operations: "sqrt(16) + sqrt(9) * sqrt(4)" => (10., Unit::BASE_UNIT),
sqrt_nested: "sqrt(sqrt(81))" => (3., Unit::BASE_UNIT),
sqrt_divide_expression: "sqrt((25 + 11) / 9)" => (2., Unit::BASE_UNIT),
// Mixed square root and units
sqrt_multiply_units: "sqrt(16) * 2g + 5g" => (13., Unit::MASS),
sqrt_add_multiply: "sqrt(49) - 1 + 2 * 3" => (12., Unit::BASE_UNIT),
sqrt_addition_multiply: "(sqrt(36) + 2) * 2" => (16., Unit::BASE_UNIT),
// Exponentiation
exponent_single: "2^3" => (8., Unit::BASE_UNIT),
exponent_mixed_operations: "2^3 + 4^2" => (24., Unit::BASE_UNIT),
exponent_nested: "2^(3+1)" => (16., Unit::BASE_UNIT),
// Operations with negative values
negative_units_add_multiply: "-5s + (-3 * 2)s" => (-11., Unit::TIME),
negative_nested_parentheses: "-(5 + 3 * (2 - 1))" => (-8., Unit::BASE_UNIT),
negative_sqrt_addition: "-(sqrt(16) + sqrt(9))" => (-7., Unit::BASE_UNIT),
multiply_sqrt_subtract: "5 * 2 + sqrt(16) / 2 - 3" => (9., Unit::BASE_UNIT),
add_multiply_subtract_sqrt: "4 + 3 * (2 + 1) - sqrt(25)" => (8., Unit::BASE_UNIT),
add_sqrt_subtract_nested_multiply: "10 + sqrt(64) - (5 * (2 + 1))" => (3., Unit::BASE_UNIT),
// Mathematical constants
constant_pi: "pi" => (std::f64::consts::PI, Unit::BASE_UNIT),
constant_e: "e" => (std::f64::consts::E, Unit::BASE_UNIT),
constant_phi: "phi" => (1.61803398875, Unit::BASE_UNIT),
constant_tau: "tau" => (2.0 * std::f64::consts::PI, Unit::BASE_UNIT),
constant_infinity: "inf" => (f64::INFINITY, Unit::BASE_UNIT),
constant_infinity_symbol: "∞" => (f64::INFINITY, Unit::BASE_UNIT),
multiply_pi: "2 * pi" => (2.0 * std::f64::consts::PI, Unit::BASE_UNIT),
add_e_constant: "e + 1" => (std::f64::consts::E + 1.0, Unit::BASE_UNIT),
multiply_phi_constant: "phi * 2" => (1.61803398875 * 2.0, Unit::BASE_UNIT),
exponent_tau: "2^tau" => (2f64.powf(2.0 * std::f64::consts::PI), Unit::BASE_UNIT),
infinity_subtract_large_number: "inf - 1000" => (f64::INFINITY, Unit::BASE_UNIT),
// Trigonometric functions
trig_sin_pi: "sin(pi)" => (0.0, Unit::BASE_UNIT),
trig_cos_zero: "cos(0)" => (1.0, Unit::BASE_UNIT),
trig_tan_pi_div_four: "tan(pi/4)" => (1.0, Unit::BASE_UNIT),
trig_sin_tau: "sin(tau)" => (0.0, Unit::BASE_UNIT),
trig_cos_tau_div_two: "cos(tau/2)" => (-1.0, Unit::BASE_UNIT),
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/math-parser/src/parser.rs | libraries/math-parser/src/parser.rs | use crate::ast::{BinaryOp, Literal, Node, UnaryOp, Unit};
use crate::context::EvalContext;
use crate::value::{Complex, Number, Value};
use lazy_static::lazy_static;
use num_complex::ComplexFloat;
use pest::Parser;
use pest::iterators::{Pair, Pairs};
use pest::pratt_parser::{Assoc, Op, PrattParser};
use pest_derive::Parser;
use std::num::{ParseFloatError, ParseIntError};
use thiserror::Error;
#[derive(Parser)]
#[grammar = "./grammer.pest"] // Point to the grammar file
struct ExprParser;
lazy_static! {
static ref PRATT_PARSER: PrattParser<Rule> = {
PrattParser::new()
.op(Op::infix(Rule::add, Assoc::Left) | Op::infix(Rule::sub, Assoc::Left))
.op(Op::infix(Rule::mul, Assoc::Left) | Op::infix(Rule::div, Assoc::Left) | Op::infix(Rule::paren, Assoc::Left))
.op(Op::infix(Rule::pow, Assoc::Right))
.op(Op::postfix(Rule::fac) | Op::postfix(Rule::EOI))
.op(Op::prefix(Rule::sqrt))
.op(Op::prefix(Rule::neg))
};
}
#[derive(Error, Debug)]
pub enum TypeError {
#[error("Invalid BinOp: {0:?} {1:?} {2:?}")]
InvalidBinaryOp(Unit, BinaryOp, Unit),
#[error("Invalid UnaryOp: {0:?}")]
InvalidUnaryOp(Unit, UnaryOp),
}
#[derive(Error, Debug)]
pub enum ParseError {
#[error("ParseIntError: {0}")]
ParseInt(#[from] ParseIntError),
#[error("ParseFloatError: {0}")]
ParseFloat(#[from] ParseFloatError),
#[error("TypeError: {0}")]
Type(#[from] TypeError),
#[error("PestError: {0}")]
Pest(#[from] Box<pest::error::Error<Rule>>),
}
impl Node {
pub fn try_parse_from_str(s: &str) -> Result<(Node, Unit), ParseError> {
let pairs = ExprParser::parse(Rule::program, s).map_err(Box::new)?;
let (node, metadata) = parse_expr(pairs)?;
Ok((node, metadata.unit))
}
}
struct NodeMetadata {
pub unit: Unit,
}
impl NodeMetadata {
pub fn new(unit: Unit) -> Self {
Self { unit }
}
}
fn parse_unit(pairs: Pairs<Rule>) -> Result<(Unit, f64), ParseError> {
let mut scale = 1.0;
let mut length = 0;
let mut mass = 0;
let mut time = 0;
for pair in pairs {
println!("found rule: {:?}", pair.as_rule());
match pair.as_rule() {
Rule::nano => scale *= 1e-9,
Rule::micro => scale *= 1e-6,
Rule::milli => scale *= 1e-3,
Rule::centi => scale *= 1e-2,
Rule::deci => scale *= 1e-1,
Rule::deca => scale *= 1e1,
Rule::hecto => scale *= 1e2,
Rule::kilo => scale *= 1e3,
Rule::mega => scale *= 1e6,
Rule::giga => scale *= 1e9,
Rule::tera => scale *= 1e12,
Rule::meter => length = 1,
Rule::gram => mass = 1,
Rule::second => time = 1,
_ => unreachable!(), // All possible rules should be covered
}
}
Ok((Unit { length, mass, time }, scale))
}
fn parse_const(pair: Pair<Rule>) -> Literal {
match pair.as_rule() {
Rule::infinity => Literal::Float(f64::INFINITY),
Rule::imaginary_unit => Literal::Complex(Complex::new(0.0, 1.0)),
Rule::pi => Literal::Float(std::f64::consts::PI),
Rule::tau => Literal::Float(2.0 * std::f64::consts::PI),
Rule::euler_number => Literal::Float(std::f64::consts::E),
Rule::golden_ratio => Literal::Float(1.61803398875),
_ => unreachable!("Unexpected constant: {:?}", pair),
}
}
fn parse_lit(mut pairs: Pairs<Rule>) -> Result<(Literal, Unit), ParseError> {
let literal = match pairs.next() {
Some(lit) => match lit.as_rule() {
Rule::int => {
let value = lit.as_str().parse::<i32>()? as f64;
Literal::Float(value)
}
Rule::float => {
let value = lit.as_str().parse::<f64>()?;
Literal::Float(value)
}
Rule::unit => {
let (unit, scale) = parse_unit(lit.into_inner())?;
return Ok((Literal::Float(scale), unit));
}
rule => unreachable!("unexpected rule: {:?}", rule),
},
None => unreachable!("expected rule"), // No literal found
};
if let Some(unit_pair) = pairs.next() {
let unit_pairs = unit_pair.into_inner(); // Get the inner pairs for the unit
let (unit, scale) = parse_unit(unit_pairs)?;
println!("found unit: {unit:?}");
Ok((
match literal {
Literal::Float(num) => Literal::Float(num * scale),
Literal::Complex(num) => Literal::Complex(num * scale),
},
unit,
))
} else {
Ok((literal, Unit::BASE_UNIT))
}
}
fn parse_expr(pairs: Pairs<Rule>) -> Result<(Node, NodeMetadata), ParseError> {
PRATT_PARSER
.map_primary(|primary| {
Ok(match primary.as_rule() {
Rule::lit => {
let (lit, unit) = parse_lit(primary.into_inner())?;
(Node::Lit(lit), NodeMetadata { unit })
}
Rule::fn_call => {
let mut pairs = primary.into_inner();
let name = pairs.next().expect("fn_call always has 2 children").as_str().to_string();
(
Node::FnCall {
name,
expr: pairs.map(|p| parse_expr(p.into_inner()).map(|expr| expr.0)).collect::<Result<Vec<Node>, ParseError>>()?,
},
NodeMetadata::new(Unit::BASE_UNIT),
)
}
Rule::constant => {
let lit = parse_const(primary.into_inner().next().expect("constant should have atleast 1 child"));
(Node::Lit(lit), NodeMetadata::new(Unit::BASE_UNIT))
}
Rule::ident => {
let name = primary.as_str().to_string();
(Node::Var(name), NodeMetadata::new(Unit::BASE_UNIT))
}
Rule::expr => parse_expr(primary.into_inner())?,
Rule::float => {
let value = primary.as_str().parse::<f64>()?;
(Node::Lit(Literal::Float(value)), NodeMetadata::new(Unit::BASE_UNIT))
}
rule => unreachable!("unexpected rule: {:?}", rule),
})
})
.map_prefix(|op, rhs| {
let (rhs, rhs_metadata) = rhs?;
let op = match op.as_rule() {
Rule::neg => UnaryOp::Neg,
Rule::sqrt => UnaryOp::Sqrt,
rule => unreachable!("unexpected rule: {:?}", rule),
};
let node = Node::UnaryOp { expr: Box::new(rhs), op };
let unit = rhs_metadata.unit;
let unit = if !unit.is_base() {
match op {
UnaryOp::Sqrt if unit.length % 2 == 0 && unit.mass % 2 == 0 && unit.time % 2 == 0 => Unit {
length: unit.length / 2,
mass: unit.mass / 2,
time: unit.time / 2,
},
UnaryOp::Neg => unit,
op => return Err(ParseError::Type(TypeError::InvalidUnaryOp(unit, op))),
}
} else {
Unit::BASE_UNIT
};
Ok((node, NodeMetadata::new(unit)))
})
.map_postfix(|lhs, op| {
let (lhs_node, lhs_metadata) = lhs?;
let op = match op.as_rule() {
Rule::EOI => return Ok((lhs_node, lhs_metadata)),
Rule::fac => UnaryOp::Fac,
rule => unreachable!("unexpected rule: {:?}", rule),
};
if !lhs_metadata.unit.is_base() {
return Err(ParseError::Type(TypeError::InvalidUnaryOp(lhs_metadata.unit, op)));
}
Ok((Node::UnaryOp { expr: Box::new(lhs_node), op }, lhs_metadata))
})
.map_infix(|lhs, op, rhs| {
let (lhs, lhs_metadata) = lhs?;
let (rhs, rhs_metadata) = rhs?;
let op = match op.as_rule() {
Rule::add => BinaryOp::Add,
Rule::sub => BinaryOp::Sub,
Rule::mul => BinaryOp::Mul,
Rule::div => BinaryOp::Div,
Rule::pow => BinaryOp::Pow,
Rule::paren => BinaryOp::Mul,
rule => unreachable!("unexpected rule: {:?}", rule),
};
let (lhs_unit, rhs_unit) = (lhs_metadata.unit, rhs_metadata.unit);
let unit = match (!lhs_unit.is_base(), !rhs_unit.is_base()) {
(true, true) => match op {
BinaryOp::Mul => Unit {
length: lhs_unit.length + rhs_unit.length,
mass: lhs_unit.mass + rhs_unit.mass,
time: lhs_unit.time + rhs_unit.time,
},
BinaryOp::Div => Unit {
length: lhs_unit.length - rhs_unit.length,
mass: lhs_unit.mass - rhs_unit.mass,
time: lhs_unit.time - rhs_unit.time,
},
BinaryOp::Add | BinaryOp::Sub => {
if lhs_unit == rhs_unit {
lhs_unit
} else {
return Err(ParseError::Type(TypeError::InvalidBinaryOp(lhs_unit, op, rhs_unit)));
}
}
BinaryOp::Pow => {
return Err(ParseError::Type(TypeError::InvalidBinaryOp(lhs_unit, op, rhs_unit)));
}
},
(true, false) => match op {
BinaryOp::Add | BinaryOp::Sub => return Err(ParseError::Type(TypeError::InvalidBinaryOp(lhs_unit, op, Unit::BASE_UNIT))),
BinaryOp::Pow => {
//TODO: improve error type
//TODO: support 1 / int
if let Ok(Value::Number(Number::Real(val))) = rhs.eval(&EvalContext::default()) {
if (val - val as i32 as f64).abs() <= f64::EPSILON {
Unit {
length: lhs_unit.length * val as i32,
mass: lhs_unit.mass * val as i32,
time: lhs_unit.time * val as i32,
}
} else {
return Err(ParseError::Type(TypeError::InvalidBinaryOp(lhs_unit, op, Unit::BASE_UNIT)));
}
} else {
return Err(ParseError::Type(TypeError::InvalidBinaryOp(lhs_unit, op, Unit::BASE_UNIT)));
}
}
_ => lhs_unit,
},
(false, true) => match op {
BinaryOp::Add | BinaryOp::Sub | BinaryOp::Pow => return Err(ParseError::Type(TypeError::InvalidBinaryOp(Unit::BASE_UNIT, op, rhs_unit))),
_ => rhs_unit,
},
(false, false) => Unit::BASE_UNIT,
};
let node = Node::BinOp {
lhs: Box::new(lhs),
op,
rhs: Box::new(rhs),
};
Ok((node, NodeMetadata::new(unit)))
})
.parse(pairs)
}
//TODO: set up Unit test for Units
#[cfg(test)]
mod tests {
use super::*;
macro_rules! test_parser {
($($name:ident: $input:expr_2021 => $expected:expr_2021),* $(,)?) => {
$(
#[test]
fn $name() {
let result = Node::try_parse_from_str($input).unwrap();
assert_eq!(result.0, $expected);
}
)*
};
}
test_parser! {
test_parse_int_literal: "42" => Node::Lit(Literal::Float(42.0)),
test_parse_float_literal: "3.14" => Node::Lit(Literal::Float(#[allow(clippy::approx_constant)] 3.14)),
test_parse_ident: "x" => Node::Var("x".to_string()),
test_parse_unary_neg: "-42" => Node::UnaryOp {
expr: Box::new(Node::Lit(Literal::Float(42.0))),
op: UnaryOp::Neg,
},
test_parse_binary_add: "1 + 2" => Node::BinOp {
lhs: Box::new(Node::Lit(Literal::Float(1.0))),
op: BinaryOp::Add,
rhs: Box::new(Node::Lit(Literal::Float(2.0))),
},
test_parse_binary_mul: "3 * 4" => Node::BinOp {
lhs: Box::new(Node::Lit(Literal::Float(3.0))),
op: BinaryOp::Mul,
rhs: Box::new(Node::Lit(Literal::Float(4.0))),
},
test_parse_binary_pow: "2 ^ 3" => Node::BinOp {
lhs: Box::new(Node::Lit(Literal::Float(2.0))),
op: BinaryOp::Pow,
rhs: Box::new(Node::Lit(Literal::Float(3.0))),
},
test_parse_unary_sqrt: "sqrt(16)" => Node::UnaryOp {
expr: Box::new(Node::Lit(Literal::Float(16.0))),
op: UnaryOp::Sqrt,
},
test_parse_sqr_ident: "sqr(16)" => Node::FnCall {
name:"sqr".to_string(),
expr: vec![Node::Lit(Literal::Float(16.0))]
},
test_parse_complex_expr: "(1 + 2) 3 - 4 ^ 2" => Node::BinOp {
lhs: Box::new(Node::BinOp {
lhs: Box::new(Node::BinOp {
lhs: Box::new(Node::Lit(Literal::Float(1.0))),
op: BinaryOp::Add,
rhs: Box::new(Node::Lit(Literal::Float(2.0))),
}),
op: BinaryOp::Mul,
rhs: Box::new(Node::Lit(Literal::Float(3.0))),
}),
op: BinaryOp::Sub,
rhs: Box::new(Node::BinOp {
lhs: Box::new(Node::Lit(Literal::Float(4.0))),
op: BinaryOp::Pow,
rhs: Box::new(Node::Lit(Literal::Float(2.0))),
}),
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/math-parser/src/value.rs | libraries/math-parser/src/value.rs | use crate::ast::{BinaryOp, UnaryOp};
use num_complex::ComplexFloat;
use std::f64::consts::PI;
pub type Complex = num_complex::Complex<f64>;
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Value {
Number(Number),
}
impl Value {
pub fn from_f64(x: f64) -> Self {
Self::Number(Number::Real(x))
}
pub fn as_real(&self) -> Option<f64> {
match self {
Self::Number(Number::Real(val)) => Some(*val),
_ => None,
}
}
}
impl From<f64> for Value {
fn from(x: f64) -> Self {
Self::from_f64(x)
}
}
impl core::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Value::Number(num) => num.fmt(f),
}
}
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Number {
Real(f64),
Complex(Complex),
}
impl std::fmt::Display for Number {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Number::Real(real) => real.fmt(f),
Number::Complex(complex) => complex.fmt(f),
}
}
}
impl Number {
pub fn binary_op(self, op: BinaryOp, other: Number) -> Number {
match (self, other) {
(Number::Real(lhs), Number::Real(rhs)) => {
let result = match op {
BinaryOp::Add => lhs + rhs,
BinaryOp::Sub => lhs - rhs,
BinaryOp::Mul => lhs * rhs,
BinaryOp::Div => lhs / rhs,
BinaryOp::Pow => lhs.powf(rhs),
};
Number::Real(result)
}
(Number::Complex(lhs), Number::Complex(rhs)) => {
let result = match op {
BinaryOp::Add => lhs + rhs,
BinaryOp::Sub => lhs - rhs,
BinaryOp::Mul => lhs * rhs,
BinaryOp::Div => lhs / rhs,
BinaryOp::Pow => lhs.powc(rhs),
};
Number::Complex(result)
}
(Number::Real(lhs), Number::Complex(rhs)) => {
let lhs_complex = Complex::new(lhs, 0.0);
let result = match op {
BinaryOp::Add => lhs_complex + rhs,
BinaryOp::Sub => lhs_complex - rhs,
BinaryOp::Mul => lhs_complex * rhs,
BinaryOp::Div => lhs_complex / rhs,
BinaryOp::Pow => lhs_complex.powc(rhs),
};
Number::Complex(result)
}
(Number::Complex(lhs), Number::Real(rhs)) => {
let rhs_complex = Complex::new(rhs, 0.0);
let result = match op {
BinaryOp::Add => lhs + rhs_complex,
BinaryOp::Sub => lhs - rhs_complex,
BinaryOp::Mul => lhs * rhs_complex,
BinaryOp::Div => lhs / rhs_complex,
BinaryOp::Pow => lhs.powf(rhs),
};
Number::Complex(result)
}
}
}
pub fn unary_op(self, op: UnaryOp) -> Number {
match self {
Number::Real(real) => match op {
UnaryOp::Neg => Number::Real(-real),
UnaryOp::Sqrt => Number::Real(real.sqrt()),
UnaryOp::Fac => todo!("Implement factorial"),
},
Number::Complex(complex) => match op {
UnaryOp::Neg => Number::Complex(-complex),
UnaryOp::Sqrt => Number::Complex(complex.sqrt()),
UnaryOp::Fac => todo!("Implement factorial"),
},
}
}
pub fn from_f64(x: f64) -> Self {
Self::Real(x)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/math-parser/src/executer.rs | libraries/math-parser/src/executer.rs | use crate::ast::{Literal, Node};
use crate::constants::DEFAULT_FUNCTIONS;
use crate::context::{EvalContext, FunctionProvider, ValueProvider};
use crate::value::{Number, Value};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum EvalError {
#[error("Missing value: {0}")]
MissingValue(String),
#[error("Missing function: {0}")]
MissingFunction(String),
#[error("Wrong type for function call")]
TypeError,
}
impl Node {
pub fn eval<V: ValueProvider, F: FunctionProvider>(&self, context: &EvalContext<V, F>) -> Result<Value, EvalError> {
match self {
Node::Lit(lit) => match lit {
Literal::Float(num) => Ok(Value::from_f64(*num)),
Literal::Complex(num) => Ok(Value::Number(Number::Complex(*num))),
},
Node::BinOp { lhs, op, rhs } => match (lhs.eval(context)?, rhs.eval(context)?) {
(Value::Number(lhs), Value::Number(rhs)) => Ok(Value::Number(lhs.binary_op(*op, rhs))),
},
Node::UnaryOp { expr, op } => match expr.eval(context)? {
Value::Number(num) => Ok(Value::Number(num.unary_op(*op))),
},
Node::Var(name) => context.get_value(name).ok_or_else(|| EvalError::MissingValue(name.clone())),
Node::FnCall { name, expr } => {
let values = expr.iter().map(|expr| expr.eval(context)).collect::<Result<Vec<Value>, EvalError>>()?;
if let Some(function) = DEFAULT_FUNCTIONS.get(&name.as_str()) {
function(&values).ok_or(EvalError::TypeError)
} else if let Some(val) = context.run_function(name, &values) {
Ok(val)
} else {
context.get_value(name).ok_or_else(|| EvalError::MissingFunction(name.to_string()))
}
}
}
}
}
#[cfg(test)]
mod tests {
use crate::ast::{BinaryOp, Literal, Node, UnaryOp};
use crate::context::{EvalContext, ValueMap};
use crate::value::Value;
macro_rules! eval_tests {
($($name:ident: $expected:expr_2021 => $expr:expr_2021),* $(,)?) => {
$(
#[test]
fn $name() {
let result = $expr.eval(&EvalContext::default()).unwrap();
assert_eq!(result, $expected);
}
)*
};
}
eval_tests! {
test_addition: Value::from_f64(7.0) => Node::BinOp {
lhs: Box::new(Node::Lit(Literal::Float(3.0))),
op: BinaryOp::Add,
rhs: Box::new(Node::Lit(Literal::Float(4.0))),
},
test_subtraction: Value::from_f64(1.0) => Node::BinOp {
lhs: Box::new(Node::Lit(Literal::Float(5.0))),
op: BinaryOp::Sub,
rhs: Box::new(Node::Lit(Literal::Float(4.0))),
},
test_multiplication: Value::from_f64(12.0) => Node::BinOp {
lhs: Box::new(Node::Lit(Literal::Float(3.0))),
op: BinaryOp::Mul,
rhs: Box::new(Node::Lit(Literal::Float(4.0))),
},
test_division: Value::from_f64(2.5) => Node::BinOp {
lhs: Box::new(Node::Lit(Literal::Float(5.0))),
op: BinaryOp::Div,
rhs: Box::new(Node::Lit(Literal::Float(2.0))),
},
test_negation: Value::from_f64(-3.0) => Node::UnaryOp {
expr: Box::new(Node::Lit(Literal::Float(3.0))),
op: UnaryOp::Neg,
},
test_sqrt: Value::from_f64(2.0) => Node::UnaryOp {
expr: Box::new(Node::Lit(Literal::Float(4.0))),
op: UnaryOp::Sqrt,
},
test_power: Value::from_f64(8.0) => Node::BinOp {
lhs: Box::new(Node::Lit(Literal::Float(2.0))),
op: BinaryOp::Pow,
rhs: Box::new(Node::Lit(Literal::Float(3.0))),
},
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/math-parser/src/constants.rs | libraries/math-parser/src/constants.rs | use crate::value::{Number, Value};
use lazy_static::lazy_static;
use num_complex::{Complex, ComplexFloat};
use std::collections::HashMap;
use std::f64::consts::PI;
type FunctionImplementation = Box<dyn Fn(&[Value]) -> Option<Value> + Send + Sync>;
lazy_static! {
pub static ref DEFAULT_FUNCTIONS: HashMap<&'static str, FunctionImplementation> = {
let mut map: HashMap<&'static str, FunctionImplementation> = HashMap::new();
map.insert(
"sin",
Box::new(|values| match values {
[Value::Number(Number::Real(real))] => Some(Value::Number(Number::Real(real.sin()))),
[Value::Number(Number::Complex(complex))] => Some(Value::Number(Number::Complex(complex.sin()))),
_ => None,
}),
);
map.insert(
"cos",
Box::new(|values| match values {
[Value::Number(Number::Real(real))] => Some(Value::Number(Number::Real(real.cos()))),
[Value::Number(Number::Complex(complex))] => Some(Value::Number(Number::Complex(complex.cos()))),
_ => None,
}),
);
map.insert(
"tan",
Box::new(|values| match values {
[Value::Number(Number::Real(real))] => Some(Value::Number(Number::Real(real.tan()))),
[Value::Number(Number::Complex(complex))] => Some(Value::Number(Number::Complex(complex.tan()))),
_ => None,
}),
);
map.insert(
"csc",
Box::new(|values| match values {
[Value::Number(Number::Real(real))] => Some(Value::Number(Number::Real(real.sin().recip()))),
[Value::Number(Number::Complex(complex))] => Some(Value::Number(Number::Complex(complex.sin().recip()))),
_ => None,
}),
);
map.insert(
"sec",
Box::new(|values| match values {
[Value::Number(Number::Real(real))] => Some(Value::Number(Number::Real(real.cos().recip()))),
[Value::Number(Number::Complex(complex))] => Some(Value::Number(Number::Complex(complex.cos().recip()))),
_ => None,
}),
);
map.insert(
"cot",
Box::new(|values| match values {
[Value::Number(Number::Real(real))] => Some(Value::Number(Number::Real(real.tan().recip()))),
[Value::Number(Number::Complex(complex))] => Some(Value::Number(Number::Complex(complex.tan().recip()))),
_ => None,
}),
);
map.insert(
"invsin",
Box::new(|values| match values {
[Value::Number(Number::Real(real))] => Some(Value::Number(Number::Real(real.asin()))),
[Value::Number(Number::Complex(complex))] => Some(Value::Number(Number::Complex(complex.asin()))),
_ => None,
}),
);
map.insert(
"invcos",
Box::new(|values| match values {
[Value::Number(Number::Real(real))] => Some(Value::Number(Number::Real(real.acos()))),
[Value::Number(Number::Complex(complex))] => Some(Value::Number(Number::Complex(complex.acos()))),
_ => None,
}),
);
map.insert(
"invtan",
Box::new(|values| match values {
[Value::Number(Number::Real(real))] => Some(Value::Number(Number::Real(real.atan()))),
[Value::Number(Number::Complex(complex))] => Some(Value::Number(Number::Complex(complex.atan()))),
_ => None,
}),
);
map.insert(
"invcsc",
Box::new(|values| match values {
[Value::Number(Number::Real(real))] => Some(Value::Number(Number::Real(real.recip().asin()))),
[Value::Number(Number::Complex(complex))] => Some(Value::Number(Number::Complex(complex.recip().asin()))),
_ => None,
}),
);
map.insert(
"invsec",
Box::new(|values| match values {
[Value::Number(Number::Real(real))] => Some(Value::Number(Number::Real(real.recip().acos()))),
[Value::Number(Number::Complex(complex))] => Some(Value::Number(Number::Complex(complex.recip().acos()))),
_ => None,
}),
);
map.insert(
"invcot",
Box::new(|values| match values {
[Value::Number(Number::Real(real))] => Some(Value::Number(Number::Real((PI / 2.0 - real).atan()))),
[Value::Number(Number::Complex(complex))] => Some(Value::Number(Number::Complex((Complex::new(PI / 2.0, 0.0) - complex).atan()))),
_ => None,
}),
);
map
};
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/math-parser/src/context.rs | libraries/math-parser/src/context.rs | use crate::value::Value;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
//TODO: editor integration, implement these traits for whatever is needed, maybe merge them if needed
pub trait ValueProvider {
fn get_value(&self, name: &str) -> Option<Value>;
}
pub trait FunctionProvider {
fn run_function(&self, name: &str, args: &[Value]) -> Option<Value>;
}
pub struct ValueMap(HashMap<String, Value>);
pub struct NothingMap;
impl ValueProvider for &ValueMap {
fn get_value(&self, name: &str) -> Option<Value> {
self.0.get(name).cloned()
}
}
impl ValueProvider for NothingMap {
fn get_value(&self, _: &str) -> Option<Value> {
None
}
}
impl ValueProvider for ValueMap {
fn get_value(&self, name: &str) -> Option<Value> {
self.0.get(name).cloned()
}
}
impl Deref for ValueMap {
type Target = HashMap<String, Value>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for ValueMap {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl FunctionProvider for NothingMap {
fn run_function(&self, _: &str, _: &[Value]) -> Option<Value> {
None
}
}
pub struct EvalContext<V: ValueProvider, F: FunctionProvider> {
values: V,
functions: F,
}
impl Default for EvalContext<NothingMap, NothingMap> {
fn default() -> Self {
Self {
values: NothingMap,
functions: NothingMap,
}
}
}
impl<V: ValueProvider, F: FunctionProvider> EvalContext<V, F> {
pub fn new(values: V, functions: F) -> Self {
Self { values, functions }
}
pub fn get_value(&self, name: &str) -> Option<Value> {
self.values.get_value(name)
}
pub fn run_function(&self, name: &str, args: &[Value]) -> Option<Value> {
self.functions.run_function(name, args)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/math-parser/benches/bench.rs | libraries/math-parser/benches/bench.rs | use criterion::{Criterion, black_box, criterion_group, criterion_main};
use math_parser::ast;
use math_parser::context::EvalContext;
macro_rules! generate_benchmarks {
($( $input:expr_2021 ),* $(,)?) => {
fn parsing_bench(c: &mut Criterion) {
$(
c.bench_function(concat!("parse ", $input), |b| {
b.iter(|| {
let _ = black_box(ast::Node::try_parse_from_str($input)).unwrap();
});
});
)*
}
fn evaluation_bench(c: &mut Criterion) {
$(
let expr = ast::Node::try_parse_from_str($input).unwrap().0;
let context = EvalContext::default();
c.bench_function(concat!("eval ", $input), |b| {
b.iter(|| {
let _ = black_box(expr.eval(&context));
});
});
)*
}
criterion_group!(benches, parsing_bench, evaluation_bench);
criterion_main!(benches);
};
}
generate_benchmarks! {
"(3 * (4 + sqrt(25)) - cos(pi/3) * (2^3)) + 5 * e", // Mixed nested functions, constants, and operations
"((5 + 2 * (3 - sqrt(49)))^2) / (1 + sqrt(16)) + tau / 2", // Complex nested expression with constants
"log(100, 10) + (5 * sin(pi/4) + sqrt(81)) / (2 * phi)", // Logarithmic and trigonometric functions
"(sqrt(144) * 2 + 5) / (3 * (4 - sin(pi / 6))) + e^2", // Combined square root, trigonometric, and exponential operations
"cos(2 * pi) + tan(pi / 3) * log(32, 2) - sqrt(256)", // Multiple trigonometric and logarithmic functions
"(10 * (3 + 2) - 8 / 2)^2 + 7 * (2^4) - sqrt(225) + phi", // Mixed arithmetic with constants
"(5^2 + 3^3) * (sqrt(81) + sqrt(64)) - tau * log(1000, 10)", // Power and square root with constants
"((8 * sqrt(49) - 2 * e) + log(256, 2) / (2 + cos(pi))) * 1.5", // Nested functions and constants
"(tan(pi / 4) + 5) * (3 + sqrt(36)) / (log(1024, 2) - 4)", // Nested functions with trigonometry and logarithm
"((3 * e + 2 * sqrt(100)) - cos(tau / 4)) * log(27, 3) + phi", // Mixed constant usage and functions
"(sqrt(100) + 5 * sin(pi / 6) - 8 / log(64, 2)) + e^(1.5)", // Complex mix of square root, division, and exponentiation
"((sin(pi/2) + cos(0)) * (e^2 - 2 * sqrt(16))) / (log(100, 10) + pi)", // Nested trigonometric, exponential, and logarithmic functions
"(5 * (7 + sqrt(121)) - (log(243, 3) * phi)) + 3^5 / tau", //
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/dyn-any/src/lib.rs | libraries/dyn-any/src/lib.rs | #![doc(html_root_url = "http://docs.rs/const-default/1.0.0")]
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::missing_safety_doc)]
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "derive")]
pub use dyn_any_derive::DynAny;
/// Implement this trait for your `dyn Trait` types for all `T: Trait`
pub trait UpcastFrom<T: ?Sized> {
fn up_from(value: &T) -> &Self;
fn up_from_mut(value: &mut T) -> &mut Self;
#[cfg(feature = "alloc")]
fn up_from_box(value: Box<T>) -> Box<Self>;
}
/// Use this trait to perform your upcasts on dyn traits. Make sure to require it in the supertrait!
pub trait Upcast<U: ?Sized> {
fn up(&self) -> &U;
fn up_mut(&mut self) -> &mut U;
#[cfg(feature = "alloc")]
fn up_box(self: Box<Self>) -> Box<U>;
}
impl<T: ?Sized, U: ?Sized> Upcast<U> for T
where
U: UpcastFrom<T>,
{
fn up(&self) -> &U {
U::up_from(self)
}
fn up_mut(&mut self) -> &mut U {
U::up_from_mut(self)
}
#[cfg(feature = "alloc")]
fn up_box(self: Box<Self>) -> Box<U> {
U::up_from_box(self)
}
}
use core::any::TypeId;
impl<'a, T: DynAny<'a> + 'a> UpcastFrom<T> for dyn DynAny<'a> + 'a {
fn up_from(value: &T) -> &(dyn DynAny<'a> + 'a) {
value
}
fn up_from_mut(value: &mut T) -> &mut (dyn DynAny<'a> + 'a) {
value
}
#[cfg(feature = "alloc")]
fn up_from_box(value: Box<T>) -> Box<Self> {
value
}
}
pub trait DynAny<'a>: 'a {
fn type_id(&self) -> TypeId;
#[cfg(feature = "log-bad-types")]
fn type_name(&self) -> &'static str;
fn reborrow_box<'short>(self: Box<Self>) -> Box<dyn DynAny<'short> + 'short>
where
'a: 'short;
fn reborrow_ref<'short>(&'a self) -> &'short (dyn DynAny<'short> + Send + Sync + 'short)
where
'a: 'short,
Self: Send + Sync;
}
impl<'a, T: StaticType + 'a> DynAny<'a> for T {
fn type_id(&self) -> core::any::TypeId {
core::any::TypeId::of::<T::Static>()
}
#[cfg(feature = "log-bad-types")]
fn type_name(&self) -> &'static str {
core::any::type_name::<T>()
}
fn reborrow_box<'short>(self: Box<Self>) -> Box<dyn DynAny<'short> + 'short>
where
'a: 'short,
{
self
}
fn reborrow_ref<'short>(&'a self) -> &'short (dyn DynAny<'short> + Send + Sync + 'short)
where
'a: 'short,
Self: Send + Sync,
{
self
}
}
pub fn downcast_ref<'a, V: StaticType + 'a>(i: &'a dyn DynAny<'a>) -> Option<&'a V> {
if i.type_id() == core::any::TypeId::of::<<V as StaticType>::Static>() {
// SAFETY: caller guarantees that T is the correct type
let ptr = i as *const dyn DynAny<'a> as *const V;
Some(unsafe { &*ptr })
} else {
None
}
}
#[cfg(feature = "alloc")]
pub fn downcast<'a, V: StaticType + 'a>(i: Box<dyn DynAny<'a> + 'a>) -> Result<Box<V>, String> {
let type_id = DynAny::type_id(i.as_ref());
if type_id == core::any::TypeId::of::<<V as StaticType>::Static>() {
// SAFETY: caller guarantees that T is the correct type
let ptr = Box::into_raw(i) as *mut V;
Ok(unsafe { Box::from_raw(ptr) })
} else {
if type_id == core::any::TypeId::of::<&dyn DynAny<'static>>() {
panic!("downcast error: type_id == core::any::TypeId::of::<dyn DynAny<'a>>()");
}
#[cfg(feature = "log-bad-types")]
{
Err(format!("Incorrect type, expected {} but found {}", core::any::type_name::<V>(), DynAny::type_name(i.as_ref())))
}
#[cfg(not(feature = "log-bad-types"))]
{
Err(format!("Incorrect type, expected {}", core::any::type_name::<V>()))
}
}
}
pub unsafe trait StaticType {
type Static: 'static + ?Sized;
fn type_id(&self) -> core::any::TypeId {
core::any::TypeId::of::<Self::Static>()
}
}
pub unsafe trait StaticTypeSized {
type Static: 'static;
fn type_id(&self) -> core::any::TypeId {
core::any::TypeId::of::<<Self as StaticTypeSized>::Static>()
}
}
unsafe impl<T: StaticType + Sized> StaticTypeSized for T
where
T::Static: Sized,
{
type Static = <T as StaticType>::Static;
}
pub unsafe trait StaticTypeClone {
type Static: 'static + Clone;
fn type_id(&self) -> core::any::TypeId {
core::any::TypeId::of::<<Self as StaticTypeClone>::Static>()
}
}
unsafe impl<T: StaticType + Clone> StaticTypeClone for T
where
T::Static: Clone,
{
type Static = <T as StaticType>::Static;
}
macro_rules! impl_type {
($($id:ident$(<$($(($l:lifetime, $s:lifetime)),*|)?$($T:ident),*>)?),*) => {
$(
unsafe impl< $($($T: $crate::StaticTypeSized ,)*)?> $crate::StaticType for $id $(<$($($l,)*)?$($T, )*>)?{
type Static = $id$(<$($($s,)*)?$(<$T as $crate::StaticTypeSized>::Static,)*>)?;
}
)*
};
}
#[cfg(feature = "alloc")]
unsafe impl<T: StaticTypeClone + Clone> StaticType for Cow<'_, T> {
type Static = Cow<'static, <T as StaticTypeClone>::Static>;
}
unsafe impl<T: StaticTypeSized> StaticType for *const [T] {
type Static = *const [<T as StaticTypeSized>::Static];
}
unsafe impl<T: StaticTypeSized> StaticType for *mut [T] {
type Static = *mut [<T as StaticTypeSized>::Static];
}
macro_rules! impl_slice {
($($id:ident),*) => {
$(
unsafe impl<'a, T: StaticTypeSized> StaticType for $id<'a, T> {
type Static = $id<'static, <T as StaticTypeSized>::Static>;
}
)*
};
}
mod slice {
use super::*;
use core::slice::*;
impl_slice!(Iter, IterMut, Chunks, ChunksMut, RChunks, RChunksMut, Windows);
}
#[cfg(feature = "alloc")]
unsafe impl<T: StaticTypeSized> StaticType for Box<dyn Iterator<Item = T> + '_ + Send + Sync> {
type Static = Box<dyn Iterator<Item = <T as StaticTypeSized>::Static> + Send + Sync>;
}
unsafe impl StaticType for &str {
type Static = &'static str;
}
unsafe impl StaticType for () {
type Static = ();
}
unsafe impl<'a, T: 'a + StaticType + ?Sized> StaticType for &'a T {
type Static = &'static <T as StaticType>::Static;
}
unsafe impl<T: StaticTypeSized, const N: usize> StaticType for [T; N] {
type Static = [<T as StaticTypeSized>::Static; N];
}
unsafe impl<T: StaticTypeSized> StaticType for [T] {
type Static = [<T as StaticTypeSized>::Static];
}
unsafe impl StaticType for dyn for<'i> DynAny<'_> + '_ {
type Static = dyn DynAny<'static>;
}
unsafe impl StaticType for dyn for<'i> DynAny<'_> + Send + Sync + '_ {
type Static = dyn DynAny<'static> + Send + Sync;
}
unsafe impl StaticType for dyn for<'i> DynAny<'_> + Send + '_ {
type Static = dyn DynAny<'static> + Sync;
}
unsafe impl<T: StaticTypeSized> StaticType for dyn core::future::Future<Output = T> + Send + Sync + '_ {
type Static = dyn core::future::Future<Output = T::Static> + Send + Sync;
}
unsafe impl<T: StaticTypeSized> StaticType for dyn core::future::Future<Output = T> + Send + '_ {
type Static = dyn core::future::Future<Output = T::Static> + Send;
}
unsafe impl<T: StaticTypeSized> StaticType for dyn core::future::Future<Output = T> + '_ {
type Static = dyn core::future::Future<Output = T::Static>;
}
#[cfg(feature = "alloc")]
pub trait IntoDynAny<'n>: Sized + StaticType + 'n {
fn into_dyn(self) -> Box<dyn DynAny<'n> + 'n> {
Box::new(self)
}
}
#[cfg(feature = "alloc")]
impl<'n, T: StaticType + 'n> IntoDynAny<'n> for T {}
#[cfg(feature = "alloc")]
impl From<()> for Box<dyn DynAny<'static>> {
fn from(_: ()) -> Box<dyn DynAny<'static>> {
Box::new(())
}
}
#[cfg(feature = "alloc")]
use alloc::borrow::Cow;
#[cfg(feature = "alloc")]
use alloc::boxed::Box;
#[cfg(feature = "alloc")]
use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque};
#[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::cell::{Cell, RefCell, UnsafeCell};
use core::iter::Empty;
use core::marker::{PhantomData, PhantomPinned};
use core::mem::{ManuallyDrop, MaybeUninit};
use core::num::Wrapping;
use core::ops::Range;
use core::pin::Pin;
use core::sync::atomic::*;
use core::time::Duration;
impl_type!(
Option<T>, Result<T, E>, Cell<T>, UnsafeCell<T>, RefCell<T>, MaybeUninit<T>,
ManuallyDrop<T>, PhantomData<T>, PhantomPinned, Empty<T>, Range<T>,
Wrapping<T>, Pin<T>, Duration, bool, f32, f64, char,
u8, AtomicU8, u16, AtomicU16, u32, AtomicU32, u64, usize, AtomicUsize,
i8, AtomicI8, i16, AtomicI16, i32, AtomicI32, i64, isize, AtomicIsize,
i128, u128, AtomicBool, AtomicPtr<T>
);
#[cfg(feature = "large-atomics")]
impl_type!(AtomicU64, AtomicI64);
#[cfg(feature = "alloc")]
impl_type!(
Vec<T>, String, BTreeMap<K,V>,BTreeSet<V>, LinkedList<T>, VecDeque<T>,
BinaryHeap<T>
);
#[cfg(feature = "std")]
use std::collections::{HashMap, HashSet};
#[cfg(feature = "std")]
use std::sync::*;
#[cfg(feature = "std")]
impl_type!(Once, Mutex<T>, RwLock<T>, HashSet<T>, HashMap<K, V>);
#[cfg(feature = "rc")]
use std::rc::Rc;
#[cfg(feature = "rc")]
impl_type!(Rc<T>);
#[cfg(all(feature = "rc", feature = "alloc"))]
use std::sync::Arc;
#[cfg(all(feature = "rc", feature = "alloc"))]
unsafe impl<T: StaticType + ?Sized> StaticType for Arc<T> {
type Static = Arc<<T as StaticType>::Static>;
}
#[cfg(feature = "glam")]
use glam::*;
#[cfg(feature = "glam")]
#[rustfmt::skip]
impl_type!(
IVec2, IVec3, IVec4, UVec2, UVec3, UVec4, BVec2, BVec3, BVec4,
Vec2, Vec3, Vec3A, Vec4, DVec2, DVec3, DVec4,
Mat2, Mat3, Mat3A, Mat4, DMat2, DMat3, DMat4,
Quat, Affine2, Affine3A, DAffine2, DAffine3, DQuat
);
#[cfg(feature = "reqwest")]
use reqwest::Response;
#[cfg(feature = "reqwest")]
impl_type!(Response);
#[cfg(feature = "alloc")]
unsafe impl<T: crate::StaticType + ?Sized> crate::StaticType for Box<T> {
type Static = Box<<T as crate::StaticType>::Static>;
}
#[test]
fn test_tuple_of_boxes() {
let tuple = (Box::new(&1u32 as &dyn DynAny<'static>), Box::new(&2u32 as &dyn DynAny<'static>));
let dyn_any = &tuple as &dyn DynAny;
assert_eq!(&1, downcast_ref::<u32>(*downcast_ref::<(Box<&dyn DynAny>, Box<&dyn DynAny>)>(dyn_any).unwrap().0).unwrap());
assert_eq!(&2, downcast_ref::<u32>(*downcast_ref::<(Box<&dyn DynAny>, Box<&dyn DynAny>)>(dyn_any).unwrap().1).unwrap());
}
macro_rules! impl_tuple {
(@rec $t:ident) => { };
(@rec $_:ident $($t:ident)+) => {
impl_tuple! { @impl $($t)* }
impl_tuple! { @rec $($t)* }
};
(@impl $($t:ident)*) => {
unsafe impl< $($t: StaticTypeSized,)*> StaticType for ($($t,)*) {
type Static = ($(<$t as $crate::StaticTypeSized>::Static,)*);
}
};
($($t:ident)*) => {
impl_tuple! { @rec _t $($t)* }
};
}
impl_tuple! {
A B C D E F G H I J K L
}
#[test]
fn simple_downcast() {
let x = Box::new(3_u32) as Box<dyn DynAny>;
assert_eq!(*downcast::<u32>(x).unwrap(), 3_u32);
}
#[test]
#[should_panic]
fn simple_downcast_panic() {
let x = Box::new(3_i32) as Box<dyn DynAny>;
assert_eq!(*downcast::<u32>(x).expect("attempted to perform invalid downcast"), 3_u32);
}
#[cfg(not(target_family = "wasm"))]
pub trait WasmNotSend: Send {}
#[cfg(target_family = "wasm")]
pub trait WasmNotSend {}
#[cfg(not(target_family = "wasm"))]
impl<T: Send> WasmNotSend for T {}
#[cfg(target_family = "wasm")]
impl<T> WasmNotSend for T {}
#[cfg(not(target_family = "wasm"))]
pub trait WasmNotSync: Sync {}
#[cfg(target_family = "wasm")]
pub trait WasmNotSync {}
#[cfg(not(target_family = "wasm"))]
impl<T: Sync> WasmNotSync for T {}
#[cfg(target_family = "wasm")]
impl<T> WasmNotSync for T {}
#[cfg(not(target_family = "wasm"))]
#[cfg(feature = "alloc")]
pub type DynFuture<'n, T> = Pin<Box<dyn core::future::Future<Output = T> + 'n + Send>>;
#[cfg(target_family = "wasm")]
#[cfg(feature = "alloc")]
pub type DynFuture<'n, T> = Pin<Box<dyn core::future::Future<Output = T> + 'n>>;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/dyn-any/derive/src/lib.rs | libraries/dyn-any/derive/src/lib.rs | #![doc(html_root_url = "http://docs.rs/dyn-any-derive/0.1.0")]
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{DeriveInput, GenericParam, Lifetime, LifetimeParam, TypeParamBound, parse_macro_input};
/// Derives an implementation for the [`DynAny`] trait.
///
/// # Note
///
/// Currently only works with `struct` inputs.
///
/// # Example
///
/// ## Struct
///
/// ```
/// # use dyn_any::{DynAny, StaticType};
/// #[derive(DynAny)]
/// pub struct Color<'a, 'b> {
/// r: &'a u8,
/// g: &'b u8,
/// b: &'a u8,
/// }
///
///
/// // Generated Impl
///
/// // impl<'dyn_any> StaticType for Color<'dyn_any, 'dyn_any> {
/// // type Static = Color<'static, 'static>;
/// // }
///
/// ```
#[proc_macro_derive(DynAny, attributes(dyn_any_derive))]
pub fn system_desc_derive(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let struct_name = &ast.ident;
let generics = &ast.generics;
let static_params = replace_lifetimes(generics, "'static");
let dyn_params = replace_lifetimes(generics, "'dyn_any");
let old_params = &generics.params.iter().collect::<Vec<_>>();
quote! {
unsafe impl<'dyn_any, #(#old_params,)*> dyn_any::StaticType for #struct_name <#(#dyn_params,)*> {
type Static = #struct_name <#(#static_params,)*>;
}
}
.into()
}
fn replace_lifetimes(generics: &syn::Generics, replacement: &str) -> Vec<proc_macro2::TokenStream> {
generics
.params
.iter()
.map(|param| {
let param = match param {
GenericParam::Lifetime(_) => GenericParam::Lifetime(LifetimeParam::new(Lifetime::new(replacement, Span::call_site()))),
GenericParam::Type(t) => {
let mut t = t.clone();
t.bounds.iter_mut().for_each(|bond| {
if let TypeParamBound::Lifetime(t) = bond {
*t = Lifetime::new(replacement, Span::call_site())
}
});
GenericParam::Type(t.clone())
}
c => c.clone(),
};
quote! {#param}
})
.collect::<Vec<_>>()
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/path_boolean.rs | libraries/path-bool/src/path_boolean.rs | //! Implements boolean operations on paths using graph-based algorithms.
//!
//! This module uses concepts from graph theory to efficiently perform boolean
//! operations on complex paths. The main algorithms involve creating a graph
//! representation of the paths, simplifying this graph, and then working with
//! its dual graph to determine the result of the boolean operation.
//!
//! ## Graph Minor
//!
//! A graph minor is a simplified version of a graph, obtained by contracting edges
//! (merging connected vertices) and removing isolated vertices. In the context of
//! path boolean operations, we use a graph minor to simplify the initial graph
//! representation of the paths. This simplification involves:
//!
//! 1. Merging collinear segments into single edges.
//! 2. Removing vertices that don't represent significant features (like intersections
//! or endpoints).
//!
//! The resulting graph minor preserves the topological structure of the paths while
//! reducing computational complexity.
//!
//! For more information on graph minors, see:
//! <https://en.wikipedia.org/wiki/Graph_minor>
//!
//! ## Dual Graph
//!
//! The dual graph is a graph derived from another graph (the primal graph). In the
//! context of path boolean operations, we construct the dual graph as follows:
//!
//! 1. Each face (region) in the primal graph becomes a vertex in the dual graph.
//! 2. Each edge in the primal graph becomes an edge in the dual graph, connecting
//! the vertices that represent the faces on either side of the original edge.
//!
//! The dual graph allows us to efficiently determine which regions are inside or
//! outside the original paths, which is crucial for performing boolean operations.
//!
//! For more information on dual graphs, see:
//! <https://en.wikipedia.org/wiki/Dual_graph>
//!
//! ## Algorithm Overview
//!
//! The boolean operation algorithm follows these main steps:
//!
//! 1. Create a graph representation of both input paths (MajorGraph).
//! 2. Simplify this graph to create a graph minor (MinorGraph).
//! 3. Construct the dual graph of the MinorGraph.
//! 4. Use the dual graph to determine which regions should be included in the result,
//! based on the specific boolean operation being performed.
//! 5. Reconstruct the resulting path(s) from the selected regions.
//!
//! This approach allows for efficient and accurate boolean operations, even on
//! complex paths with many intersections or self-intersections.
new_key_type! {
pub struct MajorVertexKey;
pub struct MajorEdgeKey;
pub struct MinorVertexKey;
pub struct MinorEdgeKey;
pub struct DualVertexKey;
pub struct DualEdgeKey;
}
// Copyright 2024 Adam Platkevič <rflashster@gmail.com>
//
// SPDX-License-Identifier: MIT
use crate::aabb::{Aabb, bounding_box_max_extent, extend_bounding_box, merge_bounding_boxes};
use crate::epsilons::Epsilons;
use crate::grid::{BitVec, Grid};
use crate::intersection_path_segment::{path_segment_intersection, segments_equal};
use crate::path::Path;
use crate::path_cubic_segment_self_intersection::path_cubic_segment_self_intersection;
use crate::path_segment::PathSegment;
#[cfg(feature = "logging")]
use crate::path_to_path_data;
use glam::{BVec2, DVec2, I64Vec2};
use roots::{Roots, find_roots_cubic};
use rustc_hash::FxHashMap as HashMap;
use rustc_hash::FxHashSet as HashSet;
use slotmap::{SlotMap, new_key_type};
use smallvec::SmallVec;
use std::cmp::Ordering;
use std::collections::VecDeque;
use std::fmt::Display;
fn new_hash_map<K, V>(capacity: usize) -> HashMap<K, V> {
HashMap::with_capacity_and_hasher(capacity, Default::default())
}
/// Represents the types of boolean operations that can be performed on paths.
#[derive(Debug, Clone, Copy)]
pub enum PathBooleanOperation {
/// Computes the union of two paths.
///
/// The result contains all areas that are inside either path A or path B (or both).
/// This operation is useful for combining shapes or creating complex outlines.
Union,
/// Computes the difference between two paths (A minus B).
///
/// The result contains all areas that are inside path A but not inside path B.
/// This operation is useful for cutting holes or subtracting shapes from each other.
Difference,
/// Computes the intersection of two paths.
///
/// The result contains only the areas that are inside both path A and path B.
/// This operation is useful for finding overlapping regions between shapes.
Intersection,
/// Computes the symmetric difference (exclusive or) of two paths.
///
/// The result contains areas that are inside either path A or path B, but not in both.
/// This operation is useful for creating non-overlapping regions or finding boundaries.
Exclusion,
/// Divides the first path using the second path as a "knife".
///
/// This operation splits path A wherever it intersects with path B, but keeps all
/// parts of path A. It's useful for creating segments or partitioning shapes.
Division,
/// Breaks both paths into separate pieces where they intersect.
///
/// This operation splits both path A and path B at their intersection points,
/// resulting in all possible non-overlapping segments from both paths.
/// It's useful for creating detailed breakdowns of overlapping shapes.
Fracture,
}
/// Specifies how to determine the "inside" of a path for filling.
#[derive(Debug, Clone, Copy)]
pub enum FillRule {
/// A point is inside if a ray from the point to infinity crosses an odd number of path segments.
NonZero,
/// A point is inside if a ray from the point to infinity crosses an even number of path segments.
EvenOdd,
}
pub const EPS: Epsilons = Epsilons {
point: 1e-5,
linear: 1e-4,
param: 1e-8,
};
type MajorGraphEdgeStage1 = (PathSegment, u8);
type MajorGraphEdgeStage2 = (PathSegment, u8, Aabb);
#[derive(Debug, Clone)]
pub struct MajorGraphEdge {
seg: PathSegment,
parent: u8,
incident_vertices: [MajorVertexKey; 2],
direction_flag: Direction,
twin: Option<MajorEdgeKey>,
}
#[derive(Debug, Clone, Default)]
pub struct MajorGraphVertex {
#[cfg_attr(not(feature = "logging"), expect(dead_code))]
pub point: DVec2,
outgoing_edges: SmallVec<[MajorEdgeKey; 4]>,
}
/// Represents the initial graph structure used in boolean operations.
///
/// This graph contains all segments from both input paths.
#[derive(Debug, Clone)]
struct MajorGraph {
edges: SlotMap<MajorEdgeKey, MajorGraphEdge>,
vertices: SlotMap<MajorVertexKey, MajorGraphVertex>,
}
#[derive(Debug, Clone, PartialEq)]
struct MinorGraphEdge {
segments: SmallVec<[PathSegment; 4]>,
parent: u8,
incident_vertices: [MinorVertexKey; 2],
direction_flag: Direction,
twin: Option<MinorEdgeKey>,
}
impl MinorGraphEdge {
fn start_segment(&self) -> PathSegment {
let segment = self.segments[0];
match self.direction_flag {
Direction::Forward => segment,
Direction::Backwards => segment.reverse(),
}
}
}
// Compares Segments based on their derivative at the start. If the derivative
// is equal, check the curvature instead. This should correctly sort most instances.
fn compare_segments(a: &PathSegment, b: &PathSegment) -> Ordering {
let angle_a = a.start_angle();
let angle_b = b.start_angle();
// Normalize angles to [0, 2π)
let angle_a = (angle_a * 1000.).round() / 1000.;
let angle_b = (angle_b * 1000.).round() / 1000.;
// Compare angles first
match angle_b.partial_cmp(&angle_a) {
Some(Ordering::Equal) => {
// If angles are equal (or very close), compare curvatures
let curvature_a = a.start_curvature();
let curvature_b = b.start_curvature();
curvature_a.partial_cmp(&curvature_b).unwrap_or(Ordering::Equal)
}
Some(ordering) => ordering,
None => Ordering::Equal, // Handle NaN cases
}
}
impl PartialOrd for MinorGraphEdge {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(compare_segments(&self.start_segment(), &other.start_segment()))
}
}
#[derive(Debug, Clone, Default)]
struct MinorGraphVertex {
outgoing_edges: SmallVec<[MinorEdgeKey; 8]>,
}
#[derive(Debug, Clone)]
struct MinorGraphCycle {
segments: Vec<PathSegment>,
parent: u8,
direction_flag: Direction,
}
/// Represents a simplified graph structure derived from the MajorGraph.
///
/// This graph combines collinear segments and removes unnecessary vertices.
#[derive(Debug, Clone)]
struct MinorGraph {
edges: SlotMap<MinorEdgeKey, MinorGraphEdge>,
vertices: SlotMap<MinorVertexKey, MinorGraphVertex>,
cycles: Vec<MinorGraphCycle>,
}
#[derive(Debug, Clone, PartialEq)]
struct DualGraphHalfEdge {
segments: Vec<PathSegment>,
parent: u8,
incident_vertex: DualVertexKey,
direction_flag: Direction,
twin: Option<DualEdgeKey>,
}
impl DualGraphHalfEdge {
fn start_segment(&self) -> PathSegment {
let segment = self.segments[0];
match self.direction_flag {
Direction::Forward => segment,
Direction::Backwards => segment.reverse(),
}
}
fn outer_boundnig_box(&self) -> Aabb {
self.segments
.iter()
.map(|seg| seg.approx_bounding_box())
.fold(Default::default(), |old, new| merge_bounding_boxes(&old, &new))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct DualGraphVertex {
incident_edges: Vec<DualEdgeKey>,
}
/// Represents a component in the dual graph.
///
/// A component is a connected subset of the dual graph, typically corresponding
/// to a distinct region in the original paths.
#[derive(Debug, Clone)]
struct DualGraphComponent {
edges: Vec<DualEdgeKey>,
vertices: Vec<DualVertexKey>,
outer_face: Option<DualVertexKey>,
inner_bb: Aabb,
outer_bb: Aabb,
}
/// Represents the dual graph of the MinorGraph.
///
/// In this graph, faces of the MinorGraph become vertices, and edges represent
/// adjacency between faces. This structure is crucial for determining the
/// inside/outside regions of the paths.
#[derive(Debug, Clone)]
struct DualGraph {
components: Vec<DualGraphComponent>,
edges: SlotMap<DualEdgeKey, DualGraphHalfEdge>,
vertices: SlotMap<DualVertexKey, DualGraphVertex>,
}
/// Represents the hierarchical nesting of regions in the paths.
///
/// This tree structure captures how different regions of the paths are contained
/// within each other
#[derive(Debug, Clone)]
struct NestingTree {
component: DualGraphComponent,
outgoing_edges: HashMap<DualVertexKey, Vec<NestingTree>>,
}
#[cfg(feature = "logging")]
fn major_graph_to_dot(graph: &MajorGraph) -> String {
let mut dot = String::from("digraph {\n");
for (vertex_key, vertex) in &graph.vertices {
dot.push_str(&format!(" {:?} [label=\"{:.1},{:.1}\"]\n", (vertex_key.0.as_ffi() & 0xFF), vertex.point.x, vertex.point.y));
}
for (_, edge) in &graph.edges {
dot.push_str(&format!(
" {:?} -> {:?}: {:0b}\n",
(edge.incident_vertices[0].0.as_ffi() & 0xFF),
(edge.incident_vertices[1].0.as_ffi() & 0xFF),
edge.parent
));
}
dot.push_str("}\n");
dot
}
#[cfg(feature = "logging")]
fn minor_graph_to_dot(edges: &SlotMap<MinorEdgeKey, MinorGraphEdge>) -> String {
let mut dot = String::from("digraph {\n");
for edge in edges.values() {
dot.push_str(&format!(
" {:?} -> {:?}: {:0b}\n",
(edge.incident_vertices[0].0.as_ffi() & 0xFF),
(edge.incident_vertices[1].0.as_ffi() & 0xFF),
edge.parent
));
}
dot.push_str("}\n");
dot
}
#[cfg(feature = "logging")]
fn dual_graph_to_dot(components: &[DualGraphComponent], edges: &SlotMap<DualEdgeKey, DualGraphHalfEdge>) -> String {
let mut dot = String::from("strict graph {\n");
for component in components {
for &edge_key in &component.edges {
let edge = &edges[edge_key];
dot.push_str(&format!(
" {:?} -- {:?}\n",
(edge.incident_vertex.0.as_ffi() & 0xFF),
(edges[edge.twin.unwrap()].incident_vertex.0.as_ffi() & 0xFF)
));
}
}
dot.push_str("}\n");
dot
}
fn segment_to_edge(parent: u8) -> impl Fn(&PathSegment) -> Option<MajorGraphEdgeStage1> {
move |seg| {
if bounding_box_max_extent(&seg.bounding_box()) < EPS.point / 2. {
return None;
}
match seg {
// Convert Line Segments expressed as cubic beziers to proper line segments
PathSegment::Cubic(start, _, _, end) => {
let direction = seg.sample_at(0.1);
if (*end - *start).angle_to(direction - *start).abs() < EPS.point * 4. {
Some((PathSegment::Line(*start, *end), parent))
} else {
Some((*seg, parent))
}
}
seg => Some((*seg, parent)),
}
}
}
fn split_at_self_intersections(edges: &mut Vec<MajorGraphEdgeStage1>) {
let mut new_edges = Vec::new();
for (seg, parent) in edges.iter_mut() {
if let PathSegment::Cubic(..) = seg {
if let Some(intersection) = path_cubic_segment_self_intersection(seg) {
let mut intersection = intersection;
if intersection[0] > intersection[1] {
intersection.swap(0, 1);
}
let [t1, t2] = intersection;
if (t1 - t2).abs() < EPS.param {
let (seg1, seg2) = seg.split_at(t1);
*seg = seg1;
new_edges.push((seg2, *parent));
} else {
let (seg1, tmp_seg) = seg.split_at(t1);
let (seg2, seg3) = &tmp_seg.split_at((t2 - t1) / (1. - t1));
*seg = seg1;
new_edges.push((*seg2, *parent));
new_edges.push((*seg3, *parent));
}
}
}
}
edges.extend(new_edges);
}
/// Splits path segments at their intersections with other segments.
///
/// This function performs the following steps:
/// 1. Computes bounding boxes for all input edges.
/// 2. Creates a spatial index (quad tree) of edges for efficient intersection checks.
/// 3. For each edge:
/// a. Finds potential intersecting edges using the spatial index.
/// b. Computes precise intersections with these candidates.
/// c. Records the intersection points as split locations.
/// 4. Splits the original edges at the recorded intersection points.
/// 5. Returns the split edges along with an overall bounding box.
///
/// The function uses an epsilon value to handle floating-point imprecision
/// when determining if intersections occur at endpoints.
///
/// # Arguments
///
/// * `edges` - A slice of initial path segments (MajorGraphEdgeStage1).
///
/// # Returns
///
/// A tuple containing:
/// * A vector of split edges (MajorGraphEdgeStage2).
/// * An optional overall bounding box (AaBb) for all edges.
fn split_at_intersections(edges: &[MajorGraphEdgeStage1]) -> Vec<MajorGraphEdgeStage1> {
// Step 1: Add bounding boxes to edges
let with_bounding_box: Vec<MajorGraphEdgeStage2> = edges.iter().map(|(seg, parent)| (*seg, *parent, seg.approx_bounding_box())).collect();
// Step 2: Calculate total bounding box
let total_bounding_box = with_bounding_box.iter().fold(Default::default(), |acc, (_, _, bb)| merge_bounding_boxes(&acc, bb));
let max_extent = bounding_box_max_extent(&total_bounding_box);
let cell_size = max_extent / (edges.len() as f64).sqrt();
// Step 3: Create grid for efficient intersection checks
let mut grid = Grid::new(cell_size, edges.len());
// Step 3: Create edge tree for efficient intersection checks
// let mut edge_tree = QuadTree::new(total_bounding_box, INTERSECTION_TREE_DEPTH, 16);
// let mut rtree = crate::util::rtree::RTree::new(24);
let mut splits_per_edge: Vec<Vec<f64>> = vec![Vec::new(); edges.len()];
fn add_split(splits_per_edge: &mut [Vec<f64>], i: usize, t: f64) {
splits_per_edge[i].push(t);
}
// let mut candidates = Vec::with_capacity(8);
let mut candidates = BitVec::new(edges.len());
// Step 4: Find intersections and record split points
for (i, edge) in with_bounding_box.iter().enumerate() {
// let candidates = edge_tree.find(&edge.2);
// let mut quad_candidates: Vec<_> = quad_candidates.into_iter().collect();
// quad_candidates.sort_unstable();
// let mut candidates = rtree.query(&edge.2);
// candidates.sort_unstable();
// assert_eq!(candidates, quad_candidates);
candidates.clear();
grid.query(&edge.2, &mut candidates);
for j in candidates.iter_set_bits() {
let candidate: &(PathSegment, u8) = &edges[j];
let include_endpoints = edge.1 != candidate.1 || !(candidate.0.end().abs_diff_eq(edge.0.start(), EPS.point) || candidate.0.start().abs_diff_eq(edge.0.end(), EPS.point));
let intersection = path_segment_intersection(&edge.0, &candidate.0, include_endpoints, &EPS);
for [t0, t1] in intersection {
add_split(&mut splits_per_edge, i, t0);
add_split(&mut splits_per_edge, j, t1);
}
}
grid.insert(&edge.2, i);
// edge_tree.insert(edge.2, i);
// rtree.insert(edge.2, i);
}
// Step 5: Apply splits to create new edges
let mut new_edges = Vec::new();
for (i, (seg, parent, _)) in with_bounding_box.into_iter().enumerate() {
if let Some(splits) = splits_per_edge.get(i) {
let mut splits = splits.clone();
splits.sort_by(|a, b| a.partial_cmp(b).unwrap());
let mut tmp_seg = seg;
let mut prev_t = 0.;
for &t in splits.iter() {
if t > 1. - EPS.param {
break;
}
let tt = (t - prev_t) / (1. - prev_t);
prev_t = t;
if tt < EPS.param {
continue;
}
if tt > 1. - EPS.param {
continue;
}
let (seg1, seg2) = tmp_seg.split_at(tt);
new_edges.push((seg1, parent));
tmp_seg = seg2;
}
new_edges.push((tmp_seg, parent));
} else {
new_edges.push((seg, parent));
}
}
new_edges
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {
Forward,
Backwards,
}
impl std::ops::Neg for Direction {
type Output = Self;
fn neg(self) -> Self::Output {
match self {
Self::Forward => Self::Backwards,
Self::Backwards => Self::Forward,
}
}
}
impl std::ops::Not for Direction {
type Output = Self;
fn not(self) -> Self::Output {
match self {
Self::Forward => Self::Backwards,
Self::Backwards => Self::Forward,
}
}
}
impl Direction {
pub fn forward(self) -> bool {
self == Self::Forward
}
}
const ROUNDING_FACTOR: f64 = 1.0 / (2. * EPS.point);
fn round_point(point: DVec2) -> I64Vec2 {
(point * ROUNDING_FACTOR).round().as_i64vec2()
}
type Edges = SmallVec<[(PathSegment, u8, MajorEdgeKey, MajorEdgeKey); 2]>;
fn find_vertices(edges: &[MajorGraphEdgeStage1]) -> MajorGraph {
let mut graph = MajorGraph {
edges: SlotMap::with_capacity_and_key(edges.len() * 2),
vertices: SlotMap::with_capacity_and_key(edges.len()),
};
let mut vertex_pair_id_to_edges: HashMap<_, Edges> = new_hash_map(edges.len());
let mut vertex_hashmap: HashMap<I64Vec2, MajorVertexKey> = new_hash_map(edges.len() * 2);
for (seg, parent) in edges {
let mut get_vertex = |point: DVec2| -> MajorVertexKey {
let rounded = round_point(point);
for dx in -1..=1 {
for dy in -1..=1 {
let offset = I64Vec2::new(dx, dy);
if let Some(&vertex) = vertex_hashmap.get(&(rounded + offset)) {
return vertex;
}
}
}
let vertex_key = graph.vertices.insert(MajorGraphVertex {
point,
outgoing_edges: SmallVec::new(),
});
vertex_hashmap.insert(rounded, vertex_key);
vertex_key
};
// we should subtract the center instead here
let start_vertex = get_vertex(seg.start());
let end_vertex = get_vertex(seg.end());
if start_vertex == end_vertex {
match seg {
PathSegment::Line(..) => continue,
PathSegment::Cubic(_, c1, c2, _) => {
if c1.abs_diff_eq(*c2, EPS.point) {
continue;
}
}
PathSegment::Quadratic(_, c, _) => {
if seg.start().abs_diff_eq(*c, EPS.point) {
continue;
}
}
PathSegment::Arc(_, _, _, _, _, false, _) => continue,
_ => {}
}
}
let vertex_pair_id = (start_vertex.min(end_vertex), start_vertex.max(end_vertex));
if let Some(existing_edges) = vertex_pair_id_to_edges.get(&vertex_pair_id) {
if let Some(existing_edge) = existing_edges
.iter()
.find(|(other_seg, ..)| segments_equal(seg, other_seg, EPS.point) || segments_equal(&seg.reverse(), other_seg, EPS.point))
{
if existing_edge.1 != *parent {
graph.edges[existing_edge.2].parent = 0b11;
graph.edges[existing_edge.3].parent = 0b11;
}
continue;
}
}
let fwd_edge_key = graph.edges.insert(MajorGraphEdge {
seg: *seg,
parent: *parent,
incident_vertices: [start_vertex, end_vertex],
direction_flag: Direction::Forward,
twin: None,
});
let bwd_edge_key = graph.edges.insert(MajorGraphEdge {
seg: *seg,
parent: *parent,
incident_vertices: [end_vertex, start_vertex],
direction_flag: Direction::Backwards,
twin: Some(fwd_edge_key),
});
graph.edges[fwd_edge_key].twin = Some(bwd_edge_key);
graph.vertices[start_vertex].outgoing_edges.push(fwd_edge_key);
graph.vertices[end_vertex].outgoing_edges.push(bwd_edge_key);
vertex_pair_id_to_edges.entry(vertex_pair_id).or_default().push((*seg, *parent, fwd_edge_key, bwd_edge_key));
}
graph
}
fn get_order(vertex: &MajorGraphVertex) -> usize {
vertex.outgoing_edges.len()
}
/// Computes the minor graph from the major graph.
///
/// This function simplifies the graph structure by performing the following steps:
/// 1. Iterates through vertices of the major graph.
/// 2. For vertices with exactly two edges (degree 2):
/// a. Combines the two edges into a single edge if they have the same parent.
/// b. Updates the endpoints of the new edge to skip the current vertex.
/// 3. For vertices with degree != 2:
/// a. Creates a new vertex in the minor graph.
/// b. Creates new edges in the minor graph for each outgoing edge.
/// 4. Handles any cyclic components (closed loops with no high-degree vertices).
///
/// The resulting minor graph preserves the topological structure of the paths
/// while reducing the number of vertices and edges.
///
/// # Arguments
///
/// * `major_graph` - A reference to the MajorGraph.
///
/// # Returns
///
/// A new MinorGraph representing the simplified structure.
fn compute_minor(major_graph: &MajorGraph) -> MinorGraph {
let vertex_count = major_graph.vertices.len();
let edge_count = major_graph.edges.len();
let mut new_edges = SlotMap::with_capacity_and_key(edge_count / 2);
let mut new_vertices = SlotMap::with_capacity_and_key(vertex_count.ilog2() as usize + 2);
let mut to_minor_vertex = new_hash_map(vertex_count);
let mut id_to_edge = new_hash_map(edge_count);
// merge with to_minor_vertex
let mut visited = HashSet::with_capacity_and_hasher(vertex_count, Default::default());
// Handle components that are not cycles
for (major_vertex_key, vertex) in &major_graph.vertices {
// Edges are contracted
if get_order(vertex) == 2 {
continue;
}
let start_vertex = *to_minor_vertex
.entry(major_vertex_key)
.or_insert_with(|| new_vertices.insert(MinorGraphVertex { outgoing_edges: SmallVec::new() }));
for &start_edge_key in &vertex.outgoing_edges {
let mut segments = SmallVec::new();
let mut edge_key = start_edge_key;
let mut edge = &major_graph.edges[edge_key];
while edge.parent == major_graph.edges[start_edge_key].parent
&& edge.direction_flag == major_graph.edges[start_edge_key].direction_flag
&& get_order(&major_graph.vertices[edge.incident_vertices[1]]) == 2
{
segments.push(edge.seg);
visited.insert(edge.incident_vertices[1]);
let next_vertex = &major_graph.vertices[edge.incident_vertices[1]];
// Choose the edge which is not our twin so we can make progress
edge_key = *next_vertex.outgoing_edges.iter().find(|&&e| Some(e) != edge.twin).unwrap();
edge = &major_graph.edges[edge_key];
}
segments.push(edge.seg);
let end_vertex = *to_minor_vertex
.entry(edge.incident_vertices[1])
.or_insert_with(|| new_vertices.insert(MinorGraphVertex { outgoing_edges: SmallVec::new() }));
assert!(major_graph.edges[start_edge_key].twin.is_some());
assert!(edge.twin.is_some());
let edge_id = (start_edge_key, edge_key);
let twin_id = (edge.twin.unwrap(), major_graph.edges[start_edge_key].twin.unwrap());
let twin_key = id_to_edge.get(&twin_id);
let new_edge_key = new_edges.insert(MinorGraphEdge {
segments,
parent: major_graph.edges[start_edge_key].parent,
incident_vertices: [start_vertex, end_vertex],
direction_flag: major_graph.edges[start_edge_key].direction_flag,
twin: twin_key.copied(),
});
if let Some(&twin_key) = twin_key {
new_edges[twin_key].twin = Some(new_edge_key);
}
id_to_edge.insert(edge_id, new_edge_key);
new_vertices[start_vertex].outgoing_edges.push(new_edge_key);
}
}
// Handle cyclic components (if any)
let mut cycles = Vec::new();
for (major_vertex_key, vertex) in &major_graph.vertices {
if vertex.outgoing_edges.len() != 2 || visited.contains(&major_vertex_key) {
continue;
}
let mut edge_key = vertex.outgoing_edges[0];
let mut edge = &major_graph.edges[edge_key];
let mut cycle = MinorGraphCycle {
segments: Vec::with_capacity(4),
parent: edge.parent,
direction_flag: edge.direction_flag,
};
loop {
cycle.segments.push(edge.seg);
visited.insert(edge.incident_vertices[0]);
assert_eq!(major_graph.vertices[edge.incident_vertices[1]].outgoing_edges.len(), 2, "Found an unvisited vertex of order != 2.");
let next_vertex = &major_graph.vertices[edge.incident_vertices[1]];
edge_key = *next_vertex.outgoing_edges.iter().find(|&&e| Some(e) != edge.twin).unwrap();
edge = &major_graph.edges[edge_key];
if edge.incident_vertices[0] == major_vertex_key {
break;
}
}
cycles.push(cycle);
}
MinorGraph {
edges: new_edges,
vertices: new_vertices,
cycles,
}
}
fn remove_dangling_edges(graph: &mut MinorGraph) {
// Basically DFS for each parent with BFS number
fn walk(parent: u8, graph: &MinorGraph) -> HashSet<MinorVertexKey> {
// merge
let vertex_count = graph.vertices.len();
let mut kept_vertices = HashSet::with_capacity_and_hasher(vertex_count, Default::default());
let mut vertex_to_level = new_hash_map(vertex_count);
fn visit(
vertex: MinorVertexKey,
incoming_edge: Option<MinorEdgeKey>,
level: usize,
graph: &MinorGraph,
vertex_to_level: &mut HashMap<MinorVertexKey, usize>,
kept_vertices: &mut HashSet<MinorVertexKey>,
parent: u8,
) -> usize {
if let Some(&existing_level) = vertex_to_level.get(&vertex) {
return existing_level;
}
vertex_to_level.insert(vertex, level);
let mut min_level = usize::MAX;
for &edge_key in &graph.vertices[vertex].outgoing_edges {
let edge = &graph.edges[edge_key];
if edge.parent & parent != 0 && Some(edge_key) != incoming_edge {
min_level = min_level.min(visit(edge.incident_vertices[1], edge.twin, level + 1, graph, vertex_to_level, kept_vertices, parent));
}
}
if min_level <= level {
kept_vertices.insert(vertex);
}
min_level
}
for edge in graph.edges.values() {
if edge.parent & parent != 0 {
visit(edge.incident_vertices[0], None, 0, graph, &mut vertex_to_level, &mut kept_vertices, parent);
}
}
kept_vertices
}
let kept_vertices_a = walk(1, graph);
let kept_vertices_b = walk(2, graph);
graph.vertices.retain(|k, _| kept_vertices_a.contains(&k) || kept_vertices_b.contains(&k));
for vertex in graph.vertices.values_mut() {
vertex.outgoing_edges.retain(|edge_key| {
let edge = &graph.edges[*edge_key];
(edge.parent & 1 == 1 && kept_vertices_a.contains(&edge.incident_vertices[0]) && kept_vertices_a.contains(&edge.incident_vertices[1]))
|| (edge.parent & 2 == 2 && kept_vertices_b.contains(&edge.incident_vertices[0]) && kept_vertices_b.contains(&edge.incident_vertices[1]))
});
}
// TODO(@TrueDoctor): merge
graph.edges.retain(|_, edge| {
(edge.parent & 1 == 1 && kept_vertices_a.contains(&edge.incident_vertices[0]) && kept_vertices_a.contains(&edge.incident_vertices[1]))
|| (edge.parent & 2 == 2 && kept_vertices_b.contains(&edge.incident_vertices[0]) && kept_vertices_b.contains(&edge.incident_vertices[1]))
});
}
fn sort_outgoing_edges_by_angle(graph: &mut MinorGraph) {
for (vertex_key, vertex) in graph.vertices.iter_mut() {
if vertex.outgoing_edges.len() > 2 {
vertex.outgoing_edges.sort_by(|&a, &b| graph.edges[a].partial_cmp(&graph.edges[b]).unwrap());
if cfg!(feature = "logging") {
eprintln!("Outgoing edges for {vertex_key:?}:");
for &edge_key in &vertex.outgoing_edges {
let edge = &graph.edges[edge_key];
let angle = edge.start_segment().start_angle();
eprintln!("{:?}: {}°", edge_key.0, angle.to_degrees())
}
}
}
}
}
#[cfg(feature = "logging")]
fn face_to_polygon(face: &DualGraphVertex, edges: &SlotMap<DualEdgeKey, DualGraphHalfEdge>) -> Vec<DVec2> {
const CNT: usize = 3;
face.incident_edges
.iter()
.flat_map(|&edge_key| {
let edge = &edges[edge_key];
edge.segments.iter().flat_map(move |seg| {
(0..CNT).map(move |i| {
let t0 = i as f64 / CNT as f64;
let t = if edge.direction_flag.forward() { t0 } else { 1. - t0 };
seg.sample_at(t)
})
})
})
.collect()
}
fn interval_crosses_point(a: f64, b: f64, p: f64) -> bool {
let dy1 = a >= p;
let dy2 = b < p;
dy1 == dy2
}
fn line_segment_intersects_horizontal_ray(a: DVec2, b: DVec2, point: DVec2) -> bool {
if !interval_crosses_point(a.y, b.y, point.y) {
return false;
}
let x = crate::math::lin_map(point.y, a.y, b.y, a.x, b.x);
x >= point.x
}
#[cfg(feature = "logging")]
fn compute_point_winding(polygon: &[DVec2], tested_point: DVec2) -> i32 {
if polygon.len() <= 2 {
return 0;
}
let mut prev_point = polygon[polygon.len() - 1];
let mut winding = 0;
for &point in polygon {
if line_segment_intersects_horizontal_ray(prev_point, point, tested_point) {
winding += if point.y > prev_point.y { -1 } else { 1 };
}
prev_point = point;
}
winding
}
#[cfg(feature = "logging")]
fn compute_winding(face: &DualGraphVertex, edges: &SlotMap<DualEdgeKey, DualGraphHalfEdge>) -> Option<i32> {
let polygon = face_to_polygon(face, edges);
for i in 0..polygon.len() {
let a = polygon[i];
let b = polygon[(i + 1) % polygon.len()];
let c = polygon[(i + 2) % polygon.len()];
let center = (a + b + c) / 3.;
let winding = compute_point_winding(&polygon, center);
if winding != 0 {
return Some(winding);
}
}
None
}
fn compute_signed_area(face: &DualGraphVertex, edges: &SlotMap<DualEdgeKey, DualGraphHalfEdge>) -> f64 {
const CNT: usize = 3;
let mut area = 0.0;
let mut prev_point: Option<DVec2> = None;
let mut start_point = None;
let mut point_count = 0;
for &edge_key in &face.incident_edges {
let edge = &edges[edge_key];
for seg in &edge.segments {
for i in 0..CNT {
let t0 = i as f64 / CNT as f64;
let t = if edge.direction_flag.forward() { t0 } else { 1. - t0 };
let current_point = seg.sample_at(t);
if let Some(prev) = prev_point {
area += prev.x * current_point.y;
area -= current_point.x * prev.y;
} else {
start_point = Some(current_point);
}
prev_point = Some(current_point);
point_count += 1;
}
}
}
if point_count <= 4 {
return -f64::EPSILON;
}
// Close the polygon
if let (Some(start), Some(end)) = (start_point, prev_point) {
area += end.x * start.y;
area -= start.x * end.y;
}
#[cfg(feature = "logging")]
{
eprintln!("vertex: {:?}", face);
eprintln!("winding: {}", area);
}
area
}
/// Computes the dual graph from the minor graph.
///
/// This function creates the dual graph by following these steps:
/// 1. Initializes empty structures for dual graph vertices and edges.
/// 2. For each edge in the minor graph:
/// a. Creates a new face (dual vertex) if not already created.
/// b. Traverses around the face, creating dual edges for each minor edge.
/// c. Connects dual edges to their twins (edges representing the same minor edge).
/// 3. Handles special cases like isolated cycles.
/// 4. Groups dual graph elements into connected components.
/// 5. Determines the outer face for each component.
///
/// The dual graph represents faces of the minor graph as vertices and adjacencies
/// between faces as edges, effectively flipping the concepts of vertices and faces.
///
/// # Arguments
///
/// * `minor_graph` - A reference to the MinorGraph.
///
/// # Returns
///
/// A Result containing either the computed DualGraph or a BooleanError if the
/// operation cannot be completed successfully.
fn compute_dual(minor_graph: &MinorGraph) -> Result<DualGraph, BooleanError> {
let mut new_vertices: Vec<DualVertexKey> = Vec::new();
let edge_count = minor_graph.edges.len();
let mut minor_to_dual_edge: HashMap<MinorEdgeKey, DualEdgeKey> = new_hash_map(edge_count);
let mut dual_edges = SlotMap::with_capacity_and_key(edge_count);
let mut dual_vertices = SlotMap::with_key();
for (start_edge_key, start_edge) in &minor_graph.edges {
#[cfg(feature = "logging")]
eprintln!("Processing start edge: {}", (start_edge_key.0.as_ffi() & 0xFF));
if minor_to_dual_edge.contains_key(&start_edge_key) {
continue;
}
let face_key = dual_vertices.insert(DualGraphVertex { incident_edges: Vec::new() });
let mut edge_key = start_edge_key;
let mut edge = start_edge;
loop {
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | true |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/path.rs | libraries/path-bool/src/path.rs | pub(crate) mod intersection_path_segment;
pub(crate) mod line_segment;
pub(crate) mod line_segment_aabb;
pub(crate) mod path_cubic_segment_self_intersection;
pub(crate) mod path_segment;
use glam::DVec2;
#[cfg(feature = "parsing")]
use crate::path_command::{AbsolutePathCommand, PathCommand, to_absolute_commands};
use crate::path_segment::PathSegment;
pub type Path = Vec<PathSegment>;
fn reflect_control_point(point: DVec2, control_point: DVec2) -> DVec2 {
point * 2. - control_point
}
#[cfg(feature = "parsing")]
pub fn path_from_commands<I>(commands: I) -> impl Iterator<Item = PathSegment>
where
I: IntoIterator<Item = PathCommand>,
{
let mut first_point: Option<DVec2> = None;
let mut last_point: Option<DVec2> = None;
let mut last_control_point: Option<DVec2> = None;
to_absolute_commands(commands).filter_map(move |cmd| match cmd {
AbsolutePathCommand::M(point) => {
last_point = Some(point);
first_point = Some(point);
last_control_point = None;
None
}
AbsolutePathCommand::L(point) => {
let start = last_point.unwrap();
last_point = Some(point);
last_control_point = None;
Some(PathSegment::Line(start, point))
}
AbsolutePathCommand::H(x) => {
let start = last_point.unwrap();
let point = DVec2::new(x, start.y);
last_point = Some(point);
last_control_point = None;
Some(PathSegment::Line(start, point))
}
AbsolutePathCommand::V(y) => {
let start = last_point.unwrap();
let point = DVec2::new(start.x, y);
last_point = Some(point);
last_control_point = None;
Some(PathSegment::Line(start, point))
}
AbsolutePathCommand::C(c1, c2, end) => {
let start = last_point.unwrap();
last_point = Some(end);
last_control_point = Some(c2);
Some(PathSegment::Cubic(start, c1, c2, end))
}
AbsolutePathCommand::S(c2, end) => {
let start = last_point.unwrap();
let c1 = reflect_control_point(start, last_control_point.unwrap_or(start));
last_point = Some(end);
last_control_point = Some(c2);
Some(PathSegment::Cubic(start, c1, c2, end))
}
AbsolutePathCommand::Q(c, end) => {
let start = last_point.unwrap();
last_point = Some(end);
last_control_point = Some(c);
Some(PathSegment::Quadratic(start, c, end))
}
AbsolutePathCommand::T(end) => {
let start = last_point.unwrap();
let c = reflect_control_point(start, last_control_point.unwrap_or(start));
last_point = Some(end);
last_control_point = Some(c);
Some(PathSegment::Quadratic(start, c, end))
}
AbsolutePathCommand::A(rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, end) => {
let start = last_point.unwrap();
last_point = Some(end);
last_control_point = None;
Some(PathSegment::Arc(start, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, end))
}
AbsolutePathCommand::Z => {
let start = last_point.unwrap();
let end = first_point.unwrap();
last_point = Some(end);
last_control_point = None;
Some(PathSegment::Line(start, end))
}
})
}
#[cfg(feature = "parsing")]
pub fn path_to_commands<'a, I>(segments: I, eps: f64) -> impl Iterator<Item = PathCommand> + 'a
where
I: IntoIterator<Item = &'a PathSegment> + 'a,
{
let mut last_point: Option<DVec2> = None;
segments
.into_iter()
.flat_map(move |seg| {
let start = seg.start();
let mut commands = Vec::new();
if last_point.is_none_or(|lp| !start.abs_diff_eq(lp, eps)) {
if last_point.is_some() {
commands.push(PathCommand::Absolute(AbsolutePathCommand::Z));
}
commands.push(PathCommand::Absolute(AbsolutePathCommand::M(start)));
}
match seg {
PathSegment::Line(_, end) => {
commands.push(PathCommand::Absolute(AbsolutePathCommand::L(*end)));
last_point = Some(*end);
}
PathSegment::Cubic(_, c1, c2, end) => {
commands.push(PathCommand::Absolute(AbsolutePathCommand::C(*c1, *c2, *end)));
last_point = Some(*end);
}
PathSegment::Quadratic(_, c, end) => {
commands.push(PathCommand::Absolute(AbsolutePathCommand::Q(*c, *end)));
last_point = Some(*end);
}
PathSegment::Arc(_, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, end) => {
commands.push(PathCommand::Absolute(AbsolutePathCommand::A(*rx, *ry, *x_axis_rotation, *large_arc_flag, *sweep_flag, *end)));
last_point = Some(*end);
}
}
commands
})
.chain(std::iter::once(PathCommand::Absolute(AbsolutePathCommand::Z)))
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/lib.rs | libraries/path-bool/src/lib.rs | #![expect(clippy::needless_doctest_main)]
#![doc = include_str!("../README.md")]
mod path_boolean;
// #[cfg(feature = "parsing")]
mod parsing {
pub(crate) mod path_command;
pub(crate) mod path_data;
}
mod util {
pub(crate) mod aabb;
pub(crate) mod epsilons;
pub(crate) mod grid;
pub(crate) mod math;
}
mod path;
#[cfg(test)]
mod visual_tests;
#[cfg(feature = "parsing")]
pub(crate) use parsing::*;
pub(crate) use path::*;
pub(crate) use util::*;
pub use intersection_path_segment::path_segment_intersection;
#[cfg(feature = "parsing")]
pub use parsing::path_data::{path_from_path_data, path_to_path_data};
pub use path_boolean::{BooleanError, EPS, FillRule, PathBooleanOperation, path_boolean};
pub use path_segment::PathSegment;
#[cfg(test)]
mod test {
use crate::path_boolean::{self, FillRule, PathBooleanOperation};
use crate::path_data::{path_from_path_data, path_to_path_data};
use path_boolean::path_boolean;
#[test]
fn square() {
let a = path_from_path_data("M 10 10 L 50 10 L 30 40 Z").unwrap();
let b = path_from_path_data("M 20 30 L 60 30 L 60 50 L 20 50 Z").unwrap();
let union = path_boolean(
&a,
path_boolean::FillRule::NonZero,
&b,
path_boolean::FillRule::NonZero,
path_boolean::PathBooleanOperation::Intersection,
)
.unwrap();
dbg!(path_to_path_data(&union[0], 0.001));
assert!(!union[0].is_empty());
}
#[test]
fn nesting_01() {
let a = path_from_path_data("M 47,24 A 23,23 0 0 1 24,47 23,23 0 0 1 1,24 23,23 0 0 1 24,1 23,23 0 0 1 47,24 Z").unwrap();
let b = path_from_path_data(
"M 37.909023,24 A 13.909023,13.909023 0 0 1 24,37.909023 13.909023,13.909023 0 0 1 10.090978,24 13.909023,13.909023 0 0 1 24,10.090978 13.909023,13.909023 0 0 1 37.909023,24 Z",
)
.unwrap();
let union = path_boolean(&a, path_boolean::FillRule::NonZero, &b, path_boolean::FillRule::NonZero, path_boolean::PathBooleanOperation::Union).unwrap();
dbg!(path_to_path_data(&union[0], 0.001));
assert!(!union[0].is_empty());
}
#[test]
fn semi_circle_join() {
let a = path_from_path_data(
"M 0.000000000000,0.000000000000 C 0.000000000000,0.000000000000 48.487723000000,-68.116546000000 51.950617000000,-96.987654000000 C 53.354187000000,-108.689605000000 5.171145000000,-241.394513000000 -0.000000000000,-254.901235000000 Z M 0.000000000000,0.000000000000 L -0.000000000000,-254.901235000000 Z"
).unwrap();
let b = path_from_path_data(
"M -0.000000000000,0.484328000000 C -0.000000000000,0.484328000000 -48.487723000000,-67.632218000000 -51.950617000000,-96.503326000000 C -53.354187000000,-108.205277000000 -5.171145000000,-240.910185000000 -0.000000000000,-254.416907000000 Z M -0.000000000000,0.484328000000 L -0.000000000000,-254.416907000000 Z",
)
.unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Union).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
dbg!(path_to_path_data(&result[0], 0.001));
// Add more specific assertions about the resulting path if needed
assert!(!result[0].is_empty());
}
#[test]
fn nesting_02() {
let a = path_from_path_data("M 0.99999994,31.334457 C 122.61195,71.81859 -79.025816,-5.5803326 47,32.253367 V 46.999996 H 0.99999994 Z").unwrap();
let b = path_from_path_data("m 25.797222,29.08718 c 0,1.292706 -1.047946,2.340652 -2.340652,2.340652 -1.292707,0 -2.340652,-1.047946 -2.340652,-2.340652 0,-1.292707 1.047945,-2.340652 2.340652,-2.340652 1.292706,0 2.340652,1.047945 2.340652,2.340652 z M 7.5851073,28.332212 c 1e-7,1.292706 -1.0479456,2.340652 -2.3406521,2.340652 -1.2927063,-1e-6 -2.3406518,-1.047946 -2.3406517,-2.340652 -10e-8,-1.292707 1.0479454,-2.340652 2.3406517,-2.340652 1.2927065,-1e-6 2.3406522,1.047945 2.3406521,2.340652 z").unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Union).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
// Add more specific assertions about the resulting path if needed
assert!(!result[0].is_empty());
}
#[test]
fn nesting_03() {
let a = path_from_path_data("m 21.829117,3.5444345 h 4.341766 V 16.502158 H 21.829117 Z M 47,24 A 23,23 0 0 1 24,47 23,23 0 0 1 1,24 23,23 0 0 1 24,1 23,23 0 0 1 47,24 Z").unwrap();
let b = path_from_path_data("M 24 6.4960938 A 17.504802 17.504802 0 0 0 6.4960938 24 A 17.504802 17.504802 0 0 0 24 41.503906 A 17.504802 17.504802 0 0 0 41.503906 24 A 17.504802 17.504802 0 0 0 24 6.4960938 z M 24 12.193359 A 11.805881 11.805881 0 0 1 35.806641 24 A 11.805881 11.805881 0 0 1 24 35.806641 A 11.805881 11.805881 0 0 1 12.193359 24 A 11.805881 11.805881 0 0 1 24 12.193359 z ").unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Union).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
// Add more specific assertions about the resulting path if needed
let path_string = dbg!(path_to_path_data(&result[0], 0.001));
assert_eq!(path_string.chars().filter(|c| c == &'M').count(), 1, "More than one path returned");
assert!(!result[0].is_empty());
}
#[test]
fn simple_07() {
let a = path_from_path_data("M 37.671452,24 C 52.46888,31.142429 42.887716,37.358779 24,37.671452 16.4505,37.796429 10.328548,31.550534 10.328548,24 c 0,-7.550534 6.120918,-13.671452 13.671452,-13.671452 7.550534,0 6.871598,10.389295 13.671452,13.671452 z",
).unwrap();
let b = path_from_path_data("M 37.671452,24 C 33.698699,53.634887 29.50935,49.018306 24,37.671452 20.7021,30.879219 10.328548,31.550534 10.328548,24 c 0,-7.550534 6.120918,-13.671452 13.671452,-13.671452 7.550534,0 14.674677,6.187863 13.671452,13.671452 z").unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Union).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
// Add more specific assertions about the resulting path if needed
dbg!(path_to_path_data(&result[0], 0.001));
assert!(!result[0].is_empty());
}
#[test]
fn rect_ellipse() {
let a = path_from_path_data("M0,0C0,0 100,0 100,0 C100,0 100,100 100,100 C100,100 0,100 0,100 C0,100 0,0 0,0 Z").unwrap();
let b = path_from_path_data("M50,0C77.589239,0 100,22.410761 100,50 C100,77.589239 77.589239,100 50,100 C22.410761,100 0,77.589239 0,50 C0,22.410761 22.410761,0 50,0 Z").unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Union).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
dbg!(path_to_path_data(&result[0], 0.001));
assert!(!result[0].is_empty());
// Add more specific assertions about the resulting path if needed
}
#[test]
fn red_dress_loop() {
let a = path_from_path_data("M969.000000,0.000000C969.000000,0.000000 1110.066898,76.934393 1085.000000,181.000000 C1052.000000,318.000000 1199.180581,334.301571 1277.000000,319.000000 C1455.000000,284.000000 1586.999985,81.000000 1418.000000,0.000000 C1418.000000,0.000000 969.000000,0.000000 969.000000,0.000000").unwrap();
let b = path_from_path_data(
"M1211.000000,0.000000C1211.000000,0.000000 1255.000000,78.000000 1536.000000,95.000000 C1536.000000,95.000000 1536.000000,0.000000 1536.000000,0.000000 C1536.000000,0.000000 1211.000000,0.000000 1211.000000,0.000000 Z",
).unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Intersection).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
dbg!(path_to_path_data(&result[0], 0.001));
// Add more specific assertions about the resulting path if needed
assert!(!result[0].is_empty());
}
#[test]
fn painted_dreams_1() {
let a = path_from_path_data("M969.000000,0.000000C969.000000,0.000000 1110.066898,76.934393 1085.000000,181.000000 C1052.000000,318.000000 1199.180581,334.301571 1277.000000,319.000000 C1455.000000,284.000000 1586.999985,81.000000 1418.000000,0.000000 C1418.000000,0.000000 969.000000,0.000000 969.000000,0.000000 Z").unwrap();
let b = path_from_path_data(
"M763.000000,0.000000C763.000000,0.000000 1536.000000,0.000000 1536.000000,0.000000 C1536.000000,0.000000 1536.000000,254.000000 1536.000000,254.000000 C1536.000000,254.000000 1462.000000,93.000000 1271.000000,199.000000 C1149.163056,266.616314 976.413656,188.510842 908.000000,134.000000 C839.586344,79.489158 763.000000,0.000000 763.000000,0.000000 Z",
).unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Intersection).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
dbg!(path_to_path_data(&result[0], 0.001));
// Add more specific assertions about the resulting path if needed
assert!(!result[0].is_empty());
}
#[test]
fn painted_dreams_2() {
let a = path_from_path_data("M0,340C161.737914,383.575765 107.564182,490.730587 273,476 C419,463 481.741198,514.692273 481.333333,768 C481.333333,768 -0,768 -0,768 C-0,768 0,340 0,340 Z ")
.unwrap();
let b = path_from_path_data(
"M458.370270,572.165771C428.525848,486.720093 368.618805,467.485992 273,476 C107.564178,490.730591 161.737915,383.575775 0,340 C0,340 0,689 0,689 C56,700 106.513901,779.342590 188,694.666687 C306.607422,571.416260 372.033966,552.205139 458.370270,572.165771 Z",
).unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Union).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
dbg!(path_to_path_data(&result[0], 0.001));
// Add more specific assertions about the resulting path if needed
assert!(!result[0].is_empty());
}
#[test]
fn painted_dreams_3() {
let a = path_from_path_data("M889,0C889,0 889,21 898,46 C909.595887,78.210796 872.365858,104.085306 869,147 C865,198 915,237 933,273 C951,309 951.703704,335.407407 923,349 C898.996281,360.366922 881,367 902,394 C923,421 928.592593,431.407407 898,468 C912.888889,472.888889 929.333333,513.333333 896,523 C896,523 876,533.333333 886,572 C896.458810,612.440732 873.333333,657.777778 802.666667,656.444444 C738.670245,655.236965 689,643 655,636 C621,629 604,623 585,666 C566,709 564,768 564,768 C564,768 0,768 0,768 C0,768 0,0 0,0 C0,0 889,0 889,0 Z ").unwrap();
let b = path_from_path_data(
"M552,768C552,768 993,768 993,768 C993,768 1068.918039,682.462471 1093,600 C1126,487 1007.352460,357.386071 957,324 C906.647540,290.613929 842,253 740,298 C638,343 491.342038,421.999263 491.342038,506.753005 C491.342038,641.999411 552,768 552,768 Z ",
).unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Difference).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
dbg!(path_to_path_data(&result[0], 0.001));
// Add more specific assertions about the resulting path if needed
assert!(!result[0].is_empty());
}
#[test]
fn painted_dreams_4() {
let a = path_from_path_data("M458.370270,572.165771C372.033966,552.205139 306.607422,571.416260 188.000000,694.666687 C106.513901,779.342590 56.000000,700.000000 0.000000,689.000000 C0.000000,689.000000 0.000000,768.000000 0.000000,768.000000 C0.000000,768.000000 481.333344,768.000000 481.333344,768.000000 C481.474091,680.589417 474.095154,617.186768 458.370270,572.165771 Z ").unwrap();
let b = path_from_path_data(
"M364.000000,768.000000C272.000000,686.000000 294.333333,468.666667 173.333333,506.666667 C110.156241,526.507407 0.000000,608.000000 0.000000,608.000000 L -0.000000,768.000000 L 364.000000,768.000000 Z",
).unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Difference).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
dbg!(path_to_path_data(&result[0], 0.001));
// Add more specific assertions about the resulting path if needed
assert!(!result[0].is_empty());
}
#[test]
fn painted_dreams_5() {
let a = path_from_path_data("M889.000000,0.000000C889.000000,0.000000 889.000000,21.000000 898.000000,46.000000 C909.595887,78.210796 872.365858,104.085306 869.000000,147.000000 C865.000000,198.000000 915.000000,237.000000 933.000000,273.000000 C951.000000,309.000000 951.703704,335.407407 923.000000,349.000000 C898.996281,360.366922 881.000000,367.000000 902.000000,394.000000 C923.000000,421.000000 928.592593,431.407407 898.000000,468.000000 C912.888889,472.888889 929.333333,513.333333 896.000000,523.000000 C896.000000,523.000000 876.000000,533.333333 886.000000,572.000000 C896.458810,612.440732 873.333333,657.777778 802.666667,656.444444 C738.670245,655.236965 689.000000,643.000000 655.000000,636.000000 C621.000000,629.000000 604.000000,623.000000 585.000000,666.000000 C566.000000,709.000000 564.000000,768.000000 564.000000,768.000000 C564.000000,768.000000 0.000000,768.000000 0.000000,768.000000 C0.000000,768.000000 0.000000,0.000000 0.000000,0.000000 C0.000000,0.000000 889.000000,0.000000 889.000000,0.000000 Z"
).unwrap();
let b = path_from_path_data(
"M891.555556,569.382716C891.555556,569.382716 883.555556,577.777778 879.111111,595.851852 C874.666667,613.925926 857.185185,631.407407 830.814815,633.777778 C804.444444,636.148148 765.629630,637.925926 708.148148,616.296296 C650.666667,594.666667 560.666667,568.000000 468.000000,487.333333 C375.333333,406.666667 283.333333,354.666667 283.333333,354.666667 C332.000000,330.666667 373.407788,298.323579 468.479950,219.785706 C495.739209,197.267187 505.084065,165.580817 514.452332,146.721008 C525.711584,124.054345 577.519713,94.951389 589.958848,64.658436 C601.152263,37.399177 601.175694,0.000010 601.175694,0.000000 C601.175694,0.000000 0.000000,0.000000 0.000000,0.000000 C0.000000,0.000000 0.000000,768.000000 0.000000,768.000000 C0.000000,768.000000 891.555556,768.000000 891.555556,768.000000 C891.555556,768.000000 891.555556,569.382716 891.555556,569.382716 Z",
).unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Intersection).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
dbg!(path_to_path_data(&result[0], 0.001));
// Add more specific assertions about the resulting path if needed
assert!(!result[0].is_empty());
}
#[test]
fn painted_dreams_6() {
let a = path_from_path_data(
"M 969.000000000000,0.000000000000 C 969.000000000000,0.000000000000 1110.066900000000,76.934400000000 1085.000000000000,181.000000000000 C 1052.000000000000,318.000000000000 1199.180600000000,334.301600000000 1277.000000000000,319.000000000000 C 1455.000000000000,284.000000000000 1587.000000000000,81.000000000000 1418.000000000000,0.000000000000 C 1418.000000000000,0.000000000000 969.000000000000,0.000000000000 969.000000000000,0.000000000000 L 969.000000000000,0.000000000000"
).unwrap();
let b = path_from_path_data(
"M 763.000000000000,0.000000000000 C 763.000000000000,0.000000000000 1536.000000000000,0.000000000000 1536.000000000000,0.000000000000 C 1536.000000000000,0.000000000000 1536.000000000000,254.000000000000 1536.000000000000,254.000000000000 C 1536.000000000000,254.000000000000 1462.000000000000,93.000000000000 1271.000000000000,199.000000000000 C 1149.163100000000,266.616300000000 976.413700000000,188.510800000000 908.000000000000,134.000000000000 C 839.586300000000,79.489200000000 763.000000000000,0.000000000000 763.000000000000,0.000000000000 L 763.000000000000,0.000000000000",
).unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Intersection).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
dbg!(path_to_path_data(&result[0], 0.001));
// Add more specific assertions about the resulting path if needed
assert!(!result[0].is_empty());
}
#[test]
fn painted_dreams_7() {
let a = path_from_path_data(
"M 989.666700000000,768.000000000000 C 989.666700000000,768.000000000000 1011.111100000000,786.399400000000 1011.111100000000,786.399400000000 C 1011.111100000000,786.399400000000 1299.306500000000,786.399400000000 1299.306500000000,786.399400000000 C 1299.306500000000,786.399400000000 1318.000000000000,768.000000000000 1318.000000000000,768.000000000000 C 1293.666700000000,681.000000000000 1173.363200000000,625.103600000000 1094.162400000000,594.296600000000 C 1094.162400000000,594.296600000000 1058.747200000000,687.805800000000 989.666700000000,768.000000000000"
).unwrap();
let b = path_from_path_data(
"M 983.155000000000,775.589300000000 L 1004.599400000000,793.988700000000 L 1007.409000000000,796.399400000000 L 1011.111100000000,796.399400000000 L 1299.306500000000,796.399400000000 L 1303.402200000000,796.399400000000 L 1306.321200000000,793.526300000000 L 1325.014800000000,775.126900000000 L 1329.236900000000,770.971200000000 L 1327.630400000000,765.306400000000 C 1302.280700000000,675.920800000000 1179.503900000000,617.211200000000 1097.787500000000,584.976800000000 L 1088.418100000000,581.280900000000 L 1084.806400000000,590.765700000000 C 1084.117400000000,592.575300000000 1049.449700000000,683.516200000000 982.090100000000,761.473400000000 L 975.539200000000,769.055000000000 L 983.155000000000,775.589300000000 M 1003.696800000000,766.861600000000 C 1068.901100000000,687.878900000000 1102.806400000000,599.696700000000 1103.497000000000,597.883400000000 L 1090.537200000000,603.616300000000 C 1165.521500000000,632.344400000000 1279.846400000000,683.736400000000 1306.585700000000,765.203400000000 L 1295.210700000000,776.399400000000 L 1014.813100000000,776.399400000000 L 1003.696800000000,766.861600000000",
).unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Difference).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
dbg!(path_to_path_data(&result[0], 0.001));
// Add more specific assertions about the resulting path if needed
assert!(!result[0].is_empty());
}
#[test]
fn blobs() {
let a = path_from_path_data(
"m658.03348 118.4966c7.85928 4.83645 114.84582 7.8304 127.89652 6.52531 20.97932-2.09799 43.06722-24.79623 43.06722-24.79623 0 0-96.43723-26.02101-108.97311-28.54836-20.22849-4.07832-78.95651 36.37872-61.99063 46.81928z
m658.03348 115.88649c40.45718-30.01653 82.213-45.24662 103.10032-31.32163 7.83037 5.2203-3.58567 22.51547 13.05064 39.152 3.91519 3.9152-129.49099 2.06705-116.15096-7.83037z
m680.87214 56.0165c2.20775-9.60391 62.6449-29.65403 101.79518-30.01652 17.61846-0.16312 119.39605 40.30737 130.50668 54.8128 5.8045 7.57806-76.88558 29.08762-91.35464 31.32162-15.28899 2.36056-144.20983-41.92525-140.94722-56.1179z"
).unwrap();
let b = path_from_path_data("").unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Union).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
dbg!(path_to_path_data(&result[0], 0.001));
// Add more specific assertions about the resulting path if needed
assert!(!result[0].is_empty());
}
#[test]
fn shared_line() {
let a = path_from_path_data(
"m 658.03348,118.4966 c 7.85928,4.83645 114.84582,7.8304 127.89652,6.52531 20.97932,-2.09799 43.06722,-24.79623 43.06722,-24.79623 0,0 -96.43723,-26.02101 -108.97311,-28.54836 -20.22849,-4.07832 -78.95651,36.37872 -61.99063,46.81928 Z"
).unwrap();
let b = path_from_path_data(
"m 658.03348,115.88649 c 40.45718,-30.01653 82.213,-45.24662 103.10032,-31.32163 7.83037,5.2203 -3.58567,22.51547 13.05064,39.152 3.91519,3.9152 -129.49099,2.06705 -116.15096,-7.83037 z",
)
.unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Union).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
dbg!(path_to_path_data(&result[0], 0.001));
// Add more specific assertions about the resulting path if needed
assert!(!result[0].is_empty());
}
#[test]
fn leaf() {
let a = path_from_path_data(
"M 0.000000000000,0.000000000000 C 0.000000000000,0.000000000000 30.204085760000,16.549763300000 72.719386340000,26.932261410000 C 72.719386340000,26.932261410000 70.254313510000,17.656445030000 64.511458520000,11.328808640000 C 64.511458520000,11.328808640000 87.851933730000,7.175523990000 112.835205650000,14.952290640000 C 112.835205650000,14.952290640000 85.410272600000,-0.944114870000 126.097112900000,-8.575894450000 C 118.337466460000,-27.271823700000 151.641256810000,-26.435638610000 157.566270790000,-37.101186050000 C 157.566270790000,-37.101186050000 140.392289790000,-20.685582680000 114.877703390000,-41.337145860000 C 99.535241580000,-45.054042580000 93.348771040000,-46.907137740000 91.251365300000,-51.920903790000 C 88.782358670000,-57.822967180000 120.444444440000,-82.851851850000 141.777777780000,-86.604938270000 C 141.777777780000,-86.604938270000 123.802469140000,-82.654320990000 114.716049380000,-90.160493830000 C 105.629629630000,-97.666666670000 112.345679010000,-115.000000000000 125.382716050000,-124.679012350000 C 125.382716050000,-124.679012350000 112.740740740000,-117.962962960000 115.506172840000,-132.382716050000 C 118.271604940000,-146.802469140000 109.740281350000,-157.864197530000 136.839506170000,-177.617283950000 C 115.506172840000,-165.567901230000 97.333333330000,-150.358024690000 92.395061730000,-161.419753090000 C 81.925925930000,-147.987654320000 66.518518520000,-140.481481480000 66.320987650000,-154.308641980000 C 59.703703700000,-139.000000000000 54.074074070000,-137.518518520000 49.135802470000,-136.333333330000 C 47.555555560000,-141.864197530000 43.456790120000,-172.333333330000 63.802469140000,-190.901234570000 C 48.888888890000,-178.259259260000 20.444444440000,-172.037037040000 28.444444440000,-210.456790120000 C 23.506172840000,-203.938271600000 13.234567900000,-196.432098770000 0.000000000000,-231.000000000000 L 0.000000000000,0.000000000000 Z"
).unwrap();
let b = path_from_path_data(
"M 0.100000000000,0.000000000000 C 0.100000000000,0.000000000000 -30.104085760000,16.549763300000 -72.619386340000,26.932261410000 C -72.619386340000,26.932261410000 -70.154313510000,17.656445030000 -64.411458520000,11.328808640000 C -64.411458520000,11.328808640000 -87.751933730000,7.175523990000 -112.735205650000,14.952290640000 C -112.735205650000,14.952290640000 -85.310272600000,-0.944114870000 -125.997112900000,-8.575894450000 C -118.237466460000,-27.271823700000 -151.541256810000,-26.435638610000 -157.466270790000,-37.101186050000 C -157.466270790000,-37.101186050000 -140.292289790000,-20.685582680000 -114.777703390000,-41.337145860000 C -99.435241580000,-45.054042580000 -93.248771040000,-46.907137740000 -91.151365300000,-51.920903790000 C -88.682358670000,-57.822967180000 -120.344444440000,-82.851851850000 -141.677777780000,-86.604938270000 C -141.677777780000,-86.604938270000 -123.702469140000,-82.654320990000 -114.616049380000,-90.160493830000 C -105.529629630000,-97.666666670000 -112.245679010000,-115.000000000000 -125.282716050000,-124.679012350000 C -125.282716050000,-124.679012350000 -112.640740740000,-117.962962960000 -115.406172840000,-132.382716050000 C -118.171604940000,-146.802469140000 -109.640281350000,-157.864197530000 -136.739506170000,-177.617283950000 C -115.406172840000,-165.567901230000 -97.233333330000,-150.358024690000 -92.295061730000,-161.419753090000 C -81.825925930000,-147.987654320000 -66.418518520000,-140.481481480000 -66.220987650000,-154.308641980000 C -59.603703700000,-139.000000000000 -53.974074070000,-137.518518520000 -49.035802470000,-136.333333330000 C -47.455555560000,-141.864197530000 -43.356790120000,-172.333333330000 -63.702469140000,-190.901234570000 C -48.788888890000,-178.259259260000 -20.344444440000,-172.037037040000 -28.344444440000,-210.456790120000 C -23.406172840000,-203.938271600000 -13.134567900000,-196.432098770000 0.100000000000,-231.000000000000 L 0.100000000000,0.000000000000 Z",
)
.unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Union).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
dbg!(path_to_path_data(&result[0], 0.001));
// Add more specific assertions about the resulting path if needed
assert_eq!(result.len(), 1);
assert!(!result[0].is_empty());
}
#[test]
fn real_01() {
let a = path_from_path_data(
"M 212.67152,105 A 64.171516,64.171516 0 0 1 148.5,169.17152 64.171516,64.171516 0 0 1 84.328484,105 64.171516,64.171516 0 0 1 148.5,40.828484 64.171516,64.171516 0 0 1 212.67152,105 Z",
)
.unwrap();
let b = path_from_path_data(
"m 83.755387,112.6962 h -7.62 v 37.0332 h 7.62 z m 22.097973,9.144 c -3.4544,0 -5.892801,1.4732 -7.620001,4.5212 v -4.064 H 91.12136 v 38.5064 h 7.111999 v -14.3256 c 1.7272,3.048 4.165601,4.4704 7.620001,4.4704 6.604,0 11.4808,-6.1976 11.4808,-14.5288 0,-8.0772 -4.3688,-14.5796 -11.4808,-14.5796 z m -1.6256,5.9436 c 3.6068,0 5.9944,3.5052 5.9944,8.7376 0,4.9784 -2.4892,8.4836 -5.9944,8.4836 -3.556,0 -5.994401,-3.4544 -5.994401,-8.5852 0,-5.1308 2.438401,-8.636 5.994401,-8.636 z m 23.62201,13.97 h -6.9596 c 0.2032,5.9944 4.6228,9.144 12.954,9.144 9.6012,0 11.9888,-5.4864 11.9888,-9.2964 0,-3.556 -1.778,-5.842 -5.3848,-6.9088 l -8.9916,-2.5908 c -1.9812,-0.6096 -2.4892,-1.016 -2.4892,-2.1336 0,-1.524 1.6256,-2.54 4.1148,-2.54 3.4036,0 5.08,1.2192 5.1308,3.7084 h 6.858 c -0.1016,-5.7912 -4.572,-9.2964 -11.938,-9.2964 -6.9596,0 -11.2776,3.5052 -11.2776,9.144 0,5.3848 4.4196,6.2484 5.9944,6.7564 l 8.4836,2.6416 c 1.778,0.5588 2.3876,1.1176 2.3876,2.2352 0,1.6764 -1.9812,2.6924 -5.2832,2.6924 -4.4704,0 -5.1816,-1.6764 -5.588,-3.556 z m 47.59959,7.9756 v -27.432 h -7.112 v 17.1704 c 0,3.2512 -2.286,5.3848 -5.7404,5.3848 -3.048,0 -4.572,-1.6256 -4.572,-4.9276 v -17.6276 h -7.112 v 19.1008 c 0,6.0452 3.3528,9.4996 9.1948,9.4996 3.7084,0 6.1976,-1.3716 8.2296,-4.4196 v 3.2512 z m 6.60404,-27.432 v 27.432 h 7.112 v -16.4592 c 0,-3.3528 1.8288,-5.3848 4.8768,-5.3848 2.3876,0 3.8608,1.3716 3.8608,3.556 v 18.288 h 7.112 v -16.4592 c 0,-3.3528 1.8288,-5.3848 4.8768,-5.3848 2.3876,0 3.8608,1.3716 3.8608,3.556 v 18.288 h 7.112 v -19.4056 c 0,-5.334 -3.2512,-8.4836 -8.7376,-8.4836 -3.4544,0 -5.8928,1.2192 -8.0264,4.064 -1.3208,-2.5908 -4.064,-4.064 -7.4676,-4.064 -3.1496,0 -5.1816,1.0668 -7.5184,3.8608 v -3.4036 z M 81.012192,49.196201 h -7.62 v 37.0332 h 25.3492 v -6.35 h -17.7292 z m 35.305978,9.144 c -8.382,0 -13.5128,5.5372 -13.5128,14.5288 0,9.0424 5.1308,14.5288 13.5636,14.5288 8.3312,0 13.5636,-5.5372 13.5636,-14.3256 0,-9.2964 -5.0292,-14.732 -13.6144,-14.732 z m 0.0508,5.7404 c 3.9116,0 6.4516,3.5052 6.4516,8.89 0,5.1308 -2.6416,8.6868 -6.4516,8.6868 -3.8608,0 -6.4516,-3.556 -6.4516,-8.7884 0,-5.2324 2.5908,-8.7884 6.4516,-8.7884 z m 18.89761,-5.2832 v 27.432 h 7.112 v -14.5796 c 0,-4.1656 2.0828,-6.2484 6.2484,-6.2484 0.762,0 1.27,0.0508 2.2352,0.2032 v -7.2136 c -0.4064,-0.0508 -0.6604,-0.0508 -0.8636,-0.0508 -3.2512,0 -6.096,2.1336 -7.62,5.842 v -5.3848 z m 31.34362,-0.4572 c -7.874,0 -12.7,5.6896 -12.7,14.8844 0,8.7884 4.7752,14.1732 12.5476,14.1732 6.14679,0 11.12519,-3.5052 12.69999,-8.89 h -7.0104 c -0.8636,2.1844 -2.8448,3.4544 -5.43559,3.4544 -4.7752,0 -5.5372,-3.5052 -5.6896,-7.2136 h 18.38959 c 0.0508,-0.6096 0.0508,-0.8636 0.0508,-1.2192 0,-12.1412 -7.366,-15.1892 -12.85239,-15.1892 z m 5.43559,11.684 H 161.1238 c 0.4572,-4.1656 2.2352,-6.2484 5.3848,-6.2484 3.30199,0 5.23239,2.2352 5.53719,6.2484 z m 12.75081,-11.2268 v 27.432 h 7.112 v -16.4592 c 0,-3.3528 1.8288,-5.3848 4.8768,-5.3848 2.3876,0 3.8608,1.3716 3.8608,3.556 v 18.288 h 7.112 v -16.4592 c 0,-3.3528 1.8288,-5.3848 4.8768,-5.3848 2.3876,0 3.8608,1.3716 3.8608,3.556 v 18.288 h 7.112 v -19.4056 c 0,-5.334 -3.2512,-8.4836 -8.7376,-8.4836 -3.4544,0 -5.8928,1.2192 -8.0264,4.064 -1.3208,-2.5908 -4.064,-4.064 -7.4676,-4.064 -3.1496,0 -5.1816,1.0668 -7.5184,3.8608 v -3.4036 z",
)
.unwrap();
let result = path_boolean(&a, FillRule::NonZero, &b, FillRule::NonZero, PathBooleanOperation::Union).unwrap();
// Add assertions here based on expected results
assert_eq!(result.len(), 1, "Expected 1 resulting path for Union operation");
dbg!(path_to_path_data(&result[0], 0.001));
// Add more specific assertions about the resulting path if needed
assert!(!result[0].is_empty());
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/visual_tests.rs | libraries/path-bool/src/visual_tests.rs | use crate::path_boolean::{self, FillRule, PathBooleanOperation};
use crate::path_data::{path_from_path_data, path_to_path_data};
use core::panic;
use glob::glob;
use image::{DynamicImage, GenericImageView, RgbaImage};
use resvg::render;
use resvg::tiny_skia::Transform;
use resvg::usvg::{Options, Tree};
use std::fs;
use std::path::PathBuf;
use svg::parser::Event;
const TOLERANCE: u8 = 84;
fn get_fill_rule(fill_rule: &str) -> FillRule {
match fill_rule {
"evenodd" => FillRule::EvenOdd,
_ => FillRule::NonZero,
}
}
#[test]
fn visual_tests() {
let ops = [
("union", PathBooleanOperation::Union),
("difference", PathBooleanOperation::Difference),
("intersection", PathBooleanOperation::Intersection),
("exclusion", PathBooleanOperation::Exclusion),
("division", PathBooleanOperation::Division),
("fracture", PathBooleanOperation::Fracture),
];
let folders: Vec<(String, PathBuf, &str, PathBooleanOperation)> = glob("visual-tests/*/")
.expect("Failed to read glob pattern")
.flat_map(|entry| {
let dir = entry.expect("Failed to get directory entry");
ops.iter()
.map(move |(op_name, op)| (dir.file_name().unwrap().to_string_lossy().into_owned(), dir.clone(), *op_name, *op))
})
.collect();
let mut failure = false;
for (name, dir, op_name, op) in folders {
let test_name = format!("{} {}", name, op_name);
println!("Running test: {}", test_name);
fs::create_dir_all(dir.join("test-results")).expect("Failed to create test-results directory");
let original_path = dir.join("original.svg");
let mut content = String::new();
let svg_tree = svg::open(&original_path, &mut content).expect("Failed to parse SVG");
let mut paths = Vec::new();
let mut first_path_attributes = String::new();
let mut width = String::new();
let mut height = String::new();
let mut view_box = String::new();
let mut transform = String::new();
for event in svg_tree {
match event {
Event::Tag("svg", svg::node::element::tag::Type::Start, attributes) => {
width = attributes.get("width").map(|s| s.to_string()).unwrap_or_default();
height = attributes.get("height").map(|s| s.to_string()).unwrap_or_default();
view_box = attributes.get("viewBox").map(|s| s.to_string()).unwrap_or_default();
}
Event::Tag("g", svg::node::element::tag::Type::Start, attributes) => {
if let Some(transform_attr) = attributes.get("transform") {
transform = transform_attr.to_string();
}
}
Event::Tag("path", svg::node::element::tag::Type::Empty, attributes) => {
let data = attributes.get("d").map(|s| s.to_string()).expect("Path data not found");
let fill_rule = attributes.get("fill-rule").map(|v| v.to_string()).unwrap_or_else(|| "nonzero".to_string());
paths.push((data, fill_rule));
// Store attributes of the first path
if first_path_attributes.is_empty() {
for (key, value) in attributes.iter() {
if key != "d" && key != "id" {
first_path_attributes.push_str(&format!("{}=\"{}\" ", key, value));
}
}
}
}
_ => {}
}
}
if (width.is_empty() || height.is_empty()) && !view_box.is_empty() {
let vb: Vec<&str> = view_box.split_whitespace().collect();
if vb.len() == 4 {
width = vb[2].to_string();
height = vb[3].to_string();
}
}
if width.is_empty() || height.is_empty() {
panic!("Failed to extract width and height from SVG");
}
let a_node = paths[0].clone();
let b_node = paths[1].clone();
let a = path_from_path_data(&a_node.0).unwrap();
let b = path_from_path_data(&b_node.0).unwrap();
let a_fill_rule = get_fill_rule(&a_node.1);
let b_fill_rule = get_fill_rule(&b_node.1);
let result = path_boolean::path_boolean(&a, a_fill_rule, &b, b_fill_rule, op).unwrap();
// Create the result SVG with correct dimensions and transform
let mut result_svg = format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{}\" height=\"{}\" viewBox=\"{}\">", width, height, view_box);
if !transform.is_empty() {
result_svg.push_str(&format!("<g transform=\"{}\">", transform));
}
for path in &result {
result_svg.push_str(&format!("<path d=\"{}\" {}/>", path_to_path_data(path, 1e-4), first_path_attributes));
}
if !transform.is_empty() {
result_svg.push_str("</g>");
}
result_svg.push_str("</svg>");
// Save the result SVG
let destination_path = dir.join("test-results").join(format!("{}-ours.svg", op_name));
fs::write(&destination_path, &result_svg).expect("Failed to write result SVG");
// Render and compare images
let ground_truth_path = dir.join(format!("{}.svg", op_name));
let ground_truth_svg = fs::read_to_string(&ground_truth_path).expect("Failed to read ground truth SVG");
let ours_image = render_svg(&result_svg);
let ground_truth_image = render_svg(&ground_truth_svg);
let ours_png_path = dir.join("test-results").join(format!("{}-ours.png", op_name));
ours_image.save(&ours_png_path).expect("Failed to save our PNG");
let ground_truth_png_path = dir.join("test-results").join(format!("{}.png", op_name));
ground_truth_image.save(&ground_truth_png_path).expect("Failed to save ground truth PNG");
failure |= compare_images(&ours_image, &ground_truth_image, TOLERANCE);
// Check the number of paths
let result_path_count = result.len();
let ground_truth_path_count = ground_truth_svg.matches("<path").count();
if result_path_count != ground_truth_path_count {
failure = true;
eprintln!("Number of paths doesn't match for test: {}", test_name);
}
}
if failure {
panic!("Some tests have failed");
}
}
fn render_svg(svg_code: &str) -> DynamicImage {
let opts = Options::default();
let tree = Tree::from_str(svg_code, &opts).unwrap();
let pixmap_size = tree.size();
let (width, height) = (pixmap_size.width() as u32, pixmap_size.height() as u32);
let mut pixmap = resvg::tiny_skia::Pixmap::new(width, height).unwrap();
let mut pixmap_mut = pixmap.as_mut();
render(&tree, Transform::default(), &mut pixmap_mut);
DynamicImage::ImageRgba8(RgbaImage::from_raw(width, height, pixmap.data().to_vec()).unwrap())
}
fn compare_images(img1: &DynamicImage, img2: &DynamicImage, tolerance: u8) -> bool {
assert_eq!(img1.dimensions(), img2.dimensions(), "Image dimensions do not match");
for (x, y, pixel1) in img1.pixels() {
let pixel2 = img2.get_pixel(x, y);
for i in 0..4 {
let difference = (pixel1[i] as i32 - pixel2[i] as i32).unsigned_abs() as u8;
if difference > tolerance {
println!("Difference {} larger than tolerance {} at [{}, {}], channel {}.", difference, tolerance, x, y, i);
return true;
}
assert!(
difference <= tolerance,
"Difference {} larger than tolerance {} at [{}, {}], channel {}.",
difference,
tolerance,
x,
y,
i
);
}
}
false
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/util/epsilons.rs | libraries/path-bool/src/util/epsilons.rs | #[derive(Clone, Copy, Debug)]
pub struct Epsilons {
pub point: f64,
pub linear: f64,
pub param: f64,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/util/aabb.rs | libraries/path-bool/src/util/aabb.rs | use glam::{BVec2, DVec2};
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Aabb {
min: DVec2,
max: DVec2,
}
impl Default for Aabb {
fn default() -> Self {
Self {
min: DVec2::INFINITY,
max: DVec2::NEG_INFINITY,
}
}
}
impl Aabb {
#[inline]
pub(crate) fn min(&self) -> DVec2 {
self.min
}
#[inline]
pub(crate) fn max(&self) -> DVec2 {
self.max
}
pub(crate) const fn new(left: f64, top: f64, right: f64, bottom: f64) -> Self {
Aabb {
min: DVec2::new(left, top),
max: DVec2::new(right, bottom),
}
}
#[inline]
pub(crate) fn top(&self) -> f64 {
self.min.y
}
#[inline]
pub(crate) fn left(&self) -> f64 {
self.min.x
}
#[inline]
pub(crate) fn right(&self) -> f64 {
self.max.x
}
#[inline]
pub(crate) fn bottom(&self) -> f64 {
self.max.y
}
}
#[inline]
pub(crate) fn bounding_boxes_overlap(a: &Aabb, b: &Aabb) -> bool {
(a.min.cmple(b.max) & b.min.cmple(a.max)) == BVec2::TRUE
}
#[inline]
pub(crate) fn merge_bounding_boxes(a: &Aabb, b: &Aabb) -> Aabb {
Aabb {
min: a.min.min(b.min),
max: a.max.max(b.max),
}
}
#[inline]
pub(crate) fn extend_bounding_box(bounding_box: Option<Aabb>, point: DVec2) -> Aabb {
match bounding_box {
Some(bb) => Aabb {
min: bb.min.min(point),
max: bb.max.max(point),
},
None => Aabb { min: point, max: point },
}
}
pub(crate) fn bounding_box_max_extent(bounding_box: &Aabb) -> f64 {
(bounding_box.max - bounding_box.min).max_element()
}
pub(crate) fn bounding_box_around_point(point: DVec2, padding: f64) -> Aabb {
Aabb {
min: point - DVec2::splat(padding),
max: point + DVec2::splat(padding),
}
}
pub(crate) fn expand_bounding_box(bounding_box: &Aabb, padding: f64) -> Aabb {
Aabb {
min: bounding_box.min - DVec2::splat(padding),
max: bounding_box.max + DVec2::splat(padding),
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/util/math.rs | libraries/path-bool/src/util/math.rs | use glam::{DVec2, FloatExt};
pub use std::f64::consts::PI;
pub fn lin_map(value: f64, in_min: f64, in_max: f64, out_min: f64, out_max: f64) -> f64 {
((value - in_min) / (in_max - in_min)) * (out_max - out_min) + out_min
}
pub fn lerp(a: f64, b: f64, t: f64) -> f64 {
a.lerp(b, t)
}
pub fn vector_angle(u: DVec2, v: DVec2) -> f64 {
const EPS: f64 = 1e-12;
let sign = u.x * v.y - u.y * v.x;
if sign.abs() < EPS && (u + v).length_squared() < EPS * EPS {
// TODO: `u` can be scaled
return PI;
}
sign.signum() * (u.dot(v) / (u.length() * v.length())).acos()
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/util/grid.rs | libraries/path-bool/src/util/grid.rs | use crate::aabb::Aabb;
use glam::{DVec2, IVec2};
use rustc_hash::FxHashMap;
use smallvec::SmallVec;
pub(crate) struct Grid {
cell_factor: f64,
cells: FxHashMap<IVec2, SmallVec<[usize; 6]>>,
}
impl Grid {
pub(crate) fn new(cell_size: f64, edges: usize) -> Self {
Grid {
cell_factor: cell_size.recip(),
cells: FxHashMap::with_capacity_and_hasher(edges, Default::default()),
}
}
pub(crate) fn insert(&mut self, bbox: &Aabb, index: usize) {
let min_cell = self.point_to_cell_floor(bbox.min());
let max_cell = self.point_to_cell_ceil(bbox.max());
for i in min_cell.x..=max_cell.x {
for j in min_cell.y..=max_cell.y {
self.cells.entry((i, j).into()).or_default().push(index);
}
}
}
pub(crate) fn query(&self, bbox: &Aabb, result: &mut BitVec) {
let min_cell = self.point_to_cell_floor(bbox.min());
let max_cell = self.point_to_cell_ceil(bbox.max());
for i in min_cell.x..=max_cell.x {
for j in min_cell.y..=max_cell.y {
if let Some(indices) = self.cells.get(&(i, j).into()) {
for &index in indices {
result.set(index);
}
}
}
}
// result.sort_unstable();
// result.dedup();
}
fn point_to_cell_ceil(&self, point: DVec2) -> IVec2 {
(point * self.cell_factor).ceil().as_ivec2()
}
fn point_to_cell_floor(&self, point: DVec2) -> IVec2 {
(point * self.cell_factor).floor().as_ivec2()
}
}
pub struct BitVec {
data: Vec<u64>,
}
impl BitVec {
pub fn new(capacity: usize) -> Self {
let num_words = capacity.div_ceil(64);
BitVec { data: vec![0; num_words] }
}
pub fn set(&mut self, index: usize) {
let word_index = index / 64;
let bit_index = index % 64;
self.data[word_index] |= 1u64 << bit_index;
}
pub fn clear(&mut self) {
self.data.fill(0);
}
pub fn iter_set_bits(&self) -> BitVecIterator<'_> {
BitVecIterator {
bit_vec: self,
current_word: self.data[0],
word_index: 0,
}
}
}
pub struct BitVecIterator<'a> {
bit_vec: &'a BitVec,
current_word: u64,
word_index: usize,
}
impl<'a> Iterator for BitVecIterator<'a> {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
loop {
if self.current_word == 0 {
self.word_index += 1;
if self.word_index == self.bit_vec.data.len() {
return None;
}
self.current_word = self.bit_vec.data[self.word_index];
continue;
}
let tz = self.current_word.trailing_zeros() as usize;
self.current_word ^= 1 << tz;
let result = self.word_index * 64 + tz;
return Some(result);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bitvec() {
let mut bv = BitVec::new(200);
bv.set(5);
bv.set(64);
bv.set(128);
bv.set(199);
let set_bits: Vec<usize> = bv.iter_set_bits().collect();
assert_eq!(set_bits, vec![5, 64, 128, 199]);
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/parsing/path_command.rs | libraries/path-bool/src/parsing/path_command.rs | use glam::DVec2;
#[derive(Clone, Debug)]
pub enum AbsolutePathCommand {
H(f64),
V(f64),
M(DVec2),
L(DVec2),
C(DVec2, DVec2, DVec2),
S(DVec2, DVec2),
Q(DVec2, DVec2),
T(DVec2),
A(f64, f64, f64, bool, bool, DVec2),
Z,
}
#[derive(Clone, Debug)]
pub enum RelativePathCommand {
H(f64),
V(f64),
M(f64, f64),
L(f64, f64),
C(f64, f64, f64, f64, f64, f64),
S(f64, f64, f64, f64),
Q(f64, f64, f64, f64),
T(f64, f64),
A(f64, f64, f64, bool, bool, f64, f64),
}
#[derive(Clone, Debug)]
pub enum PathCommand {
Absolute(AbsolutePathCommand),
Relative(RelativePathCommand),
}
pub fn to_absolute_commands<I>(commands: I) -> impl Iterator<Item = AbsolutePathCommand>
where
I: IntoIterator<Item = PathCommand>,
{
let mut last_point = DVec2::ZERO;
let mut first_point = last_point;
commands.into_iter().flat_map(move |cmd| match cmd {
PathCommand::Absolute(abs_cmd) => {
match abs_cmd {
AbsolutePathCommand::H(x) => {
last_point.x = x;
}
AbsolutePathCommand::V(y) => {
last_point.y = y;
}
AbsolutePathCommand::M(point) => {
last_point = point;
first_point = point;
}
AbsolutePathCommand::L(point) => {
last_point = point;
}
AbsolutePathCommand::C(_, _, end) => {
last_point = end;
}
AbsolutePathCommand::S(_, end) => {
last_point = end;
}
AbsolutePathCommand::Q(_, end) => {
last_point = end;
}
AbsolutePathCommand::T(end) => {
last_point = end;
}
AbsolutePathCommand::A(_, _, _, _, _, end) => {
last_point = end;
}
AbsolutePathCommand::Z => {
last_point = first_point;
}
}
vec![abs_cmd]
}
PathCommand::Relative(rel_cmd) => match rel_cmd {
RelativePathCommand::H(dx) => {
last_point.x += dx;
vec![AbsolutePathCommand::L(last_point)]
}
RelativePathCommand::V(dy) => {
last_point.y += dy;
vec![AbsolutePathCommand::L(last_point)]
}
RelativePathCommand::M(dx, dy) => {
last_point += DVec2::new(dx, dy);
first_point = last_point;
vec![AbsolutePathCommand::M(last_point)]
}
RelativePathCommand::L(dx, dy) => {
last_point += DVec2::new(dx, dy);
vec![AbsolutePathCommand::L(last_point)]
}
RelativePathCommand::C(dx1, dy1, dx2, dy2, dx, dy) => {
let c1 = last_point + DVec2::new(dx1, dy1);
let c2 = last_point + DVec2::new(dx2, dy2);
last_point += DVec2::new(dx, dy);
vec![AbsolutePathCommand::C(c1, c2, last_point)]
}
RelativePathCommand::S(dx2, dy2, dx, dy) => {
let c2 = last_point + DVec2::new(dx2, dy2);
last_point += DVec2::new(dx, dy);
vec![AbsolutePathCommand::S(c2, last_point)]
}
RelativePathCommand::Q(dx1, dy1, dx, dy) => {
let control = last_point + DVec2::new(dx1, dy1);
last_point += DVec2::new(dx, dy);
vec![AbsolutePathCommand::Q(control, last_point)]
}
RelativePathCommand::T(dx, dy) => {
last_point += DVec2::new(dx, dy);
vec![AbsolutePathCommand::T(last_point)]
}
RelativePathCommand::A(rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, dx, dy) => {
last_point += DVec2::new(dx, dy);
vec![AbsolutePathCommand::A(rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, last_point)]
}
},
})
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/parsing/path_data.rs | libraries/path-bool/src/parsing/path_data.rs | use crate::BooleanError;
use crate::path::{Path, path_from_commands, path_to_commands};
use crate::path_command::{AbsolutePathCommand, PathCommand, RelativePathCommand};
use glam::DVec2;
use regex::Regex;
pub fn commands_from_path_data(d: &str) -> Result<Vec<PathCommand>, BooleanError> {
let re_float = Regex::new(r"^\s*,?\s*(-?\d*(?:\d\.|\.\d|\d)\d*(?:[eE][+\-]?\d+)?)").unwrap();
let re_cmd = Regex::new(r"^\s*([MLCSQTAZHVmlhvcsqtaz])").unwrap();
let re_bool = Regex::new(r"^\s*,?\s*([01])").unwrap();
let mut i = 0;
let mut last_cmd = 'M';
let mut commands = Vec::new();
let get_cmd = |i: &mut usize, last_cmd: char| -> Option<char> {
if *i >= d.len() - 1.min(d.len()) {
return None;
}
if let Some(cap) = re_cmd.captures(&d[*i..]) {
*i += cap[0].len();
Some(cap[1].chars().next().unwrap())
} else {
match last_cmd {
'M' => Some('L'),
'm' => Some('l'),
'z' | 'Z' => None,
_ => Some(last_cmd),
}
}
};
let get_float = |i: &mut usize| -> f64 {
if let Some(cap) = re_float.captures(&d[*i..]) {
*i += cap[0].len();
cap[1].parse().unwrap()
} else {
panic!("Invalid path data. Expected a number at index {}, got {}", i, &d[*i..]);
}
};
let get_bool = |i: &mut usize| -> bool {
if let Some(cap) = re_bool.captures(&d[*i..]) {
*i += cap[0].len();
&cap[1] == "1"
} else {
panic!("Invalid path data. Expected a flag at index {i}");
}
};
while let Some(cmd) = get_cmd(&mut i, last_cmd) {
last_cmd = cmd;
match cmd {
'M' => commands.push(PathCommand::Absolute(AbsolutePathCommand::M(DVec2::new(get_float(&mut i), get_float(&mut i))))),
'L' => commands.push(PathCommand::Absolute(AbsolutePathCommand::L(DVec2::new(get_float(&mut i), get_float(&mut i))))),
'C' => commands.push(PathCommand::Absolute(AbsolutePathCommand::C(
DVec2::new(get_float(&mut i), get_float(&mut i)),
DVec2::new(get_float(&mut i), get_float(&mut i)),
DVec2::new(get_float(&mut i), get_float(&mut i)),
))),
'S' => commands.push(PathCommand::Absolute(AbsolutePathCommand::S(
DVec2::new(get_float(&mut i), get_float(&mut i)),
DVec2::new(get_float(&mut i), get_float(&mut i)),
))),
'Q' => commands.push(PathCommand::Absolute(AbsolutePathCommand::Q(
DVec2::new(get_float(&mut i), get_float(&mut i)),
DVec2::new(get_float(&mut i), get_float(&mut i)),
))),
'T' => commands.push(PathCommand::Absolute(AbsolutePathCommand::T(DVec2::new(get_float(&mut i), get_float(&mut i))))),
'A' => commands.push(PathCommand::Absolute(AbsolutePathCommand::A(
get_float(&mut i),
get_float(&mut i),
get_float(&mut i),
get_bool(&mut i),
get_bool(&mut i),
DVec2::new(get_float(&mut i), get_float(&mut i)),
))),
'Z' | 'z' => commands.push(PathCommand::Absolute(AbsolutePathCommand::Z)),
'H' => commands.push(PathCommand::Absolute(AbsolutePathCommand::H(get_float(&mut i)))),
'V' => commands.push(PathCommand::Absolute(AbsolutePathCommand::V(get_float(&mut i)))),
'm' => commands.push(PathCommand::Relative(RelativePathCommand::M(get_float(&mut i), get_float(&mut i)))),
'l' => commands.push(PathCommand::Relative(RelativePathCommand::L(get_float(&mut i), get_float(&mut i)))),
'h' => commands.push(PathCommand::Relative(RelativePathCommand::H(get_float(&mut i)))),
'v' => commands.push(PathCommand::Relative(RelativePathCommand::V(get_float(&mut i)))),
'c' => commands.push(PathCommand::Relative(RelativePathCommand::C(
get_float(&mut i),
get_float(&mut i),
get_float(&mut i),
get_float(&mut i),
get_float(&mut i),
get_float(&mut i),
))),
's' => commands.push(PathCommand::Relative(RelativePathCommand::S(
get_float(&mut i),
get_float(&mut i),
get_float(&mut i),
get_float(&mut i),
))),
'q' => commands.push(PathCommand::Relative(RelativePathCommand::Q(
get_float(&mut i),
get_float(&mut i),
get_float(&mut i),
get_float(&mut i),
))),
't' => commands.push(PathCommand::Relative(RelativePathCommand::T(get_float(&mut i), get_float(&mut i)))),
'a' => commands.push(PathCommand::Relative(RelativePathCommand::A(
get_float(&mut i),
get_float(&mut i),
get_float(&mut i),
get_bool(&mut i),
get_bool(&mut i),
get_float(&mut i),
get_float(&mut i),
))),
_ => return Err(BooleanError::InvalidPathCommand(cmd)),
}
}
Ok(commands)
}
pub fn path_from_path_data(d: &str) -> Result<Path, BooleanError> {
Ok(path_from_commands(commands_from_path_data(d)?).collect())
}
pub fn path_to_path_data(path: &Path, eps: f64) -> String {
path_to_commands(path.iter(), eps)
.map(|cmd| match cmd {
PathCommand::Absolute(abs_cmd) => match abs_cmd {
AbsolutePathCommand::H(dx) => format!("H {dx:.12}"),
AbsolutePathCommand::V(dy) => format!("V {dy:.12}"),
AbsolutePathCommand::M(p) => format!("M {:.12},{:.12}", p.x, p.y),
AbsolutePathCommand::L(p) => format!("L {:.12},{:.12}", p.x, p.y),
AbsolutePathCommand::C(p1, p2, p3) => format!("C {:.12},{:.12} {:.12},{:.12} {:.12},{:.12}", p1.x, p1.y, p2.x, p2.y, p3.x, p3.y),
AbsolutePathCommand::S(p1, p2) => {
format!("S {:.12},{:.12} {:.12},{:.12}", p1.x, p1.y, p2.x, p2.y)
}
AbsolutePathCommand::Q(p1, p2) => {
format!("Q {:.12},{:.12} {:.12},{:.12}", p1.x, p1.y, p2.x, p2.y)
}
AbsolutePathCommand::T(p) => format!("T {:.12},{:.12}", p.x, p.y),
AbsolutePathCommand::A(rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, p) => {
format!("A {:.12} {:.12} {:.12} {} {} {:.12},{:.12}", rx, ry, x_axis_rotation, large_arc_flag as u8, sweep_flag as u8, p.x, p.y)
}
AbsolutePathCommand::Z => "Z".to_string(),
},
PathCommand::Relative(rel_cmd) => match rel_cmd {
RelativePathCommand::M(dx, dy) => format!("m {dx:.12},{dy:.12}"),
RelativePathCommand::L(dx, dy) => format!("l {dx:.12},{dy:.12}"),
RelativePathCommand::H(dx) => format!("h {dx:.12}"),
RelativePathCommand::V(dy) => format!("v {dy:.12}"),
RelativePathCommand::C(dx1, dy1, dx2, dy2, dx, dy) => format!("c{dx1:.12},{dy1:.12} {dx2:.12},{dy2:.12} {dx:.12},{dy:.12}"),
RelativePathCommand::S(dx2, dy2, dx, dy) => {
format!("s {dx2:.12},{dy2:.12} {dx:.12},{dy:.12}")
}
RelativePathCommand::Q(dx1, dy1, dx, dy) => {
format!("q {dx1:.12},{dy1:.12} {dx:.12},{dy:.12}")
}
RelativePathCommand::T(dx, dy) => format!("t{dx:.12},{dy:.12}"),
RelativePathCommand::A(rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, dx, dy) => {
format!("a {:.12} {:.12} {:.12} {} {} {:.12},{:.12}", rx, ry, x_axis_rotation, large_arc_flag as u8, sweep_flag as u8, dx, dy)
}
},
})
.collect::<Vec<String>>()
.join(" ")
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/path/line_segment_aabb.rs | libraries/path-bool/src/path/line_segment_aabb.rs | use crate::aabb::Aabb;
use crate::line_segment::LineSegment;
const INSIDE: u8 = 0;
const LEFT: u8 = 1;
const RIGHT: u8 = 1 << 1;
const BOTTOM: u8 = 1 << 2;
const TOP: u8 = 1 << 3;
fn out_code(x: f64, y: f64, bounding_box: &Aabb) -> u8 {
let mut code = INSIDE;
if x < bounding_box.left() {
code |= LEFT;
} else if x > bounding_box.right() {
code |= RIGHT;
}
if y < bounding_box.top() {
code |= BOTTOM;
} else if y > bounding_box.bottom() {
code |= TOP;
}
code
}
pub(crate) fn line_segment_aabb_intersect(seg: LineSegment, bounding_box: &Aabb) -> bool {
let [mut p0, mut p1] = seg;
let mut outcode0 = out_code(p0.x, p0.y, bounding_box);
let mut outcode1 = out_code(p1.x, p1.y, bounding_box);
loop {
if (outcode0 | outcode1) == 0 {
// bitwise OR is 0: both points inside window; trivially accept and exit loop
return true;
} else if (outcode0 & outcode1) != 0 {
// bitwise AND is not 0: both points share an outside zone (LEFT, RIGHT, TOP,
// or BOTTOM), so both must be outside window; exit loop (accept is false)
return false;
} else {
// failed both tests, so calculate the line segment to clip
// from an outside point to an intersection with clip edge
let mut x = 0.;
let mut y = 0.;
// At least one endpoint is outside the clip rectangle; pick it.
let outcode_out = if outcode1 > outcode0 { outcode1 } else { outcode0 };
// Now find the intersection point;
// use formulas:
// slope = (y1 - y0) / (x1 - x0)
// x = x0 + (1 / slope) * (ym - y0), where ym is ymin or ymax
// y = y0 + slope * (xm - x0), where xm is xmin or xmax
// No need to worry about divide-by-zero because, in each case, the
// outcode bit being tested guarantees the denominator is non-zero
if (outcode_out & TOP) != 0 {
// point is above the clip window
x = p0.x + (p1.x - p0.x) * (bounding_box.bottom() - p0.y) / (p1.y - p0.y);
y = bounding_box.bottom();
} else if (outcode_out & BOTTOM) != 0 {
// point is below the clip window
x = p0.x + (p1.x - p0.x) * (bounding_box.top() - p0.y) / (p1.y - p0.y);
y = bounding_box.top();
} else if (outcode_out & RIGHT) != 0 {
// point is to the right of clip window
y = p0.y + (p1.y - p0.y) * (bounding_box.right() - p0.x) / (p1.x - p0.x);
x = bounding_box.right();
} else if (outcode_out & LEFT) != 0 {
// point is to the left of clip window
y = p0.y + (p1.y - p0.y) * (bounding_box.left() - p0.x) / (p1.x - p0.x);
x = bounding_box.left();
}
// Now we move outside point to intersection point to clip
// and get ready for next pass.
if outcode_out == outcode0 {
p0.x = x;
p0.y = y;
outcode0 = out_code(p0.x, p0.y, bounding_box);
} else {
p1.x = x;
p1.y = y;
outcode1 = out_code(p1.x, p1.y, bounding_box);
}
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/path/path_segment.rs | libraries/path-bool/src/path/path_segment.rs | //! Defines the `PathSegment` enum and related functionality for representing and
//! manipulating path segments in 2D space.
//!
//! This module provides implementations for various types of path segments including
//! lines, cubic and quadratic Bézier curves, and elliptical arcs. It also includes
//! utility functions for operations such as bounding box calculation, segment splitting,
//! and arc-to-cubic conversion.
//!
//! The implementations in this module closely follow the SVG path specification,
//! making it suitable for use in vector graphics applications.
use crate::EPS;
use crate::aabb::{Aabb, bounding_box_around_point, expand_bounding_box, extend_bounding_box, merge_bounding_boxes};
use crate::math::{lerp, vector_angle};
use glam::{DMat2, DMat3, DVec2};
use std::f64::consts::{PI, TAU};
/// Represents a segment of a path in a 2D space, based on the SVG path specification.
///
/// This enum closely follows the path segment types defined in the SVG 2 specification.
/// For more details, see: <https://www.w3.org/TR/SVG2/paths.html>
///
/// Each variant of this enum corresponds to a different type of path segment:
/// - Line: A straight line between two points.
/// - Cubic: A cubic Bézier curve.
/// - Quadratic: A quadratic Bézier curve.
/// - Arc: An elliptical arc.
///
/// # Examples
///
/// Creating a line segment:
/// ```
/// use path_bool::PathSegment;
/// use glam::DVec2;
///
/// let line = PathSegment::Line(DVec2::new(0., 0.), DVec2::new(1., 1.));
/// ```
///
/// Creating a cubic Bézier curve:
/// ```
/// use path_bool::PathSegment;
/// use glam::DVec2;
///
/// let cubic = PathSegment::Cubic(
/// DVec2::new(0., 0.),
/// DVec2::new(1., 0.),
/// DVec2::new(1., 1.),
/// DVec2::new(2., 1.)
/// );
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PathSegment {
/// A line segment from the first point to the second.
/// Corresponds to the SVG "L" command.
Line(DVec2, DVec2),
/// A cubic Bézier curve with start point, two control points, and end point.
/// Corresponds to the SVG "C" command.
Cubic(DVec2, DVec2, DVec2, DVec2),
/// A quadratic Bézier curve with start point, control point, and end point.
/// Corresponds to the SVG "Q" command.
Quadratic(DVec2, DVec2, DVec2),
/// An elliptical arc.
/// Corresponds to the SVG "A" command.
///
/// Parameters:
/// - Start point
/// - X-axis radius
/// - Y-axis radius
/// - X-axis rotation (in radians)
/// - Large arc flag (true if the arc should be greater than or equal to 180 degrees)
/// - Sweep flag (true if the arc should be drawn in a "positive-angle" direction)
/// - End point
Arc(DVec2, f64, f64, f64, bool, bool, DVec2),
}
impl PathSegment {
/// Calculates the angle of the tangent at the start point of the segment.
///
/// This method computes the angle (in radians) of the tangent vector at the
/// beginning of the path segment. The angle is measured clockwise
/// from the positive x-axis.
///
/// # Returns
///
/// A float representing the angle in radians, normalized to the range [0, 2π).
///
/// # Examples
///
/// ```
/// use path_bool::PathSegment;
/// use glam::DVec2;
/// use std::f64::consts::{TAU, FRAC_PI_4};
///
/// let line = PathSegment::Line(DVec2::new(0., 0.), DVec2::new(1., 1.));
/// assert_eq!(line.start_angle(), TAU - (FRAC_PI_4));
/// ```
pub fn start_angle(&self) -> f64 {
let angle = match *self {
PathSegment::Line(start, end) => (end - start).angle_to(DVec2::X),
PathSegment::Cubic(start, control1, control2, _) => {
let diff = control1 - start;
if diff.abs_diff_eq(DVec2::ZERO, EPS.point) {
// if this diff were empty too, the segments would have been converted to a line
(control2 - start).angle_to(DVec2::X)
} else {
diff.angle_to(DVec2::X)
}
}
// Apply same logic as for cubic bezier
PathSegment::Quadratic(start, control, _) => (control - start).to_angle(),
PathSegment::Arc(..) => self.arc_segment_to_cubics(0.001)[0].start_angle(),
};
use std::f64::consts::TAU;
(angle + TAU) % TAU
}
/// Computes the curvature at the start point of the segment.
///
/// The curvature is a measure of how sharply a curve bends. A straight line
/// has a curvature of 0, while a tight curve has a higher curvature value.
///
/// # Returns
///
/// A float representing the curvature. Positive values indicate a left
/// curve, while negative values indicate a right curve.
///
/// # Examples
///
/// ```
/// use path_bool::PathSegment;
/// use glam::DVec2;
///
/// let line = PathSegment::Line(DVec2::new(0., 0.), DVec2::new(1., 1.));
/// assert_eq!(line.start_curvature(), 0.);
///
/// let curve = PathSegment::Cubic(
/// DVec2::new(0., 0.),
/// DVec2::new(0., 1.),
/// DVec2::new(1., 1.),
/// DVec2::new(1., 0.)
/// );
/// assert!(curve.start_curvature() < 0.);
/// ```
pub fn start_curvature(&self) -> f64 {
match *self {
PathSegment::Line(_, _) => 0.,
PathSegment::Cubic(start, control1, control2, _) => {
let a = control1 - start;
let a = 3. * a;
let b = start - 2. * control1 + control2;
let b = 6. * b;
let numerator = a.x * b.y - a.y * b.x;
let denominator = a.length_squared() * a.length();
if denominator == 0. { 0. } else { numerator / denominator }
}
PathSegment::Quadratic(start, control, end) => {
// First derivative
let a = 2. * (control - start);
// Second derivative
let b = 2. * (start - 2. * control + end);
let numerator = a.x * b.y - a.y * b.x;
let denominator = a.length_squared() * a.length();
if denominator == 0. { 0. } else { numerator / denominator }
}
PathSegment::Arc(..) => self.arc_segment_to_cubics(0.001)[0].start_curvature(),
}
}
/// Converts the segment to a cubic Bézier curve representation.
///
/// This method provides a uniform representation of all segment types as
/// cubic Bézier curves. For segments that are not naturally cubic Bézier
/// curves (like lines or quadratic Bézier curves), an equivalent cubic
/// Bézier representation is computed.
///
/// # Returns
///
/// An array of four `DVec2` points representing the cubic Bézier curve:
/// [start point, first control point, second control point, end point]
///
/// # Examples
///
/// ```
/// use path_bool::PathSegment;
/// use glam::DVec2;
///
/// let line = PathSegment::Line(DVec2::new(0., 0.), DVec2::new(1., 1.));
/// let cubic = line.to_cubic();
/// assert_eq!(cubic[0], DVec2::new(0., 0.));
/// assert_eq!(cubic[3], DVec2::new(1., 1.));
/// ```
///
/// # Panics
///
/// This method is not implemented for `PathSegment::Arc`. Attempting to call
/// `to_cubic()` on an `Arc` segment will result in a panic.
pub fn to_cubic(&self) -> [DVec2; 4] {
match *self {
PathSegment::Line(start, end) => [start, start, end, end],
PathSegment::Cubic(s, c1, c2, e) => [s, c1, c2, e],
PathSegment::Quadratic(start, control, end) => {
// C0 = Q0
// C1 = Q0 + (2/3) (Q1 - Q0)
// C2 = Q2 + (2/3) (Q1 - Q2)
// C3 = Q2
let d1 = control - start;
let d2 = control - end;
[start, start + (2. / 3.) * d1, end + (2. / 3.) * d2, end]
}
PathSegment::Arc(..) => unimplemented!(),
}
}
#[must_use]
/// Retrieves the start point of a path segment.
pub fn start(&self) -> DVec2 {
match self {
PathSegment::Line(start, _) => *start,
PathSegment::Cubic(start, _, _, _) => *start,
PathSegment::Quadratic(start, _, _) => *start,
PathSegment::Arc(start, _, _, _, _, _, _) => *start,
}
}
#[must_use]
/// Retrieves the end point of a path segment.
pub fn end(&self) -> DVec2 {
match self {
PathSegment::Line(_, end) => *end,
PathSegment::Cubic(_, _, _, end) => *end,
PathSegment::Quadratic(_, _, end) => *end,
PathSegment::Arc(_, _, _, _, _, _, end) => *end,
}
}
#[must_use]
/// Reverses the direction of the path segment.
///
/// This method creates a new `PathSegment` that represents the same geometric shape
/// but in the opposite direction.
///
/// # Examples
///
/// ```
/// use path_bool::PathSegment;
/// use glam::DVec2;
///
/// let line = PathSegment::Line(DVec2::new(0., 0.), DVec2::new(1., 1.));
/// let reversed = line.reverse();
/// assert_eq!(reversed.start(), DVec2::new(1., 1.));
/// assert_eq!(reversed.end(), DVec2::new(0., 0.));
/// ```
pub fn reverse(&self) -> PathSegment {
match *self {
PathSegment::Line(start, end) => PathSegment::Line(end, start),
PathSegment::Cubic(p1, p2, p3, p4) => PathSegment::Cubic(p4, p3, p2, p1),
PathSegment::Quadratic(p1, p2, p3) => PathSegment::Quadratic(p3, p2, p1),
PathSegment::Arc(start, rx, ry, phi, fa, fs, end) => PathSegment::Arc(end, rx, ry, phi, fa, !fs, start),
}
}
#[must_use]
/// Converts an arc segment to its center parameterization.
///
/// This method is only meaningful for `Arc` segments. For other segment types,
/// it returns `None`.
///
/// # Returns
///
/// An `Option` containing `PathArcSegmentCenterParametrization` if the segment
/// is an `Arc`, or `None` otherwise.
pub fn arc_segment_to_center(&self) -> Option<PathArcSegmentCenterParametrization> {
if let PathSegment::Arc(xy1, rx, ry, phi, fa, fs, xy2) = *self {
if rx == 0. || ry == 0. {
return None;
}
let rotation_matrix = DMat2::from_angle(-phi.to_radians());
let xy1_prime = rotation_matrix * (xy1 - xy2) * 0.5;
let mut rx2 = rx * rx;
let mut ry2 = ry * ry;
let x1_prime2 = xy1_prime.x * xy1_prime.x;
let y1_prime2 = xy1_prime.y * xy1_prime.y;
let mut rx = rx.abs();
let mut ry = ry.abs();
let lambda = x1_prime2 / rx2 + y1_prime2 / ry2 + 1e-12;
if lambda > 1. {
let lambda_sqrt = lambda.sqrt();
rx *= lambda_sqrt;
ry *= lambda_sqrt;
let lambda_abs = lambda.abs();
rx2 *= lambda_abs;
ry2 *= lambda_abs;
}
let sign = if fa == fs { -1. } else { 1. };
let multiplier = ((rx2 * ry2 - rx2 * y1_prime2 - ry2 * x1_prime2) / (rx2 * y1_prime2 + ry2 * x1_prime2)).sqrt();
let cx_prime = sign * multiplier * ((rx * xy1_prime.y) / ry);
let cy_prime = sign * multiplier * ((-ry * xy1_prime.x) / rx);
let cxy = rotation_matrix.transpose() * DVec2::new(cx_prime, cy_prime) + (xy1 + xy2) * 0.5;
let vec1 = DVec2::new((xy1_prime.x - cx_prime) / rx, (xy1_prime.y - cy_prime) / ry);
let theta1 = vector_angle(DVec2::new(1., 0.), vec1);
let mut delta_theta = vector_angle(vec1, DVec2::new((-xy1_prime.x - cx_prime) / rx, (-xy1_prime.y - cy_prime) / ry));
if !fs && delta_theta > 0. {
delta_theta -= TAU;
} else if fs && delta_theta < 0. {
delta_theta += TAU;
}
Some(PathArcSegmentCenterParametrization {
center: cxy,
theta1,
delta_theta,
rx,
ry,
phi,
})
} else {
None
}
}
#[must_use]
/// Samples a point on the path segment at a given parameter value.
///
/// # Arguments
///
/// * `t` - A value between 0. and 1. representing the position along the segment.
///
/// # Examples
///
/// ```
/// use path_bool::PathSegment;
/// use glam::DVec2;
///
/// let line = PathSegment::Line(DVec2::new(0., 0.), DVec2::new(2., 2.));
/// assert_eq!(line.sample_at(0.5), DVec2::new(1., 1.));
/// ```
pub fn sample_at(&self, t: f64) -> DVec2 {
match *self {
PathSegment::Line(start, end) => start.lerp(end, t),
PathSegment::Cubic(p1, p2, p3, p4) => {
let p01 = p1.lerp(p2, t);
let p12 = p2.lerp(p3, t);
let p23 = p3.lerp(p4, t);
let p012 = p01.lerp(p12, t);
let p123 = p12.lerp(p23, t);
p012.lerp(p123, t)
}
PathSegment::Quadratic(p1, p2, p3) => {
let p01 = p1.lerp(p2, t);
let p12 = p2.lerp(p3, t);
p01.lerp(p12, t)
}
PathSegment::Arc(start, rx, ry, phi, _, _, end) => {
if let Some(center_param) = self.arc_segment_to_center() {
let theta = center_param.theta1 + t * center_param.delta_theta;
let p = DVec2::new(rx * theta.cos(), ry * theta.sin());
let rotation_matrix = DMat2::from_angle(phi);
rotation_matrix * p + center_param.center
} else {
start.lerp(end, t)
}
}
}
}
#[must_use]
/// Approximates an arc segment with a series of cubic Bézier curves.
///
/// This method is primarily used for `Arc` segments, converting them into
/// a series of cubic Bézier curves for easier rendering or manipulation.
/// For non-`Arc` segments, it returns a vector containing only the original segment.
///
/// # Arguments
///
/// * `max_delta_theta` - The maximum angle (in radians) that each cubic Bézier
/// curve approximation should span.
///
/// # Returns
///
/// A vector of `PathSegment::Cubic` approximating the original segment.
pub fn arc_segment_to_cubics(&self, max_delta_theta: f64) -> Vec<PathSegment> {
if let PathSegment::Arc(start, rx, ry, phi, _, _, end) = *self {
if let Some(center_param) = self.arc_segment_to_center() {
let count = ((center_param.delta_theta.abs() / max_delta_theta).ceil() as usize).max(1);
let from_unit = DMat3::from_translation(center_param.center) * DMat3::from_angle(phi.to_radians()) * DMat3::from_scale(DVec2::new(rx, ry));
let theta = center_param.delta_theta / count as f64;
let k = (4. / 3.) * (theta / 4.).tan();
let sin_theta = theta.sin();
let cos_theta = theta.cos();
(0..count)
.map(|i| {
let start = DVec2::new(1., 0.);
let control1 = DVec2::new(1., k);
let control2 = DVec2::new(cos_theta + k * sin_theta, sin_theta - k * cos_theta);
let end = DVec2::new(cos_theta, sin_theta);
let matrix = DMat3::from_angle(center_param.theta1 + i as f64 * theta) * from_unit;
let start = (matrix * start.extend(1.)).truncate();
let control1 = (matrix * control1.extend(1.)).truncate();
let control2 = (matrix * control2.extend(1.)).truncate();
let end = (matrix * end.extend(1.)).truncate();
PathSegment::Cubic(start, control1, control2, end)
})
.collect()
} else {
vec![PathSegment::Line(start, end)]
}
} else {
vec![*self]
}
}
}
/// Represents the center parameterization of an elliptical arc.
///
/// This struct is used internally to perform calculations on arc segments.
pub struct PathArcSegmentCenterParametrization {
center: DVec2,
theta1: f64,
delta_theta: f64,
rx: f64,
ry: f64,
phi: f64,
}
/// Converts the center parameterization back to an arc segment.
///
/// # Arguments
///
/// * `start` - Optional start point of the arc. If `None`, the start point is calculated.
/// * `end` - Optional end point of the arc. If `None`, the end point is calculated.
///
/// # Returns
///
/// A `PathSegment::Arc` representing the arc described by this parameterization.
impl PathArcSegmentCenterParametrization {
#[must_use]
pub fn arc_segment_from_center(&self, start: Option<DVec2>, end: Option<DVec2>) -> PathSegment {
let rotation_matrix = DMat2::from_angle(self.phi);
let mut xy1 = rotation_matrix * DVec2::new(self.rx * self.theta1.cos(), self.ry * self.theta1.sin()) + self.center;
let mut xy2 = rotation_matrix * DVec2::new(self.rx * (self.theta1 + self.delta_theta).cos(), self.ry * (self.theta1 + self.delta_theta).sin()) + self.center;
let fa = self.delta_theta.abs() > PI;
let fs = self.delta_theta > 0.;
xy1 = start.unwrap_or(xy1);
xy2 = end.unwrap_or(xy2);
PathSegment::Arc(xy1, self.rx, self.ry, self.phi, fa, fs, xy2)
}
}
/// Evaluates a 1D cubic Bézier curve at a given parameter value.
///
/// # Arguments
///
/// * `p0`, `p1`, `p2`, `p3` - Control points of the cubic Bézier curve.
/// * `t` - Parameter value between 0 and 1.
///
/// # Returns
///
/// The value of the Bézier curve at parameter `t`.
fn eval_cubic_1d(p0: f64, p1: f64, p2: f64, p3: f64, t: f64) -> f64 {
let p01 = lerp(p0, p1, t);
let p12 = lerp(p1, p2, t);
let p23 = lerp(p2, p3, t);
let p012 = lerp(p01, p12, t);
let p123 = lerp(p12, p23, t);
lerp(p012, p123, t)
}
/// Computes the bounding interval of a 1D cubic Bézier curve.
///
/// This function finds the minimum and maximum values of a cubic Bézier curve
/// over the interval [0, 1].
///
/// # Arguments
///
/// * `p0`, `p1`, `p2`, `p3` - Control points of the cubic Bézier curve.
///
/// # Returns
///
/// A tuple `(min, max)` representing the bounding interval.
fn cubic_bounding_interval(p0: f64, p1: f64, p2: f64, p3: f64) -> (f64, f64) {
let mut min = p0.min(p3);
let mut max = p0.max(p3);
let a = 3. * (-p0 + 3. * p1 - 3. * p2 + p3);
let b = 6. * (p0 - 2. * p1 + p2);
let c = 3. * (p1 - p0);
let d = b * b - 4. * a * c;
if d < 0. || a == 0. {
// TODO: if a=0, solve linear
return (min, max);
}
let sqrt_d = d.sqrt();
let t0 = (-b - sqrt_d) / (2. * a);
if 0. < t0 && t0 < 1. {
let x0 = eval_cubic_1d(p0, p1, p2, p3, t0);
min = min.min(x0);
max = max.max(x0);
}
let t1 = (-b + sqrt_d) / (2. * a);
if 0. < t1 && t1 < 1. {
let x1 = eval_cubic_1d(p0, p1, p2, p3, t1);
min = min.min(x1);
max = max.max(x1);
}
(min, max)
}
/// Evaluates a 1D quadratic Bézier curve at a given parameter value.
///
/// # Arguments
///
/// * `p0`, `p1`, `p2` - Control points of the quadratic Bézier curve.
/// * `t` - Parameter value between 0 and 1.
///
/// # Returns
///
/// The value of the Bézier curve at parameter `t`.
fn eval_quadratic_1d(p0: f64, p1: f64, p2: f64, t: f64) -> f64 {
let p01 = lerp(p0, p1, t);
let p12 = lerp(p1, p2, t);
lerp(p01, p12, t)
}
/// Computes the bounding interval of a 1D quadratic Bézier curve.
///
/// This function finds the minimum and maximum values of a quadratic Bézier curve
/// over the interval [0, 1].
///
/// # Arguments
///
/// * `p0`, `p1`, `p2` - Control points of the quadratic Bézier curve.
///
/// # Returns
///
/// A tuple `(min, max)` representing the bounding interval.
fn quadratic_bounding_interval(p0: f64, p1: f64, p2: f64) -> (f64, f64) {
let mut min = p0.min(p2);
let mut max = p0.max(p2);
let denominator = p0 - 2. * p1 + p2;
if denominator == 0. {
return (min, max);
}
let t = (p0 - p1) / denominator;
if (0.0..=1.).contains(&t) {
let x = eval_quadratic_1d(p0, p1, p2, t);
min = min.min(x);
max = max.max(x);
}
(min, max)
}
fn in_interval(x: f64, x0: f64, x1: f64) -> bool {
(x0..=x1).contains(&x)
}
impl PathSegment {
/// Computes the bounding box of the path segment.
///
/// # Returns
///
/// An [`Aabb`] representing the axis-aligned bounding box of the segment.
pub(crate) fn bounding_box(&self) -> Aabb {
match *self {
PathSegment::Line(start, end) => Aabb::new(start.x.min(end.x), start.y.min(end.y), start.x.max(end.x), start.y.max(end.y)),
PathSegment::Cubic(p1, p2, p3, p4) => {
let (left, right) = cubic_bounding_interval(p1.x, p2.x, p3.x, p4.x);
let (top, bottom) = cubic_bounding_interval(p1.y, p2.y, p3.y, p4.y);
Aabb::new(left, top, right, bottom)
}
PathSegment::Quadratic(p1, p2, p3) => {
let (left, right) = quadratic_bounding_interval(p1.x, p2.x, p3.x);
let (top, bottom) = quadratic_bounding_interval(p1.y, p2.y, p3.y);
Aabb::new(left, top, right, bottom)
}
PathSegment::Arc(start, rx, ry, phi, _, _, end) => {
if let Some(center_param) = self.arc_segment_to_center() {
let theta2 = center_param.theta1 + center_param.delta_theta;
let mut bounding_box = extend_bounding_box(Some(bounding_box_around_point(start, 0.)), end);
if phi == 0. || rx == ry {
// TODO: Fix the fact that the following gives false positives, resulting in larger boxes
if in_interval(-PI, center_param.theta1, theta2) || in_interval(PI, center_param.theta1, theta2) {
bounding_box = extend_bounding_box(Some(bounding_box), DVec2::new(center_param.center.x - rx, center_param.center.y));
}
if in_interval(-PI / 2., center_param.theta1, theta2) || in_interval(3. * PI / 2., center_param.theta1, theta2) {
bounding_box = extend_bounding_box(Some(bounding_box), DVec2::new(center_param.center.x, center_param.center.y - ry));
}
if in_interval(0., center_param.theta1, theta2) || in_interval(2. * PI, center_param.theta1, theta2) {
bounding_box = extend_bounding_box(Some(bounding_box), DVec2::new(center_param.center.x + rx, center_param.center.y));
}
if in_interval(PI / 2., center_param.theta1, theta2) || in_interval(5. * PI / 2., center_param.theta1, theta2) {
bounding_box = extend_bounding_box(Some(bounding_box), DVec2::new(center_param.center.x, center_param.center.y + ry));
}
expand_bounding_box(&bounding_box, 1e-11) // TODO: Get rid of expansion
} else {
// TODO: Don't convert to cubics
let cubics = self.arc_segment_to_cubics(PI / 16.);
let mut bounding_box = bounding_box_around_point(start, 0.);
for cubic_seg in cubics {
bounding_box = merge_bounding_boxes(&bounding_box, &cubic_seg.bounding_box());
}
bounding_box
}
} else {
extend_bounding_box(Some(bounding_box_around_point(start, 0.)), end)
}
}
}
}
/// Computes a loose bounding box that surrounds all anchors, but also the handles of cubic and quadratic segments.
/// This will usually be larger than the actual bounding box, but is faster to compute because it does not have to find where each curve reaches its maximum and minimum.
pub(crate) fn approx_bounding_box(&self) -> Aabb {
match *self {
PathSegment::Cubic(p1, p2, p3, p4) => {
// Use the control points to create a bounding box
let left = p1.x.min(p2.x).min(p3.x).min(p4.x);
let right = p1.x.max(p2.x).max(p3.x).max(p4.x);
let top = p1.y.min(p2.y).min(p3.y).min(p4.y);
let bottom = p1.y.max(p2.y).max(p3.y).max(p4.y);
Aabb::new(left, top, right, bottom)
}
PathSegment::Quadratic(p1, p2, p3) => {
// Use the control points to create a bounding box
let left = p1.x.min(p2.x).min(p3.x);
let right = p1.x.max(p2.x).max(p3.x);
let top = p1.y.min(p2.y).min(p3.y);
let bottom = p1.y.max(p2.y).max(p3.y);
Aabb::new(left, top, right, bottom)
}
seg => seg.bounding_box(),
}
}
/// Splits the path segment at a given parameter value.
///
/// # Arguments
///
/// * `t` - A value between 0. and 1. representing the split point along the segment.
///
/// # Returns
///
/// A tuple of two `PathSegment`s representing the parts before and after the split point.
///
/// # Examples
///
/// ```
/// use path_bool::PathSegment;
/// use glam::DVec2;
///
/// let line = PathSegment::Line(DVec2::new(0., 0.), DVec2::new(2., 2.));
/// let (first_half, second_half) = line.split_at(0.5);
/// assert_eq!(first_half.end(), DVec2::new(1., 1.));
/// assert_eq!(second_half.start(), DVec2::new(1., 1.));
/// ```
pub fn split_at(&self, t: f64) -> (PathSegment, PathSegment) {
match *self {
PathSegment::Line(start, end) => {
let p = start.lerp(end, t);
(PathSegment::Line(start, p), PathSegment::Line(p, end))
}
PathSegment::Cubic(p0, p1, p2, p3) => {
let p01 = p0.lerp(p1, t);
let p12 = p1.lerp(p2, t);
let p23 = p2.lerp(p3, t);
let p012 = p01.lerp(p12, t);
let p123 = p12.lerp(p23, t);
let p = p012.lerp(p123, t);
(PathSegment::Cubic(p0, p01, p012, p), PathSegment::Cubic(p, p123, p23, p3))
}
PathSegment::Quadratic(p0, p1, p2) => {
let p01 = p0.lerp(p1, t);
let p12 = p1.lerp(p2, t);
let p = p01.lerp(p12, t);
(PathSegment::Quadratic(p0, p01, p), PathSegment::Quadratic(p, p12, p2))
}
PathSegment::Arc(start, _, _, _, _, _, end) => {
if let Some(center_param) = self.arc_segment_to_center() {
let mid_delta_theta = center_param.delta_theta * t;
let seg1 = PathArcSegmentCenterParametrization {
delta_theta: mid_delta_theta,
..center_param
}
.arc_segment_from_center(Some(start), None);
let seg2 = PathArcSegmentCenterParametrization {
theta1: center_param.theta1 + mid_delta_theta,
delta_theta: center_param.delta_theta - mid_delta_theta,
..center_param
}
.arc_segment_from_center(None, Some(end));
(seg1, seg2)
} else {
// https://svgwg.org/svg2-draft/implnote.html#ArcCorrectionOutOfRangeRadii
let p = start.lerp(end, t);
(PathSegment::Line(start, p), PathSegment::Line(p, end))
}
}
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/path/path_cubic_segment_self_intersection.rs | libraries/path-bool/src/path/path_cubic_segment_self_intersection.rs | use crate::path_segment::PathSegment;
const EPS: f64 = 1e-12;
pub fn path_cubic_segment_self_intersection(seg: &PathSegment) -> Option<[f64; 2]> {
// https://math.stackexchange.com/questions/3931865/self-intersection-of-a-cubic-bezier-interpretation-of-the-solution
if let PathSegment::Cubic(p1, p2, p3, p4) = seg {
let ax = -p1.x + 3. * p2.x - 3. * p3.x + p4.x;
let ay = -p1.y + 3. * p2.y - 3. * p3.y + p4.y;
let bx = 3. * p1.x - 6. * p2.x + 3. * p3.x;
let by = 3. * p1.y - 6. * p2.y + 3. * p3.y;
let cx = -3. * p1.x + 3. * p2.x;
let cy = -3. * p1.y + 3. * p2.y;
let m = ay * bx - ax * by;
let n = ax * cy - ay * cx;
let k = (-3. * ax * ax * cy * cy + 6. * ax * ay * cx * cy + 4. * ax * bx * by * cy - 4. * ax * by * by * cx - 3. * ay * ay * cx * cx - 4. * ay * bx * bx * cy + 4. * ay * bx * by * cx)
/ (ax * ax * by * by - 2. * ax * ay * bx * by + ay * ay * bx * bx);
if k < 0. {
return None;
}
let t1 = (n / m + k.sqrt()) / 2.;
let t2 = (n / m - k.sqrt()) / 2.;
if (EPS..=1. - EPS).contains(&t1) && (EPS..=1. - EPS).contains(&t2) {
let mut result = [t1, t2];
result.sort_by(|a, b| a.partial_cmp(b).unwrap());
Some(result)
} else {
None
}
} else {
None
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/path/intersection_path_segment.rs | libraries/path-bool/src/path/intersection_path_segment.rs | use crate::aabb::{Aabb, bounding_box_max_extent, bounding_boxes_overlap};
use crate::epsilons::Epsilons;
use crate::line_segment::{line_segment_intersection, line_segments_intersect};
use crate::line_segment_aabb::line_segment_aabb_intersect;
use crate::math::lerp;
use crate::path_segment::PathSegment;
use glam::DVec2;
use lyon_geom::{CubicBezierSegment, Point};
/// Convert PathSegment::Cubic to lyon_geom::CubicBezierSegment
fn path_segment_cubic_to_lyon(start: DVec2, ctrl1: DVec2, ctrl2: DVec2, end: DVec2) -> CubicBezierSegment<f64> {
CubicBezierSegment {
from: Point::new(start.x, start.y),
ctrl1: Point::new(ctrl1.x, ctrl1.y),
ctrl2: Point::new(ctrl2.x, ctrl2.y),
to: Point::new(end.x, end.y),
}
}
#[derive(Clone)]
struct IntersectionSegment {
seg: PathSegment,
start_param: f64,
end_param: f64,
bounding_box: Aabb,
}
#[inline(never)]
fn subdivide_intersection_segment(int_seg: &IntersectionSegment) -> [IntersectionSegment; 2] {
let (seg0, seg1) = int_seg.seg.split_at(0.5);
let mid_param = (int_seg.start_param + int_seg.end_param) / 2.;
[
IntersectionSegment {
seg: seg0,
start_param: int_seg.start_param,
end_param: mid_param,
bounding_box: seg0.approx_bounding_box(),
},
IntersectionSegment {
seg: seg1,
start_param: mid_param,
end_param: int_seg.end_param,
bounding_box: seg1.approx_bounding_box(),
},
]
}
#[inline(never)]
fn path_segment_to_line_segment(seg: &PathSegment) -> [DVec2; 2] {
match seg {
PathSegment::Line(start, end) => [*start, *end],
PathSegment::Cubic(start, _, _, end) => [*start, *end],
PathSegment::Quadratic(start, _, end) => [*start, *end],
PathSegment::Arc(start, _, _, _, _, _, end) => [*start, *end],
}
}
#[inline(never)]
fn intersection_segments_overlap(seg0: &IntersectionSegment, seg1: &IntersectionSegment) -> bool {
match (&seg0.seg, &seg1.seg) {
(PathSegment::Line(start0, end0), PathSegment::Line(start1, end1)) => {
line_segments_intersect([*start0, *end0], [*start1, *end1], 1e-6) // TODO: configurable
}
(PathSegment::Line(start, end), _) => line_segment_aabb_intersect([*start, *end], &seg1.bounding_box),
(_, PathSegment::Line(start, end)) => line_segment_aabb_intersect([*start, *end], &seg0.bounding_box),
_ => bounding_boxes_overlap(&seg0.bounding_box, &seg1.bounding_box),
}
}
#[inline(never)]
pub fn segments_equal(seg0: &PathSegment, seg1: &PathSegment, point_epsilon: f64) -> bool {
match (*seg0, *seg1) {
(PathSegment::Line(start0, end0), PathSegment::Line(start1, end1)) => start0.abs_diff_eq(start1, point_epsilon) && end0.abs_diff_eq(end1, point_epsilon),
(PathSegment::Cubic(p00, p01, p02, p03), PathSegment::Cubic(p10, p11, p12, p13)) => {
let start_and_end_equal = p00.abs_diff_eq(p10, point_epsilon) && p03.abs_diff_eq(p13, point_epsilon);
let parameter_equal = p01.abs_diff_eq(p11, point_epsilon) && p02.abs_diff_eq(p12, point_epsilon);
let direction1 = seg0.sample_at(0.1);
let direction2 = seg1.sample_at(0.1);
let angles_equal = (direction1 - p00).angle_to(direction2 - p00).abs() < point_epsilon * 4.;
start_and_end_equal && (parameter_equal || angles_equal)
}
(PathSegment::Quadratic(p00, p01, p02), PathSegment::Quadratic(p10, p11, p12)) => {
p00.abs_diff_eq(p10, point_epsilon) && p01.abs_diff_eq(p11, point_epsilon) && p02.abs_diff_eq(p12, point_epsilon)
}
(PathSegment::Arc(p00, rx0, ry0, angle0, large_arc0, sweep0, p01), PathSegment::Arc(p10, rx1, ry1, angle1, large_arc1, sweep1, p11)) => {
p00.abs_diff_eq(p10, point_epsilon) &&
(rx0 - rx1).abs() < point_epsilon &&
(ry0 - ry1).abs() < point_epsilon &&
(angle0 - angle1).abs() < point_epsilon && // TODO: Phi can be anything if rx = ry. Also, handle rotations by Pi/2.
large_arc0 == large_arc1 &&
sweep0 == sweep1 &&
p01.abs_diff_eq(p11, point_epsilon)
}
_ => false,
}
}
pub fn path_segment_intersection(seg0: &PathSegment, seg1: &PathSegment, endpoints: bool, eps: &Epsilons) -> Vec<[f64; 2]> {
match (seg0, seg1) {
(PathSegment::Line(start0, end0), PathSegment::Line(start1, end1)) => {
if let Some(st) = line_segment_intersection([*start0, *end0], [*start1, *end1], eps.param) {
if !endpoints && (st.0 < eps.param || st.0 > 1. - eps.param) && (st.1 < eps.param || st.1 > 1. - eps.param) {
return vec![];
}
return vec![st.into()];
}
}
(PathSegment::Cubic(s1, c11, c21, e1), PathSegment::Cubic(s2, c12, c22, e2)) => {
let path1 = path_segment_cubic_to_lyon(*s1, *c11, *c21, *e1);
let path2 = path_segment_cubic_to_lyon(*s2, *c12, *c22, *e2);
let intersections = path1.cubic_intersections_t(&path2);
let intersections: Vec<_> = intersections.into_iter().map(|(s, t)| [s, t]).collect();
return intersections;
}
_ => (),
};
// Fallback for quadratics and arc segments
// https://math.stackexchange.com/questions/20321/how-can-i-tell-when-two-cubic-b%C3%A9zier-curves-intersect
let mut pairs = vec![(
IntersectionSegment {
seg: *seg0,
start_param: 0.,
end_param: 1.,
bounding_box: seg0.approx_bounding_box(),
},
IntersectionSegment {
seg: *seg1,
start_param: 0.,
end_param: 1.,
bounding_box: seg1.approx_bounding_box(),
},
)];
let mut next_pairs = Vec::new();
let mut params = Vec::new();
let mut subdivided0 = Vec::new();
let mut subdivided1 = Vec::new();
// Check if start and end points are on the other bezier curves. If so, add an intersection.
while !pairs.is_empty() {
next_pairs.clear();
if pairs.len() > 256 {
return calculate_overlap_intersections(seg0, seg1, eps);
}
for (seg0, seg1) in pairs.iter() {
if segments_equal(&seg0.seg, &seg1.seg, eps.point) {
// TODO: move this outside of this loop?
continue; // TODO: what to do?
}
let is_linear0 = bounding_box_max_extent(&seg0.bounding_box) <= eps.linear || (seg0.end_param - seg0.start_param).abs() < eps.param;
let is_linear1 = bounding_box_max_extent(&seg1.bounding_box) <= eps.linear || (seg1.end_param - seg1.start_param).abs() < eps.param;
if is_linear0 && is_linear1 {
let line_segment0 = path_segment_to_line_segment(&seg0.seg);
let line_segment1 = path_segment_to_line_segment(&seg1.seg);
if let Some(st) = line_segment_intersection(line_segment0, line_segment1, eps.param) {
params.push([lerp(seg0.start_param, seg0.end_param, st.0), lerp(seg1.start_param, seg1.end_param, st.1)]);
}
} else {
subdivided0.clear();
subdivided1.clear();
if is_linear0 {
subdivided0.push(seg0.clone())
} else {
subdivided0.extend_from_slice(&subdivide_intersection_segment(seg0))
};
if is_linear1 {
subdivided1.push(seg1.clone())
} else {
subdivided1.extend_from_slice(&subdivide_intersection_segment(seg1))
};
for seg0 in &subdivided0 {
for seg1 in &subdivided1 {
if intersection_segments_overlap(seg0, seg1) {
next_pairs.push((seg0.clone(), seg1.clone()));
}
}
}
}
}
std::mem::swap(&mut pairs, &mut next_pairs);
}
params
}
fn calculate_overlap_intersections(seg0: &PathSegment, seg1: &PathSegment, eps: &Epsilons) -> Vec<[f64; 2]> {
let start0 = seg0.start();
let end0 = seg0.end();
let start1 = seg1.start();
let end1 = seg1.end();
let mut intersections = Vec::new();
// Check start0 against seg1
if let Some(t1) = find_point_on_segment(seg1, start0, eps) {
intersections.push([0., t1]);
}
// Check end0 against seg1
if let Some(t1) = find_point_on_segment(seg1, end0, eps) {
intersections.push([1., t1]);
}
// Check start1 against seg0
if let Some(t0) = find_point_on_segment(seg0, start1, eps) {
intersections.push([t0, 0.]);
}
// Check end1 against seg0
if let Some(t0) = find_point_on_segment(seg0, end1, eps) {
intersections.push([t0, 1.]);
}
// Remove duplicates and sort intersections
intersections.sort_unstable_by(|a, b| a[0].partial_cmp(&b[0]).unwrap());
intersections.dedup_by(|a, b| DVec2::from(*a).abs_diff_eq(DVec2::from(*b), eps.param));
// Handle special cases
if intersections.is_empty() {
// Check if segments are identical
if (start0.abs_diff_eq(start1, eps.point)) && end0.abs_diff_eq(end1, eps.point) {
return vec![[0., 0.], [1., 1.]];
}
} else if intersections.len() > 2 {
// Keep only the first and last intersection points
intersections = vec![intersections[0], intersections[intersections.len() - 1]];
}
intersections
}
fn find_point_on_segment(seg: &PathSegment, point: DVec2, eps: &Epsilons) -> Option<f64> {
let start = 0.;
let end = 1.;
let mut t = 0.5;
for _ in 0..32 {
// Limit iterations to prevent infinite loops
let current_point = seg.sample_at(t);
if current_point.abs_diff_eq(point, eps.point) {
return Some(t);
}
let start_point = seg.sample_at(start);
let end_point = seg.sample_at(end);
let dist_start = (point - start_point).length_squared();
let dist_end = (point - end_point).length_squared();
let dist_current = (point - current_point).length_squared();
if dist_current < dist_start && dist_current < dist_end {
return Some(t);
}
if dist_start < dist_end {
t = (start + t) / 2.;
} else {
t = (t + end) / 2.;
}
if (end - start) < eps.param {
break;
}
}
None
}
#[cfg(test)]
mod test {
use super::*;
use glam::DVec2;
#[test]
fn intersect_cubic_slow_first() {
path_segment_intersection(&a(), &b(), true, &crate::EPS);
}
#[test]
fn intersect_cubic_slow_second() {
path_segment_intersection(&c(), &d(), true, &crate::EPS);
}
fn a() -> PathSegment {
PathSegment::Cubic(
DVec2::new(458.37027, 572.165771),
DVec2::new(428.525848, 486.720093),
DVec2::new(368.618805, 467.485992),
DVec2::new(273., 476.),
)
}
fn b() -> PathSegment {
PathSegment::Cubic(DVec2::new(273., 476.), DVec2::new(419., 463.), DVec2::new(481.741198, 514.692273), DVec2::new(481.333333, 768.))
}
fn c() -> PathSegment {
PathSegment::Cubic(DVec2::new(273., 476.), DVec2::new(107.564178, 490.730591), DVec2::new(161.737915, 383.575775), DVec2::new(0., 340.))
}
fn d() -> PathSegment {
PathSegment::Cubic(DVec2::new(0., 340.), DVec2::new(161.737914, 383.575765), DVec2::new(107.564182, 490.730587), DVec2::new(273., 476.))
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/src/path/line_segment.rs | libraries/path-bool/src/path/line_segment.rs | use glam::DVec2;
pub type LineSegment = [DVec2; 2];
const COLLINEAR_EPS: f64 = f64::EPSILON * 64.;
#[inline(never)]
pub fn line_segment_intersection([p1, p2]: LineSegment, [p3, p4]: LineSegment, eps: f64) -> Option<(f64, f64)> {
// https://en.wikipedia.org/wiki/Intersection_(geometry)#Two_line_segments
let a = p2 - p1;
let b = p3 - p4;
let c = p3 - p1;
let denom = a.x * b.y - a.y * b.x;
if denom.abs() < COLLINEAR_EPS {
return None;
}
let s = (c.x * b.y - c.y * b.x) / denom;
let t = (a.x * c.y - a.y * c.x) / denom;
if (-eps..=1. + eps).contains(&s) && (-eps..=1. + eps).contains(&t) { Some((s, t)) } else { None }
}
pub fn line_segments_intersect(seg1: LineSegment, seg2: LineSegment, eps: f64) -> bool {
line_segment_intersection(seg1, seg2, eps).is_some()
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/benches/path_segment_intersection.rs | libraries/path-bool/benches/path_segment_intersection.rs | use criterion::{Criterion, black_box, criterion_group, criterion_main};
use glam::DVec2;
use path_bool::*;
pub fn criterion_benchmark(crit: &mut Criterion) {
crit.bench_function("intersect 1", |bench| bench.iter(|| path_segment_intersection(black_box(&a()), black_box(&b()), true, &EPS)));
crit.bench_function("intersect 2", |bench| bench.iter(|| path_segment_intersection(black_box(&c()), black_box(&d()), true, &EPS)));
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
fn a() -> PathSegment {
PathSegment::Cubic(
DVec2::new(458.37027, 572.165771),
DVec2::new(428.525848, 486.720093),
DVec2::new(368.618805, 467.485992),
DVec2::new(273., 476.),
)
}
fn b() -> PathSegment {
PathSegment::Cubic(DVec2::new(273., 476.), DVec2::new(419., 463.), DVec2::new(481.741198, 514.692273), DVec2::new(481.333333, 768.))
}
fn c() -> PathSegment {
PathSegment::Cubic(DVec2::new(273., 476.), DVec2::new(107.564178, 490.730591), DVec2::new(161.737915, 383.575775), DVec2::new(0., 340.))
}
fn d() -> PathSegment {
PathSegment::Cubic(DVec2::new(0., 340.), DVec2::new(161.737914, 383.575765), DVec2::new(107.564182, 490.730587), DVec2::new(273., 476.))
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/libraries/path-bool/benches/painted_dreams.rs | libraries/path-bool/benches/painted_dreams.rs | use criterion::{Criterion, black_box, criterion_group, criterion_main};
use path_bool::*;
pub fn criterion_benchmark(c: &mut Criterion) {
let path_a =
path_from_path_data("M0,340C161.737914,383.575765 107.564182,490.730587 273,476 C419,463 481.741198,514.692273 481.333333,768 C481.333333,768 -0,768 -0,768 C-0,768 0,340 0,340 Z").unwrap();
let path_b = path_from_path_data(
"M458.370270,572.165771C428.525848,486.720093 368.618805,467.485992 273,476 C107.564178,490.730591 161.737915,383.575775 0,340 C0,340 0,689 0,689 C56,700 106.513901,779.342590 188,694.666687 C306.607422,571.416260 372.033966,552.205139 458.370270,572.165771 Z",
).unwrap();
c.bench_function("painted_dreams_diff", |b| {
b.iter(|| path_boolean(black_box(&path_a), FillRule::NonZero, black_box(&path_b), FillRule::NonZero, PathBooleanOperation::Difference))
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
emilk/egui | https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/tests/egui_tests/tests/regression_tests.rs | tests/egui_tests/tests/regression_tests.rs | use egui::accesskit::Role;
use egui::{Align, Color32, Image, Label, Layout, RichText, Sense, TextWrapMode, include_image};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable as _;
#[test]
fn image_button_should_have_alt_text() {
let harness = Harness::new_ui(|ui| {
_ = ui.button(
Image::new(include_image!("../../../crates/eframe/data/icon.png")).alt_text("Egui"),
);
});
harness.get_by_label("Egui");
}
#[test]
fn hovering_should_preserve_text_format() {
let mut harness = Harness::builder().with_size((200.0, 70.0)).build_ui(|ui| {
ui.add(
Label::new(
RichText::new("Long text that should be elided and has lots of styling and is long enough to have multiple lines.")
.italics()
.underline()
.color(Color32::LIGHT_BLUE),
)
.wrap_mode(TextWrapMode::Truncate),
);
});
harness.get_by_label_contains("Long text").hover();
harness.run_steps(5);
harness.snapshot("hovering_should_preserve_text_format");
}
#[test]
fn text_edit_rtl() {
let mut text = "hello ".to_owned();
let mut harness = Harness::builder().with_size((200.0, 50.0)).build_ui(|ui| {
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
_ = ui.button("right");
ui.add(
egui::TextEdit::singleline(&mut text)
.desired_width(10.0)
.clip_text(false),
);
_ = ui.button("left");
});
});
harness.get_by_role(Role::TextInput).focus();
harness.step();
harness.snapshot("text_edit_rtl_0");
harness.get_by_role(Role::TextInput).type_text("world");
for i in 1..3 {
harness.step();
harness.snapshot(format!("text_edit_rtl_{i}"));
}
}
#[test]
fn combobox_should_have_value() {
let harness = Harness::new_ui(|ui| {
egui::ComboBox::from_label("Select an option")
.selected_text("Option 1")
.show_ui(ui, |_ui| {});
});
assert_eq!(
harness.get_by_label("Select an option").value().as_deref(),
Some("Option 1")
);
}
/// This test ensures that `ui.response().interact(...)` works correctly.
///
/// This was broken, because there was an optimization in [`egui::Response::interact`]
/// which caused the [`Sense`] of the original response to flip-flop between `click` and `hover`
/// between frames.
///
/// See <https://github.com/emilk/egui/pull/7713> for more details.
#[test]
fn interact_on_ui_response_should_be_stable() {
let mut first_frame = true;
let mut click_count = 0;
let mut harness = Harness::new_ui(|ui| {
let ui_response = ui.response();
if !first_frame {
assert!(
ui_response.sense.contains(Sense::click()),
"ui.response() didn't have click sense even though we called interact(Sense::click()) last frame"
);
}
// Add a label so we have something to click with kittest
ui.add(
Label::new("senseless label")
.sense(Sense::hover())
.selectable(false),
);
let click_response = ui_response.interact(Sense::click());
if click_response.clicked() {
click_count += 1;
}
first_frame = false;
});
for i in 0..=10 {
harness.run_steps(i);
harness.get_by_label("senseless label").click();
}
drop(harness);
assert_eq!(click_count, 10, "We missed some clicks!");
}
| rust | Apache-2.0 | 9e95b9ca50c224077617434707f7bd29bd70938b | 2026-01-04T15:36:36.351731Z | false |
emilk/egui | https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/tests/egui_tests/tests/test_atoms.rs | tests/egui_tests/tests/test_atoms.rs | use egui::{Align, AtomExt as _, Button, Layout, TextWrapMode, Ui, Vec2};
use egui_kittest::{HarnessBuilder, SnapshotResult, SnapshotResults};
#[test]
fn test_atoms() {
let mut results = SnapshotResults::new();
results.add(single_test("max_width", |ui| {
ui.add(Button::new((
"max width not grow".atom_max_width(30.0),
"other text",
)));
}));
results.add(single_test("max_width_and_grow", |ui| {
ui.add(Button::new((
"max width and grow".atom_max_width(30.0).atom_grow(true),
"other text",
)));
}));
results.add(single_test("shrink_first_text", |ui| {
ui.style_mut().wrap_mode = Some(TextWrapMode::Truncate);
ui.add(Button::new(("this should shrink", "this shouldn't")));
}));
results.add(single_test("shrink_last_text", |ui| {
ui.style_mut().wrap_mode = Some(TextWrapMode::Truncate);
ui.add(Button::new((
"this shouldn't shrink",
"this should".atom_shrink(true),
)));
}));
results.add(single_test("grow_all", |ui| {
ui.style_mut().wrap_mode = Some(TextWrapMode::Truncate);
ui.add(Button::new((
"I grow".atom_grow(true),
"I also grow".atom_grow(true),
"I grow as well".atom_grow(true),
)));
}));
results.add(single_test("size_max_size", |ui| {
ui.style_mut().wrap_mode = Some(TextWrapMode::Truncate);
ui.add(Button::new((
"size and max size"
.atom_size(Vec2::new(80.0, 80.0))
.atom_max_size(Vec2::new(20.0, 20.0)),
"other text".atom_grow(true),
)));
}));
}
fn single_test(name: &str, mut f: impl FnMut(&mut Ui)) -> SnapshotResult {
let mut harness = HarnessBuilder::default()
.with_size(Vec2::new(400.0, 200.0))
.build_ui(move |ui| {
ui.label("Normal");
let normal_width = ui.horizontal(&mut f).response.rect.width();
ui.label("Justified");
ui.with_layout(
Layout::left_to_right(Align::Min).with_main_justify(true),
&mut f,
);
ui.label("Shrunk");
ui.scope(|ui| {
ui.set_max_width(normal_width / 2.0);
f(ui);
});
});
harness.try_snapshot(name)
}
#[test]
fn test_intrinsic_size() {
let widgets = [Ui::button, Ui::label];
for widget in widgets {
let mut intrinsic_size = None;
for wrapping in [
TextWrapMode::Extend,
TextWrapMode::Wrap,
TextWrapMode::Truncate,
] {
_ = HarnessBuilder::default()
.with_size(Vec2::new(100.0, 100.0))
.build_ui(|ui| {
ui.style_mut().wrap_mode = Some(wrapping);
let response = widget(
ui,
"Hello world this is a long text that should be wrapped.",
);
if let Some(current_intrinsic_size) = intrinsic_size {
assert_eq!(
Some(current_intrinsic_size),
response.intrinsic_size,
"For wrapping: {wrapping:?}"
);
}
assert!(
response.intrinsic_size.is_some(),
"intrinsic_size should be set for `Button`"
);
intrinsic_size = response.intrinsic_size;
if wrapping == TextWrapMode::Extend {
assert_eq!(Some(response.rect.size()), response.intrinsic_size);
}
});
}
}
}
#[test]
fn test_button_shortcut_text() {
let mut harness = HarnessBuilder::default().build_ui(|ui| {
ui.add(egui::Button::new("Click me").shortcut_text(("1", "2", "3")));
});
harness.run();
harness.fit_contents();
harness.snapshot("button_shortcut");
}
| rust | Apache-2.0 | 9e95b9ca50c224077617434707f7bd29bd70938b | 2026-01-04T15:36:36.351731Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.