/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include "SDL.h"

/* Globals */

int nbx, nby;
float lx, ly, k, m, frot, dt;

int dragging = 0;
int dragged;

int fixed[8];

struct Mass
{
	float x,y;		/* In pixels */
	float vx, vy;	/* In pixels per frame */
	float ax, ay;	/* In pixels per frame^2 */
	float m;		/* mass in whatever... */
	
	
};

void IteratePhysics(struct Mass **grid);
float Distance(struct Mass *a, struct Mass *b);
float Xshift(struct Mass *a, struct Mass *b);
float Yshift(struct Mass *a, struct Mass *b);
void Force(struct Mass *a, struct Mass *b, float k, float l, float *fx, float *fy);

void PrintScene(SDL_Surface *screen, struct Mass **grid);
void DrawLine(int ax, int ay, int bx, int by, SDL_Surface *screen);

/*--------------[Main]-------------*/

int main(int argc, char **argv)
{
	struct Mass **grid;
	
	int i, j, count;
	
	int stop;

	
	SDL_Surface *screen;
	SDL_Event event;
	
	/* Reading arguments */
	
	printf("Elasto starting\n");
	
	if (argc < 8)
	{
		printf("Usage : elasto nbx nby lx ly k m frot\n");
		exit(EXIT_FAILURE);
	}
	
	nbx = atoi(argv[1]);
	nby = atoi(argv[2]);
	
	lx = atof(argv[3]);
	ly = atof(argv[4]);
	
	k = atof(argv[5]);
	
	m = atof(argv[6]);
	frot = atof(argv[7]);
	
	printf("Using : %d %d , %f %f, %f, %f\n", nbx, nby, lx, ly, k, m);
	
	dt = 0.1;
	
	fixed[0] = 799;
	fixed[1]= 0;
	
	fixed[2] = 0;
	fixed[3] = 0;
		
	fixed[4] = 799;
	fixed[5] = 599;
	
	fixed[6] = 0;
	fixed[7] = 599;
	
	/* Preparing stuff */
	
	/*------
	printf("sizeof *grid : %d\n sizeof grid : %d\n", sizeof(*grid), sizeof(grid));
	printf("sizeof **grid : %d\n sizeof struct Mass : %d\n", sizeof(**grid), sizeof(struct Mass));
	------*/
	
	grid = malloc(nbx * nby * sizeof(*grid));
	if (grid == NULL)
	{
		printf("Couldn't allocate memory, exiting...\n");
		exit(EXIT_FAILURE);
	}
	
	for (i=0 ; i < nbx ; i++)
		for (j=0 ; j < nby ; j++)
		{
			grid[i + j*nbx] = malloc(sizeof(struct Mass));
			if (grid[i + j*nbx] == NULL)
			{
				printf("Couldn't allocate memory, exiting...\n");
				exit(EXIT_FAILURE);
			}
			
			grid[i + j*nbx]->x = lx + i*lx;
			grid[i + j*nbx]->y = ly + j*ly;
			
			grid[i + j*nbx]->vx = 0;
			grid[i + j*nbx]->vy = 0;
			grid[i + j*nbx]->ax = 0;
			grid[i + j*nbx]->ay = 0;
			
			grid[i + j*nbx]->m = m;
		}
	
	/* Worrying about SDL */
		
	if ( SDL_Init(SDL_INIT_VIDEO) < 0 )
	{
                fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
                exit(1);
        }
	
	/* Set 800x600 video mode */
        screen=SDL_SetVideoMode(800,600,16, SDL_SWSURFACE);
        if (screen == NULL)
	{
                fprintf(stderr, "Couldn't set 800*600x%d video mode: %s\n", 16, SDL_GetError());
                SDL_Quit();
                exit(2);
        }
		
		
	/* Starting simulation */
	
	grid[5]->y = 50;
	
	stop = 0;
	count = 0;
	while(!stop)
	{
		while ( SDL_PollEvent(&event) )
		{
			if (event.type == SDL_QUIT)
			{
				stop = 1;
			}
			if (event.type == SDL_MOUSEBUTTONDOWN)
			{
				for( i=0 ; i < nbx*nby && !dragging; i++)
				{
					if ( abs(event.button.x - grid[i]->x) <= 3 && abs(event.button.y - grid[i]->y) <= 3)
					{
						dragging = 1;
						dragged = i;
					}
					
				}
				
			}
			if (event.type == SDL_MOUSEBUTTONUP)
				dragging = 0;
		}
				
		printf("Oh yeah %d\n", count);
		IteratePhysics(grid);
		
		PrintScene(screen, grid);
		
		count++;
	}
	

	/* Cleaning a little bit */
		
	for (i=0 ; i < nbx*nby ; i++)
		free(grid[i]);
	
	free(grid);
	
	SDL_Quit();
	
	printf("Ok, good bye.\n");
	
	return 0;
}

