Skip to content

Instantly share code, notes, and snippets.

@lukakostic
Created March 17, 2020 00:06
Show Gist options
  • Save lukakostic/92dae027a219a086a30054291b460ce3 to your computer and use it in GitHub Desktop.
Save lukakostic/92dae027a219a086a30054291b460ce3 to your computer and use it in GitHub Desktop.
/*
Use these commands to render img.ppm:
w & h: 4000 4000
2 -.5 0 .3
1
*/
#include<stdio.h>
#include<stdlib.h>
#include<vector>
using namespace std;
struct Complex{ double x,y; };
struct Color{ unsigned char r,g,b; };
//e is ^ , t is * , p is +
//z^2 + c (Mandelbrot set)
#define Ze2pC \
zt.x = z.x * z.x - z.y * z.y + c.x;\
zt.y = 2.0 * z.x * z.y + c.y;\
z = zt;
//Global settings
static unsigned int height = 1000, width = 1500;
static vector<Color> pixels;
//view x and y, zoom
static double vx = -.5, vy = 0, zoom = 1.0;
static double limit = 4.0; //2^2
static unsigned int maxIter = 200;
static Complex startPoint = Complex{0,0};
void SaveImage(){
printf("Saving image... ");
FILE *fp = fopen("img.ppm", "wb");
(void) fprintf(fp, "P6\n%u %u\n255\n", width, height);
fwrite(&pixels[0], sizeof(vector<Color>::value_type), width*height, fp);
fclose(fp);
printf(" Saved\n");
}
void Render(){
printf("Rendering... ");
Color white = Color{(unsigned char)255,(unsigned char)255,(unsigned char)255};
Color black = Color{(unsigned char)0,(unsigned char)0,(unsigned char)0};
for (int i = 0; i < (width*height); i++)
{
//Center & Scale pixels to view -1.0 to 1.0 for 1000x1000
//get 2d index - offset to make centered, div by 2.0(turn -.5,.5 to -1,1)/1000.0(scale 1kx1k to -1,1) (500)
double x = ((i % width) - (width / 2.0)) / 500.0;
double y = ((i / width) - (height / 2.0)) / 500.0;
//Move and zoom view
x = x * zoom + vx;
y = y * zoom + vy;
Complex c = Complex {x, y};
Complex z = startPoint;
Complex zt = z; //z temp
for (size_t j = 0; j < maxIter; j++)
{
Ze2pC
}
if((z.x*z.x+z.y*z.y) < limit){
pixels[i] = white;
}else{
pixels[i] = black;
}
}
printf(" Rendered\n");
SaveImage();
}
bool ReadCmd(){
int cmd = 0;
printf("Enter a command (0 for help):\n");
scanf("%d",&cmd);
if(cmd == 0){
printf("1 - render & save, 2 - set [vx vy zoom], 3 - set iterations [maxIter], 4 - set iteration start point, 5 - set [width height], 6 - quit\n");
}else if(cmd == 1){
Render();
}else if(cmd == 2){
scanf("%lf %lf %lf",&vx,&vy,&zoom);
}else if(cmd == 3){
scanf("%u",&maxIter);
}else if(cmd == 4){
scanf("%lf %lf",&startPoint.x,&startPoint.y);
}else if(cmd == 5){
scanf("%u %u",&width,&height);
pixels.clear();
pixels = vector<Color>(width * height);
}else if(cmd == 6)
return false;
return true;
}
int main(int argc, char* argv[]) {
int w,h;
printf("width height: ");
scanf("%u %u",&w,&h);
width = w;
height = h;
pixels = vector<Color>(width * height);
while(ReadCmd()){}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment