Anonymous user
Ray-casting algorithm: Difference between revisions
→{{header|Rust}}: cleanup
m (→{{header|REXX}}: added whitespace, changed an indentation for alignment.) |
(→{{header|Rust}}: cleanup) |
||
Line 3,180:
{{trans|Python}}
<lang rust>use std::f64;
const _EPS: f64 = 0.00001;
Line 3,186 ⟶ 3,185:
const _MAX: f64 = f64::MAX;
#[derive(
struct Point {
x: f64,
y: f64,
}
#[derive(
struct Edge {
pt1: Point,
pt2: Point,
}
impl Edge {
fn new(pt1: (f64, f64), pt2: (f64, f64)) -> Edge {
pt2: Point { x: pt2.0, y: pt2.1 },
}▼
}
}
struct Polygon {▼
edges: Vec<Edge>, // Polygon has to be created with counter-clockwise coordinates▼
▲struct Polygon{
▲ edges: Vec<Edge> // Polygon has to be created with counter-clockwise coordinates
}
fn pt_in_polygon(pt: &Point, poly: &Polygon) -> bool {
let count = poly.edges
.
.
.count();
count % 2 == 1
}
Line 3,219 ⟶ 3,223:
let (mut a, mut b): (&Point, &Point) = (&edge.pt1, &edge.pt2);
if a.y > b.y {
}
if pt.y == a.y || pt.y == b.y {
}
if (pt.y > b.y || pt.y < a.y) || pt.x > a.x.max(b.x) {
} else if pt.x < a.x.min(b.x) {
▲ }
▲ return true;
} else {
let m_red = if (a.x - b.x).abs() > _MIN {
_MAX
};
let m_blue = if (a.x - pt.x).abs() > _MIN {
(pt.y - a.y) / (pt.x - a.x)
} else {
_MAX
};
m_blue >= m_red
}
}
fn main() {
let p = |x, y| Point {
let testpoints =
let poly_square = Polygon {
edges: vec![
Line 3,244 ⟶ 3,256:
Edge::new((10.0, 0.0), (10.0, 10.0)),
Edge::new((10.0, 10.0), (0.0, 10.0)),
Edge::new((0.0, 10.0), (0.0, 0.0)),
let poly_square_hole = Polygon {
edges: vec![
Line 3,256 ⟶ 3,268:
Edge::new((7.5, 2.5), (7.5, 7.5)),
Edge::new((7.5, 7.5), (2.5, 7.5)),
Edge::new((2.5, 7.5), (2.5, 2.5)),
],
};
let poly_strange = Polygon {
Line 3,267 ⟶ 3,279:
Edge::new((7.5, 7.5), (10.0, 10.0)),
Edge::new((10.0, 10.0), (10.0, 0.0)),
Edge::new((10.0, 0.0), (2.5, 2.5)),
],
};
let poly_hexagon = Polygon {
Line 3,277 ⟶ 3,289:
Edge::new((7.0, 10.0), (3.0, 10.0)),
Edge::new((3.0, 10.0), (0.0, 5.0)),
Edge::new((0.0, 5.0), (3.0, 0.0)),
print!("\nSquare :");
for pt in &testpoints
print!(" {:?}", pt_in_polygon(pt, &poly_square));
}
print!("\nSquare with hole:");
for pt in &testpoints
print!(" {:?}", pt_in_polygon(pt, &poly_square_hole));
}
print!("\nStrange polygon :");
for pt in &testpoints
print!(" {:?}", pt_in_polygon(pt, &poly_strange));
}
print!("\nHexagon :");
for pt in &testpoints
print!(" {:?}", pt_in_polygon(pt, &poly_hexagon));
}
}</lang>
{{out}}
|