#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "SDL.h"
#include "SDL_image.h"
#include "SDL_gfxPrimitives.h"

#define N 256


int VERT;
int GONS;

/* 4 colors bytes, 2 coordinates per vertex */
#define GONLEN (4 + VERT * 2)
/* this for each polygon plus a backgroung color */
#define LEN (GONLEN * GONS + 3) 

/* types */

typedef struct agent
{
	Uint8 *dna;
	double fit;
} Agent;


/* Function prototypes */

Uint8 *make_rand_dna(void);
Uint8 *make_dna(void);
SDL_Surface *raster_dna(Uint8 *dna);
double compare_imgs(SDL_Surface *ima, SDL_Surface *imb);
double fitness(Uint8 *dna, SDL_Surface *target);
Uint32 getpixel(SDL_Surface *surface, int x, int y);

Uint8 *step_uphill(Uint8 *dna, SDL_Surface *target);
Agent *make_pool(int pop, SDL_Surface *target);
int agent_comp(const void* a, const void* b);
void breed_pool(Agent *pool, int pop, double loss, double newrand, SDL_Surface *target);
Agent *breed_pool2(Agent *pool, int pop, double newrand, SDL_Surface *target);

int main(int argc, char **argv)
{
	SDL_Surface *screen, *target, *raster;
	Uint8 *dna = NULL;
	int starttick, iter;
	Agent *pool;
	int pop = 100;
	int i;
	
	int invisible = 0, output = 0;
	
	char filename[256];
	
	/* args */
	
	switch (argc)
	{
		case 7:
			invisible = 1;
		case 6:
			output = 1;
			break;	
	}
	
	if (argc < 5)
	{
		printf("Usage : genepic vert gon path pop [output [invisible]]\n");
		exit(EXIT_FAILURE);
	}

	VERT = atoi(argv[1]);
	GONS = atoi(argv[2]);	
	pop = atoi(argv[4]);
	
	/* Init stuff, yeah */

	if( SDL_Init(SDL_INIT_VIDEO) < 0 )
	{
		printf("Couldn't initialize SDL: %s\n", SDL_GetError());
		exit(1);
	}
	
	screen=SDL_SetVideoMode(N,N,32, SDL_HWSURFACE|SDL_DOUBLEBUF);
        
        if(screen == NULL)
	{
		printf("Couldn't set %dx%d video mode: %s\n", N, N, SDL_GetError());
		exit(1);
        }
	
	srand(time(NULL));
	
	/* load the target picture */
	
	{
		SDL_Surface *tmp;
		
		tmp = IMG_Load(argv[3]);
		if ( tmp == NULL )
		{
			printf("Couldn't load image %s. Exiting.\n", argv[3]);
			exit(EXIT_FAILURE);
		}
	
		target = SDL_DisplayFormat(tmp);
		SDL_FreeSurface(tmp);
	}
	
	printf("Length of DNA: %d\n", LEN);
	
	pool = make_pool(pop,target);
	
	printf("Initial pool made.");
	
	starttick = SDL_GetTicks();
	iter = 0;
	
	while(1)
	{
		SDL_Event event;
		double rate;
		double time;

		while(SDL_PollEvent(&event))
		{
			if(event.type == SDL_QUIT)
				exit(0);
		}
		
		
		time = (SDL_GetTicks()-starttick)/60000.0; /* minutes */
		rate = iter / time; /* iteration per minute */
		
		/* always show the best one */
		dna = pool[pop - 1].dna;
		raster = raster_dna(dna);

		printf("#%d: %f %fmin (%f it/min)\n", iter, fitness(dna,target), time, rate);
		
		if(output)
		{	
			sprintf(filename, "%s-%.8d.bmp", argv[4], iter);
			if(SDL_SaveBMP(raster, filename) < 0)
				printf("Couldn't save file %s\n",filename);
		}
		if (!invisible)
		{
			SDL_BlitSurface(raster,NULL,screen,NULL);
			SDL_Flip(screen);
		}

		SDL_FreeSurface(raster);
		

		/* to see all the population in a flash */		
		/*
		for (i = 0; i < pop; i += 1)
		{
			dna = pool[i].dna;
			raster = raster_dna(dna);
			SDL_BlitSurface(raster,NULL,screen,NULL);
			SDL_Flip(screen);
			SDL_FreeSurface(raster);
		}
		*/
		
		
		/* evolution stuff */
	/*	breed_pool(pool, pop, 0.70, 0.05, target);*/
		pool = breed_pool2(pool, pop, 0.05, target);
		iter++;
	}
	
	SDL_FreeSurface(target);
	SDL_Quit();
	return 0;
}

Uint8 *make_dna(void)
{
	Uint8 *dna;
	
	dna = (Uint8 *)malloc(LEN * sizeof(dna));
	if (dna == NULL)
	{
		printf("Couldn't allocate memory. Exiting.\n");
		exit(EXIT_FAILURE);
	}
	
	return dna;
}

Uint8 *dup_dna(Uint8 *dna)
{
	Uint8 *dup;
	int i;
	
	dup = make_dna();
	for (i = 0; i < LEN; i += 1)
	{
		dup[i] = dna[i];
	}
	
	return dup;
}

Uint8 *make_rand_dna(void)
{
	Uint8 *dna;
	int i;
	
	dna = make_dna();
	
	for (i = 0; i < LEN; i += 1)
	{
		dna[i] = rand() % 256;
	}
	
	return dna;
}

SDL_Surface *raster_dna(Uint8 *dna)
{
	SDL_Surface *surf, *tmp;
	int i;
	Sint16 *x, *y;
	
	/* prepare the coord tables */
	
	x = (Sint16 *)malloc(VERT * sizeof(x));
	y = (Sint16 *)malloc(VERT * sizeof(y));
	if (x == NULL || y == NULL)
	{
		printf("Couldn't allocate memory. Exiting.\n");
		exit(EXIT_FAILURE);
	}
	
	/* make a surface */
	
	tmp = SDL_CreateRGBSurface(SDL_HWSURFACE,N,N,32,0,0,0,0);
	if ( tmp == NULL )
	{
		printf("Couldn't create surface. Exiting.\n");
		exit(EXIT_FAILURE);
	}
	
	surf = SDL_DisplayFormat(tmp);
	SDL_FreeSurface(tmp);
	
	/* give it its background color */
	
	SDL_FillRect(surf,NULL, SDL_MapRGB(surf->format,dna[LEN-3],dna[LEN-2],dna[LEN-1]));
	
	/* and fill it with stuff */
	
	for (i = 0; i < GONS; i += 1)
	{
		Uint8 r,g,b,a;

		int j;
		
		r = dna[i*GONLEN];
		g = dna[i*GONLEN + 1];
		b = dna[i*GONLEN + 2];
		a = dna[i*GONLEN + 3] / 255.0 * 30 + 30; /* alpha between 30 and 60 */
		
		for (j = 0 ; j < VERT; j += 1)
		{
			x[j] = dna[i*GONLEN + 4 + 2*j];
			y[j] = dna[i*GONLEN + 4 + 2*j + 1];
		}
		
		filledPolygonRGBA(surf, x, y, VERT, r, g, b, a);
	}
	
	return surf;
}

/* returns 1 if equal, 0 if black and white */
double compare_imgs(SDL_Surface *ima, SDL_Surface *imb)
{
	int i,j;
	Uint32 pixa, pixb;
	Uint8 r,g,b;
	Uint8 rr,gg,bb;
	
	double sum = 0;

	for (i = 0; i < N; i += 1)
	for (j = 0; j < N; j += 1)
	{
		double dr, dg, db;
		pixa = getpixel(ima,i,j);
		pixb = getpixel(imb,i,j);
		
		SDL_GetRGB(pixa, ima->format, &r, &g, &b);
		SDL_GetRGB(pixb, imb->format, &rr, &gg, &bb);
		
		dr = (r - rr);
		dg = (g - gg);
		db = (b - bb);
		
		sum += 0.4*dr*dr + 0.45*dg*dg + 0.15*db*db;
	}
	return (N*N*255.0*255.0)/sum;	/* 65025 is the max value for one pixel */
}