/*--------------[IteratePhysics]-------------*/

void IteratePhysics(struct Mass **grid)
{
	int i,j;
	float fxt, fyt, fx, fy;
	
	/* Computing forces */
	
	for (i=0 ; i < nbx ; i++)
		for (j=0 ; j < nby ; j++)
		{
			fxt = fyt = fx = fy = 0;
			
			if (i>0)
			{
				Force(grid[i-1 + j*nbx], grid[i + j*nbx], k, lx, &fx, &fy);
				fxt += fx;
				fyt += fy;
			}
			if (i < (nbx-1))
			{
				Force(grid[i+1 + j*nbx], grid[i + j*nbx], k, lx, &fx, &fy);
				fxt += fx;
				fyt += fy;
			}
			
			if (j>0)
			{
				Force(grid[i + (j-1)*nbx], grid[i + j*nbx], k, ly, &fx, &fy);
				fxt += fx;
				fyt += fy;
			}
			if (j < (nby-1))
			{
				Force(grid[i + (j+1)*nbx], grid[i + j*nbx], k, ly, &fx, &fy);
				fxt += fx;
				fyt += fy;
			}
			
			/* transversales */
			
			if (i>0 && j>0)
			{
				Force(grid[(i-1) + (j-1)*nbx],grid[i + j*nbx], k, lx*sqrt(2), &fx, &fy);
				fxt += fx;
				fyt += fy;
			}
			if (i>0 && j < (nby-1))
			{
				Force(grid[(i-1) + (j+1)*nbx], grid[i + j*nbx], k, lx*sqrt(2), &fx, &fy);
				fxt += fx;
				fyt += fy;
			}
			if (i < (nbx - 1) && j>0)
			{
				Force(grid[(i+1) + (j-1)*nbx], grid[i + j*nbx], k, lx*sqrt(2), &fx, &fy);
				fxt += fx;
				fyt += fy;
			}
			if (i < (nbx - 1) && j < (nby-1) )
			{
				Force(grid[(i+1) + (j+1)*nbx], grid[i + j*nbx], k, lx*sqrt(2), &fx, &fy);
				fxt += fx;
				fyt += fy;
			}
			
			grid[i + j*nbx]->ax = fxt / grid[i + j*nbx]->m - frot * grid[i + j*nbx]->vx;
			grid[i + j*nbx]->ay = fyt / grid[i + j*nbx]->m - frot * grid[i + j*nbx]->vy;
		}
		
	/* Computing new positions */	
	
	for (i=0 ; i < nbx ; i++)
		for (j=0 ; j < nby ; j++)
		{
			grid[i + j*nbx]->vx += grid[i + j*nbx]->ax * dt;
			grid[i + j*nbx]->vy += grid[i + j*nbx]->ay * dt;
			
			grid[i + j*nbx]->x += grid[i + j*nbx]->vx * dt;
			grid[i + j*nbx]->y += grid[i + j*nbx]->vy * dt;
			
		}
	
	/* Fixed positions */
		
	if (dragging)
	{
		int x,y;
		SDL_GetMouseState(&x, &y);
		
		
		if (dragged == 0)
		{
			fixed[0] = x;
			fixed[1] = y;
		}
		else if (dragged == nbx - 1)
		{
			fixed[2] = x;
			fixed[3] = y;
		}
		else if (dragged == (nbx - 1)*nby)
		{
			fixed[4] = x;
			fixed[5] = y;
		}
		else if (dragged == nbx*nby - 1)
		{
			fixed[6] = x;
			fixed[7] = y;
		}
		
		grid[dragged]->x = x;
		grid[dragged]->y = y;
	}
	
	
	grid[0]->x = fixed[0];
	grid[0]->y = fixed[1];
	
	grid[nbx -1]->x =fixed[2];
	grid[nbx -1]->y = fixed[3];
		
	grid[(nbx -1)*nby]->x = fixed[4];
	grid[(nbx -1)*nby]->y = fixed[5];
	
	grid[nby*nbx - 1]->x = fixed[6];
	grid[nby*nbx - 1]->y = fixed[7];
	
	return;
}

float Distance(struct Mass *a, struct Mass *b)
{
	return( sqrt ((a->x - b->x)*(a->x - b->x) + (a->y - b->y)*(a->y - b->y)) );
}

float Xshift(struct Mass *a, struct Mass *b)	/* xb-xa ! */
{
	return ( (float)(b->x - a->x) );
}

float Yshift(struct Mass *a, struct Mass *b)	/* yb-ya ! */
{
	return ( (float)(b->y - a->y) );
}

void Force(struct Mass *a, struct Mass *b, float k, float l, float *fx, float *fy)	/* Force given to b by a */
{
	float f, d;
	
	f = - k * (Distance(a, b)-l);
	d = Distance(a,b);

	*fx = f * Xshift(a,b) / d;
	*fy = f * Yshift(a,b) / d;
	
	return;
}

void PrintScene(SDL_Surface *screen, struct Mass **grid)
{
	SDL_Rect rect;
	int i,j;
	
	SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 255, 255, 255));
	
	rect.w = rect.h = 5;
	
	for (i=0 ; i < nbx ; i++)
		for (j=0 ; j < nby ; j++)
		{
			rect.x = (int) grid[i + j*nbx]->x - 2;
			rect.y = (int) grid[i + j*nbx]->y - 2;
			
			rect.w = rect.h = 5;
			
			SDL_FillRect(screen, &rect, SDL_MapRGB(screen->format, 255, 0, 255));
			
			if ( i < nbx-1)
			{
				DrawLine(grid[i + j*nbx]->x, grid[i + j*nbx]->y, grid[i+1 + j*nbx]->x, grid[i+1 + j*nbx]->y, screen);
			}
			if ( j < nby-1)
			{
				DrawLine(grid[i + j*nbx]->x, grid[i + j*nbx]->y, grid[i + (j+1)*nbx]->x, grid[i + (j+1)*nbx]->y, screen);
			}
			if ( i < nbx-1 &&  j < nby-1)
			{
				DrawLine(grid[i + j*nbx]->x, grid[i + j*nbx]->y, grid[i+1 + (j+1)*nbx]->x, grid[i+1 + (j+1)*nbx]->y, screen);
			}
			if ( i > 0 &&  j < nby-1)
			{
				DrawLine(grid[i + j*nbx]->x, grid[i + j*nbx]->y, grid[i-1 + (j+1)*nbx]->x, grid[i-1 + (j+1)*nbx]->y, screen);
			}
			
			
		}
	
	SDL_Flip(screen);
	return;	
}

void DrawLine(int ax, int ay, int bx, int by, SDL_Surface *screen)
{
	int n,i;
	
	SDL_Rect rect;
	
	n = abs(ax-bx) < abs(ay-by) ? abs(ay-by) : abs(ax-bx) ;
	
	if (n==0)
		return;
	
	for (i=0 ; i <= n ; i++)
	{
		rect.w = rect.h = 1;
		rect. x = ax + i * (bx-ax) / n;
		rect. y = ay + i * (by-ay) / n;
		
		SDL_FillRect(screen, &rect, SDL_MapRGB(screen->format, 0, 255, 255));
	}
	
	return;
}
