more async

This commit is contained in:
Logan 2024-01-12 14:33:34 -06:00
parent f7591439fb
commit 21244bd086
2 changed files with 46 additions and 1 deletions

View file

@ -43,7 +43,8 @@ pub fn generate(image: ImageBuffer<Rgb<u8>, Vec<u8>>) -> Vec<u8> {
}
pub async fn generate_async(image: ImageBuffer<Rgb<u8>, Vec<u8>>) -> Vec<u8> {
let (mut sim, it) = sim::Simulation::simulate_image(500.0, 500.0, 8.0, image);
let (mut sim, it) =
sim::Simulation::simulate_image_async(500.0, 500.0, 8.0, image).await;
let mut buffer = Vec::<u8>::new();
let mut encoder = gif::Encoder::new(&mut buffer, 500, 500, &[]).unwrap();

View file

@ -91,6 +91,32 @@ impl Simulation {
(sim, total_iterations)
}
#[inline]
pub async fn simulate_image_async(
width: f32,
height: f32,
circle_radius: f32,
img: ImageBuffer<Rgb<u8>, Vec<u8>>,
) -> (Self, usize) {
let image_hash = ({
let mut s = std::hash::DefaultHasher::new();
img.hash(&mut s);
s.finish()
} % 1204) as usize;
let mut sim = Simulation::new(width, height, circle_radius, image_hash);
while sim.circles() < sim.max_circles {
sim.step_async().await;
}
for _ in 0..120 {
sim.step_async().await
}
let total_iterations = sim.clock;
sim.assign_colors_from_image(img);
sim.circles.clear();
sim.clock = sim.rand_seed;
(sim, total_iterations)
}
#[inline]
pub fn add_circle(&mut self, position: Vector2, velocity: Vector2) {
self.circles.push(Circle {
@ -220,6 +246,24 @@ impl Simulation {
});
}
#[inline]
pub async fn step_async(&mut self) {
if self.circles.len() < self.max_circles {
self.launch();
}
if self.circles.len() < self.max_circles {
self.launch2();
}
(0..self.substeps).for_each(|_| {
self.constrain_rect();
self.sort();
self.collide();
self.integrate();
self.clock += 1;
});
}
// #[inline]
// pub fn draw(&self, d: &mut RaylibDrawHandle) {
// self