#include "example7.h"

#define NUM_CIRCLES 6
#define CIRCLE_DIAMETER 60.0

using namespace std;

RatPhysicsExample7::RatPhysicsExample7(string name): RatPhysicsExample(name) {}
RatPhysicsExample7::RatPhysicsExample7(const char *name): RatPhysicsExample(name) {}
RatPhysicsExample7::RatPhysicsExample7(char *name): RatPhysicsExample(name) {}

bool RatPhysicsExample7::InitWorld()
{
	SDL_WM_SetCaption(title.c_str(),NULL);

	aabb space={{0,0},{bounds.x,bounds.y}};
	vector2 cell_size={150,150};
	vector2 gravity={0,12};

	world=rat_world_create(space,rat_integrator_euler,10,
		rat_body_manager_type_quad_tree,&cell_size);

	rat_world_set_body_left_world_callback(world,rat_examples_leave_world_callback,this);

	rat_world_set_gravity(world,gravity);
	rat_world_set_damping(world,1.0);

	rat_examples_create_walls(world);

	vector2 anchpos={0,0};
	rat_body *anchor=rat_body_create(rat_hull_particle_create(anchpos),0.0,0.0,0.0,0.0);
	rat_world_add_body(world,anchor);

	register unsigned int i;
	register rat_real halfwidth=(CIRCLE_DIAMETER/2.0)*NUM_CIRCLES;
	rat_real radius=CIRCLE_DIAMETER*0.5;

	for (i=0; i<NUM_CIRCLES; i++)
	{
		vector2 center={bounds.x*0.5-halfwidth+CIRCLE_DIAMETER*i+radius,CIRCLE_DIAMETER+bounds.y*0.25};
		rat_hull *circ=rat_hull_circle_create(center,radius);

		rat_body *body=rat_body_create(circ,1.0,0.0,rat_area_circle(radius),0.0);
		if (i==0) body->velocity.x=-40.0;

		vector2 zerovec={0,0};
		vector2 anchvec={rat_hull_get_pos(body->hull).x,0};

		rat_world_add_body(world,body);
		rat_world_add_constraint(world,rat_constraint_bar_create(body,anchor,zerovec,anchvec));
	}

	return (bool)world;
}

bool RatPhysicsExample7::UpdateWorld(rat_real timestep)
{
	timestep=timestep>2.0?2.0:timestep;
	rat_world_update(world,timestep*0.05,timestep<=1.0?1:0);

	return true;
}

bool RatPhysicsExample7::UpdateVisuals()
{
	rat_draw_world(world,show_quadtree,show_arbiters,show_aabbs);
	return true;
}

bool RatPhysicsExample7::FreeWorld()
{
	rat_world_free_entities(world);
	rat_world_destroy(world);

	return true;
}
