Created
March 25, 2024 12:11
-
-
Save float3/cf26e1bd33076a09edb21d677f09f2e7 to your computer and use it in GitHub Desktop.
optlevel = 1 is white while optlevel = 0 works
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use minifb::{Key, Scale, Window, WindowOptions}; | |
| use num_complex::Complex; | |
| use tokio::task; | |
| const WIDTH: usize = 640; | |
| const HEIGHT: usize = 360; | |
| fn mandelbrot_set(c: Complex<f64>, limit: u32) -> Option<u32> { | |
| let mut z = Complex::new(0.0, 0.0); | |
| for i in 0..limit { | |
| if z.norm() > 2.0 { | |
| return Some(i); | |
| } | |
| z = z * z + c; | |
| } | |
| None | |
| } | |
| #[tokio::main] | |
| async fn main() { | |
| let mut zoom = 1.0; | |
| let center_x = 0.0; | |
| let center_y = 0.0; | |
| let mut window = Window::new( | |
| "Test Window", | |
| WIDTH, | |
| HEIGHT, | |
| WindowOptions { | |
| scale: Scale::X2, | |
| ..WindowOptions::default() | |
| }, | |
| ) | |
| .unwrap_or_else(|e| { | |
| panic!("{}", e); | |
| }); | |
| let mut accumulated_buffer = vec![0u64; WIDTH * HEIGHT]; | |
| let mut frame_count = 0u64; | |
| while window.is_open() && !window.is_key_down(Key::Escape) { | |
| let buffer: Vec<u32> = task::spawn(async move { | |
| let limit = 100; | |
| let mut buffer = vec![0u32; WIDTH * HEIGHT]; | |
| (0..HEIGHT).for_each(|y| { | |
| (0..WIDTH).for_each(|x| { | |
| let re = (3.0 * (x as f64 - center_x) / (WIDTH as f64) - 2.0) / zoom; | |
| let im = (2.0 * (y as f64 - center_y) / (HEIGHT as f64) - 1.0) / zoom; | |
| let c = Complex::new(re, im); | |
| if let Some(i) = mandelbrot_set(c, limit) { | |
| if let Some(value) = i.checked_mul(0x0000_0100u32) { | |
| if let Some(color) = 0x00FF_FF00u32.checked_sub(value) { | |
| buffer[y * WIDTH + x] = color; | |
| } | |
| } | |
| } | |
| }); | |
| }); | |
| buffer | |
| }) | |
| .await | |
| .unwrap(); | |
| for (i, pixel) in buffer.iter().enumerate() { | |
| accumulated_buffer[i] += *pixel as u64; | |
| } | |
| frame_count += 1; | |
| let averaged_buffer: Vec<u32> = accumulated_buffer | |
| .iter() | |
| .map(|&sum| { | |
| let average = sum / frame_count; | |
| let clamped_average = if average > u32::MAX as u64 { | |
| u32::MAX as u64 | |
| } else { | |
| average | |
| }; | |
| clamped_average as u32 | |
| }) | |
| .collect(); | |
| std::thread::sleep(std::time::Duration::from_nanos(1000000000 / 60)); | |
| window | |
| .update_with_buffer(&averaged_buffer, WIDTH, HEIGHT) | |
| .unwrap(); | |
| zoom *= 1.01; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment