use std::hash::{DefaultHasher, Hash, Hasher};
use std::rc::Rc;
use crate::render::Rect;
pub type Point = [f32; 2];
pub type Quad = [Point; 3];
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Path {
pub contours: Vec<Vec<Quad>>,
}
impl Path {
pub fn polygon(points: &[Point]) -> Path {
let edges = (0..points.len())
.map(|i| line(points[i], points[(i + 1) % points.len()]))
.collect();
Path {
contours: vec![edges],
}
}
pub fn offset(mut self, dx: f32, dy: f32) -> Path {
for q in self.contours.iter_mut().flatten() {
for p in q {
*p = [p[0] + dx, p[1] + dy];
}
}
self
}
}
#[derive(Clone)]
pub struct Shape(pub(crate) Rc<ShapeData>);
pub(crate) struct ShapeData {
pub key: u64,
pub path: Path,
pub view: Rect,
}
impl Shape {
pub fn from_bytes(bytes: &[u8]) -> Option<Shape> {
let body = bytes.strip_prefix(b"DFP1")?;
let mut words = body
.as_chunks::<4>()
.0
.iter()
.map(|&w| u32::from_le_bytes(w));
let mut f = || words.next().map(f32::from_bits);
let view = Rect::new(f()?, f()?, f()?, f()?);
let lengths: Vec<u32> = (0..f()?.to_bits())
.map(|_| f().map(f32::to_bits))
.collect::<Option<_>>()?;
let mut contours = Vec::new();
for n in lengths {
let quads = (0..n)
.map(|_| Some([[f()?, f()?], [f()?, f()?], [f()?, f()?]]))
.collect::<Option<_>>()?;
contours.push(quads);
}
Some(Shape::new(Path { contours }, view))
}
pub fn new(path: Path, view: Rect) -> Shape {
let mut h = DefaultHasher::new();
let bits = [view.x, view.y, view.w, view.h];
let quads = path.contours.iter().flatten().flatten().flatten();
for v in bits.iter().chain(quads) {
v.to_bits().hash(&mut h);
}
let key = h.finish();
Shape(Rc::new(ShapeData { key, path, view }))
}
pub fn view(&self) -> Rect {
self.0.view
}
pub fn path(&self) -> &Path {
&self.0.path
}
}
pub(crate) fn line(a: Point, b: Point) -> Quad {
[a, [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0], b]
}