double fitness(Uint8 *dna, SDL_Surface *target)
{
	SDL_Surface *raster;
	double diff;
	
	raster = raster_dna(dna);
	diff = compare_imgs(raster,target);
	
	SDL_FreeSurface(raster);
	
	return diff;
}

/*
 * Return the pixel value at (x, y)
 * NOTE: The surface must be locked before calling this!
 */
Uint32 getpixel(SDL_Surface *surface, int x, int y)
{
    int bpp = surface->format->BytesPerPixel;
    /* Here p is the address to the pixel we want to retrieve */
    Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;

    switch (bpp) {
    case 1:
        return *p;

    case 2:
        return *(Uint16 *)p;

    case 3:
        if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
            return p[0] << 16 | p[1] << 8 | p[2];
        else
            return p[0] | p[1] << 8 | p[2] << 16;

    case 4:
        return *(Uint32 *)p;

    default:
        return 0;       /* shouldn't happen, but avoids warnings */
    } // switch
}

Uint8 *step_uphill(Uint8 *dna, SDL_Surface *target)
{
	int byte;
	Uint8 *dup;
	double fit;
	char *grad;
	
	fit = fitness(dna,target);
	
	dup = dup_dna(dna);
	
	/* make a table for the gradient, inited to 0 */
	
	grad = (char *)calloc(LEN,sizeof(grad));
	if ( grad == NULL )
	{
		printf("Couldn't Allocate memory. Exiting.\n");
		exit(EXIT_FAILURE);
	}
	
	/* compute gradient: for each byte, try adding one and see if fitness increases */
	for (byte = 0; byte < LEN; byte += 1)
	{	
		double newfit;
		int dir;
		
		dir = rand() % 5 - 2;
		
		dup[byte] += dir;
		newfit = fitness(dup,target);
		
		grad[byte] += newfit > fit ? dir : -dir;

		/* set it back for the next calculations */
		dup[byte] -= dir;
	}

	/* and add the gradient */
	for (byte = 0; byte < LEN; byte += 1)
	{
		int try = dup[byte] + grad[byte];
		if (try < 256 && try >= 0)
			dup[byte] = try;
	}

	free(grad);
	
	return dup;
}

Agent *make_pool(int pop, SDL_Surface *target)
{
	Agent *pool;
	int i;
		
	pool = malloc(pop * sizeof(Agent));
	if(pool == NULL)
	{
		printf("Couldn't allocate memory, exiting.\n");
		exit(EXIT_FAILURE);
	}
	
	for (i = 0; i < pop; i += 1)
	{
		pool[i].dna = make_rand_dna();
		pool[i].fit = fitness(pool[i].dna, target);
	}	
	
	/* sort it */
	qsort(pool, pop, sizeof(pool[0]), agent_comp);
	
	return pool;
}

int agent_comp(const void* a, const void* b)
{	
	Agent *x,*y;
	
	x = (Agent *)a;
	y = (Agent *)b;

	if (x->fit == y->fit)
		return 0;
	else if (x->fit > y->fit)
		return 1;
	else
		return -1;
}

