Skip to content

Instantly share code, notes, and snippets.

@Tosainu
Created January 2, 2019 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tosainu/fb13623b9fa56593ad6bc5dacef08dc8 to your computer and use it in GitHub Desktop.
Save Tosainu/fb13623b9fa56593ad6bc5dacef08dc8 to your computer and use it in GitHub Desktop.
use std::f32;
use num_complex::Complex;
// http://linas.org/art-gallery/escape/smooth.html
fn smooth_iter(i: u32, z: Complex<f32>) -> f32 {
i as f32 - z.norm().ln().ln() / 2.0f32.ln()
}
// https://github.com/Nuke928/mandelbrot-opengl/blob/039fe9213c01992584f7b391da49bdeeb8d259e2/shader.glsl#L10-L16
fn map_to_color(t: f32) -> (u8, u8, u8) {
let r = 9.0 * (1.0 - t) * t * t * t;
let g = 15.0 * (1.0 - t) * (1.0 - t) * t * t;
let b = 8.5 * (1.0 - t) * (1.0 - t) * (1.0 - t) * t;
(
(r * 255.0).min(255.0).floor() as u8,
(g * 255.0).min(255.0).floor() as u8,
(b * 255.0).min(255.0).floor() as u8,
)
}
fn main() {
let imgx = 2048;
let imgy = 2048;
let max_iter = 255;
let scalex = 3.0 / imgx as f32;
let scaley = 3.0 / imgy as f32;
let mut imgbuf = image::ImageBuffer::new(imgx, imgy);
for (x, y, pixel) in imgbuf.enumerate_pixels_mut() {
let cx = x as f32 * scalex - 1.5;
let cy = y as f32 * scaley - 1.5;
let c = Complex::new(-0.4, 0.6);
let mut z = Complex::new(cx, cy);
let mut i = 0u32;
while i < max_iter && z.norm() <= 2.0 {
z = z * z + c;
i += 1;
}
// let (r, g, b) = map_to_color(i as f32 / 255.0);
let (r, g, b) = if i == max_iter {
(0, 0, 0)
} else {
map_to_color(smooth_iter(i, z) / max_iter as f32)
};
*pixel = image::Rgb([r, g, b]);
}
imgbuf.save("fractal.png").unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment