1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
//! Find the first collision between a ray and a path.

use path::PathEvent;
use math::{Point, point, Vector, vector};
use geom::{LineSegment, Line};
use std::f32;

pub struct Ray {
    pub origin: Point,
    pub direction: Vector,
}

// Position and normal at the point of contact between a ray and a shape.
pub struct Hit {
    pub position: Point,
    pub normal: Vector,
}

// TODO: early out in the bézier/arc cases using bounding rect or circle
// to speed things up.

/// Find the closest collision between a ray and the path.
pub fn raycast_path<Iter>(ray: &Ray, path: Iter, tolerance: f32) -> Option<Hit>
where
    Iter: Iterator<Item=PathEvent>,
{
    let ray_len = ray.direction.square_length();
    if ray_len == 0.0 || ray_len.is_nan() {
        return None;
    }

    let mut state = RayCastInner {
        ray: Line {
            point: ray.origin,
            vector: ray.direction,
        },
        min_dot: f32::MAX,
        result: point(0.0, 0.0),
        normal: vector(0.0, 0.0),
    };

    for evt in path {
        match evt {
            PathEvent::MoveTo(..) => {}
            PathEvent::Line(ref segment) | PathEvent::Close(ref segment) => {
                test_segment(&mut state, segment);
            }
            PathEvent::Quadratic(ref segment) => {
                let mut prev = segment.from;
                segment.for_each_flattened(tolerance, &mut|p| {
                    test_segment(&mut state, &LineSegment { from: prev, to: p });
                    prev = p;
                });
            }
            PathEvent::Cubic(ref segment) => {
                let mut prev = segment.from;
                segment.for_each_flattened(tolerance, &mut|p| {
                    test_segment(&mut state, &LineSegment { from: prev, to: p });
                    prev = p;
                });
            }
        }
    }

    if state.min_dot == f32::MAX {
        return None;
    }

    if state.normal.dot(ray.direction) > 0.0 {
        state.normal = -state.normal;
    }

    Some(Hit {
        position: state.result,
        normal: state.normal.normalize(),
    })
}

struct RayCastInner {
    ray: Line<f32>,
    min_dot: f32,
    result: Point,
    normal: Vector,
}

fn test_segment(state: &mut RayCastInner, segment: &LineSegment<f32>) {
    if let Some(pos) = segment.line_intersection(&state.ray) {
        let dot = (pos - state.ray.point).dot(state.ray.vector);
        if dot >= 0.0 && dot < state.min_dot {
            state.min_dot = dot;
            state.result = pos;
            let v = segment.to_vector();
            state.normal = vector(-v.y, v.x);
        }
    }
}

#[test]
fn test_raycast() {
    use geom::euclid::approxeq::ApproxEq;
    use path::Path;

    let mut builder = Path::builder();
    builder.move_to(point(0.0, 0.0));
    builder.line_to(point(1.0, 0.0));
    builder.line_to(point(1.0, 1.0));
    builder.line_to(point(0.0, 1.0));
    builder.close();
    let path = builder.build();

    assert!(
        raycast_path(
            &Ray { origin: point(-1.0, 2.0), direction: vector(1.0, 0.0) },
            path.iter(),
            0.1
        ).is_none()
    );

    let hit = raycast_path(
        &Ray { origin: point(-1.0, 0.5), direction: vector(1.0, 0.0) },
        path.iter(),
        0.1
    ).unwrap();
    assert!(hit.position.approx_eq(&point(0.0, 0.5)));
    assert!(hit.normal.approx_eq(&vector(-1.0, 0.0)));

    let hit = raycast_path(
        &Ray { origin: point(-1.0, 0.0), direction: vector(1.0, 0.0) },
        path.iter(),
        0.1
    ).unwrap();
    assert!(hit.position.approx_eq(&point(0.0, 0.0)));

    let hit = raycast_path(
        &Ray { origin: point(0.5, 0.5), direction: vector(1.0, 0.0) },
        path.iter(),
        0.1
    ).unwrap();
    assert!(hit.position.approx_eq(&point(1.0, 0.5)));
    assert!(hit.normal.approx_eq(&vector(-1.0, 0.0)));

    let hit = raycast_path(
        &Ray { origin: point(0.0, -1.0), direction: vector(1.0, 1.0) },
        path.iter(),
        0.1
    ).unwrap();
    assert!(hit.position.approx_eq(&point(1.0, 0.0)));
}