void breed_pool(Agent *pool, int pop, double loss, double newrand, SDL_Surface *target)
{
	int i;
	int kills = (int)(pop*loss);
	int randbabies = (int)(pop*newrand);


	/* kill the less fit */
	for (i = 0; i < kills; i += 1)
	{
		free(pool[i].dna);
		pool[i].fit = 0;
	}
	/*printf("Killed %d less fit\n", kills);*/
	
	/* make a few random new ones */
	for (i = 0; i < randbabies; i += 1)
	{
		pool[i].dna = make_rand_dna();
		pool[i].fit = fitness(pool[i].dna, target);		
	}
	/*printf("Created %d random ones\n", randbabies);*/
	
	/* breed the rest from our champions */
	for (i = randbabies; i < kills; i += 1)
	{
		/* select two random champions */
		int a,b, cross;
		int byte;
		
		a = rand() % (pop - 1 - kills) + kills;
		b = rand() % (pop - 1 - kills) + kills;
		cross = rand() % LEN;
		
		pool[i].dna = make_dna();
		
		/* get a part from each parent */
		
		for (byte = 0; byte < cross; byte += 1)
		{
			pool[i].dna[byte] = pool[a].dna[byte];
		}
		for (byte = cross; byte < LEN; byte += 1)
		{
			pool[i].dna[byte] = pool[b].dna[byte];
		}
		
		pool[i].fit = fitness(pool[i].dna,target);
			
	}
	/*printf("Breeded %d\n", kills - randbabies);*/
	
	/* sort it */
	qsort(pool, pop, sizeof(pool[0]), agent_comp);
}

Agent *breed_pool2(Agent *pool, int pop, double newrand, SDL_Surface *target)
{
	int i;
	int randbabies = (int)(pop*newrand);
	Agent *newpool;
	
	newpool = malloc(pop * sizeof(Agent));
	if(newpool == NULL)
	{
		printf("Couldn't allocate memory, exiting.\n");
		exit(EXIT_FAILURE);
	}
	
	/* make a few random new ones */
	for (i = 0; i < randbabies; i += 1)
	{
		newpool[i].dna = make_rand_dna();
		newpool[i].fit = fitness(newpool[i].dna, target);		
	}

	/* breed the rest from our champions */
	for (i = randbabies; i < pop - randbabies; i += 1)
	{
		/* select two random champions */
		int cross, middlecross;
		int byte;
		double a,b;
		
		a = (rand() % 100000) / (100000.0-1);
		a = sqrt(sqrt(a))*(pop-1);
		b = (rand() % 100000) / (100000.0-1);
		b = sqrt(sqrt(b))*(pop-1);		
		
		/*printf("Chosen %d %d",(int)a,(int)b);*/
		
		cross = rand() % LEN;
		middlecross = rand() % 8;
		
		newpool[i].dna = make_dna();
		
		/* get a part from each parent */
		
		for (byte = 0; byte < cross; byte += 1)
		{
			newpool[i].dna[byte] = pool[(int)a].dna[byte];
		}
		newpool[i].dna[cross] = ( pool[(int)a].dna[byte] >> (8-1-middlecross) ) << (8-1-middlecross) | (pool[(int)b].dna[byte] << (middlecross+1)) >> (middlecross+1);
		for (byte = cross + 1; byte < LEN; byte += 1)
		{
			newpool[i].dna[byte] = pool[(int)b].dna[byte];
		}
		
		newpool[i].fit = fitness(newpool[i].dna,target);
			
	}
	
	/* pick a few directly from the old pool */
	/* with more chance in the most fit */
	/* use CDC = x^2 */
	
	for (i = pop - randbabies; i < pop; i += 1)
	{
		double r;
		
		r = (rand() % 100000) / (100000.0-1);
		r = sqrt(sqrt(r))*(pop-1);
		
		/* always take the best one */
		if (i == pop - 1)
			r = pop - 1;
				
		if (pool[(int)r].dna != NULL)
		{
			newpool[i].dna = pool[(int)r].dna;
			pool[(int)r].dna = NULL;
		}
		else
			newpool[i].dna = make_rand_dna();
	}

	/* apply some mutations */
	
	for (i = 0; i < pop; i += 1)
	{
		if (rand()%3 == 0)
			newpool[i].dna[rand()%LEN] ^= rand() % 256;
	}

	
	/* delete old pool */
	/* beware of the dnas we copied */
	
	for (i = 0; i < pop; i += 1)
	{
		if (pool[i].dna != NULL)
			free(pool[i].dna);
	}
	free(pool);
		
	/* sort it */
	qsort(newpool, pop, sizeof(newpool[0]), agent_comp);

	return newpool;
}
