Skip to content

Instantly share code, notes, and snippets.

@j-walk
Created January 14, 2018 08:37
Show Gist options
  • Save j-walk/c17ca98a7d2dd1b68cba806407f2c1bc to your computer and use it in GitHub Desktop.
Save j-walk/c17ca98a7d2dd1b68cba806407f2c1bc to your computer and use it in GitHub Desktop.
extern crate image;
extern crate num;
use std::fs::File;
use std::path::Path;
use num::Complex;
// a function which takes a borrowed Complex<f32> and checks if its within
// the bounds of the mandelbrot set
fn in_mandel(p : &Complex<f32>) -> bool {
p.norm_sqr() < 4.0
}
// takes in an iteration limit and a borrowed Complex<f32>
// preforms z = z^2 + p until it reaches the iteration limit or
// it goes out of bounds
fn iter(limit : usize, p : &Complex<f32>) -> usize {
let mut i : usize = 0;
let mut z : Complex<f32> = Complex::new(0.0, 0.0);
while i < limit && in_mandel(&z) {
z = z.powf(2.0) + p;
i += 1;
};
i
}
// really shitty color pallet just uses the iteration count as a color
// looks awful
fn color(i : usize, max_iter : usize) -> [u8;3] {
if i == max_iter {
[0,0,0]
} else if i < 64 {
[(i * 2) as u8, 0, 0]
} else if i < 128 {
[((((i - 64) * 128)as f32 / 126.0) as usize + 128) as u8, 0, 0]
} else if i < 256 {
[((((i - 128) * 62)as f32 / 127.0) as usize + 193) as u8, 0, 0]
} else if i < 512 {
[255, ((((i - 256) * 62)as f32 / 255.0) as usize + 1) as u8, 0]
} else if i < 1024 {
[255, ((((i - 512) * 63)as f32 / 511.0) as usize + 64) as u8, 0]
} else if i < 2048 {
[255, ((((i - 1024) * 63)as f32 / 1023.0) as usize + 128) as u8, 0]
} else if i < 4096 {
[255, ((((i - 2048) * 63)as f32 / 2047.0) as usize + 192) as u8, 0]
} else {
[255, 255, 0]
}
}
// main function o boi
fn main() {
// some dumb x and y offsets with variables
let x : f32 = 0.75;
let y : f32 = 0.0;
let scale : f32 = 0.001;
let max_iter = 1000;
let size_x = 1920;
let size_y = 1080;
// reserves the space for the image in ram of size 1000x1000
let mut image = image::ImageBuffer::new(size_x, size_y);
// showing off the beautiful iterator trait
// enumerate_pixels_mut() returns an iterator of the x, y, and reference to
// the pixels
for (re, im, p) in image.enumerate_pixels_mut() {
// this is dumb shit don't do this in practice
// just shoving functions into one another
// you can use some libs like command to have pipelines but I cba
*p = image::Rgb(color(iter(
max_iter
, &Complex::new( (re as f32 - size_x as f32/2.0) * scale - x
, (im as f32 - size_y as f32/2.0) * scale - y
)), max_iter));
};
// creating the file reference
let ref mut fout = File::create(&Path::new("test.png")).unwrap();
// writing the image to the file and throwing away the result
let _ = image::ImageRgb8(image).save(fout, image::PNG);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment