vornoi experiment

This commit is contained in:
Artur Sapek 2022-04-27 10:30:32 -06:00 committed by Héctor Ramón Jiménez
parent fe17641d46
commit 9d6834f250
No known key found for this signature in database
GPG key ID: 140CC052C94F138E
2 changed files with 81 additions and 5 deletions

View file

@ -9,3 +9,4 @@ publish = false
iced = { path = "../..", features = ["canvas", "tokio", "debug"] }
tokio = { version = "1.0", features = ["sync"] }
env_logger = "0.9"
voronoi = "0.1.4"

View file

@ -9,6 +9,7 @@ use iced::{
};
use std::collections::HashMap;
use voronoi;
pub fn main() -> iced::Result {
env_logger::builder().format_timestamp(None).init();
@ -126,16 +127,77 @@ impl<'a> canvas::Program<Message> for State {
_state: &Self::State,
_theme: &Theme,
bounds: Rectangle,
_cursor: Cursor,
cursor: Cursor,
) -> Vec<Geometry> {
let fingerweb = self.cache.draw(bounds.size(), |frame| {
for finger in &self.fingers {
dbg!(&finger);
let mut fingers = HashMap::new();
let circle = Path::new(|p| p.circle(*finger.1, 50.0));
// TODO delete fake fingers
fingers.insert(1, Point { x: 50.0, y: 50.0 });
fingers.insert(2, Point { x: 250.0, y: 400.0 });
fingers.insert(3, Point { x: 650.0, y: 120.0 });
fingers.insert(4, Point { x: 750.0, y: 520.0 });
match cursor {
canvas::Cursor::Available(pt) => {
dbg!(&pt);
fingers.insert(5, pt);
}
_ => {}
}
// Collect tuples of (id, point);
let mut zones: Vec<(i32, Point)> = fingers
.iter()
.map(|(id, pt)| (id.clone(), pt.clone()))
.collect();
// Sort by ID
zones.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
// Generate sorted list of points
let vpoints: Vec<voronoi::Point> = zones
.iter()
.map(|zone| iced_point_to_voronoi_point(&zone.1))
.collect();
let diagram = voronoi::voronoi(vpoints, 700.0);
let polys = voronoi::make_polygons(&diagram);
for i in 0..polys.len() {
let mut builder = canvas::path::Builder::new();
let zone = &zones[i];
let poly = &polys[i];
for (index, pt) in poly.iter().enumerate() {
let pt = voronoi_point_to_iced_point(pt);
match index {
0 => builder.move_to(pt),
_ => builder.line_to(pt),
}
}
let path = builder.build();
let zone = &zones[i];
let color_r = (10 % zone.0) as f32 / 20.0;
let color_g = (10 % (zone.0 + 8)) as f32 / 20.0;
let color_b = (10 % (zone.0 + 3)) as f32 / 20.0;
frame.fill(
&path,
Color {
r: color_r,
g: color_g,
b: color_b,
a: 1.0,
},
);
frame.stroke(
&circle,
&path,
Stroke {
color: Color::BLACK,
width: 3.0,
@ -148,3 +210,16 @@ impl<'a> canvas::Program<Message> for State {
vec![fingerweb]
}
}
fn iced_point_to_voronoi_point(pt: &iced::Point) -> voronoi::Point {
voronoi::Point::new(pt.x.into(), pt.y.into())
}
fn voronoi_point_to_iced_point(pt: &voronoi::Point) -> iced::Point {
let x: f64 = pt.x.into();
let y: f64 = pt.y.into();
Point {
x: x as f32,
y: y as f32,
}
}