hit_test for HtmlAreaElement polygons

Signed-off-by: Ashwin Naren <arihant2math@gmail.com>
This commit is contained in:
Ashwin Naren 2025-05-21 00:13:08 -07:00
parent cd36c35cf2
commit 4fd818d46d
No known key found for this signature in database
GPG key ID: D96D7DE56FBCB6B6

View file

@ -46,6 +46,8 @@ pub enum Area {
bottom_right: (f32, f32),
},
Polygon {
/// Stored as a flat array of coordinates
/// e.g. [x1, y1, x2, y2, x3, y3] for a triangle
points: Vec<f32>,
},
}
@ -203,8 +205,27 @@ impl Area {
p.y >= top_left.1
},
//TODO polygon hit_test
_ => false,
Area::Polygon { ref points } => {
// Ray-casting algorithm to determine if point is inside polygon
let mut inside = false;
debug_assert!(points.len() % 2 == 0);
let vertices = points.len() / 2;
for i in 0..vertices {
let next_i = if i + 1 == vertices { 0 } else { i + 1 };
let xi = points[2 * i];
let yi = points[2 * i + 1];
let xj = points[2 * next_i];
let yj = points[2 * next_i + 1];
if (yi > p.y) != (yj > p.y) && p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi {
inside = !inside;
}
}
inside
},
}
}