#ifndef BUFFER_H
#define BUFFER_H

#include "../common/structs.h"

extern scene_data* main_scene;

#ifndef FORCE_INLINE
//void flush_object_buffer();
INLINE void flush_color_buffer();
INLINE int array_offset(int x, int y);
INLINE void get_sample(int x, int y, color* c, int* obj);
//INLINE int get_object(int x, int y);
INLINE void get_color(int x, int y, color* c);
INLINE intersect_data* get_idata(int x, int y);
INLINE void set_color(int x, int y, color *c);
//INLINE void get_normal(int x, int y, vector* v);
INLINE intersect_data* get_idata(int x, int y);
INLINE void clear_idata_buffer();

#endif


#ifdef FORCE_INLINE




#include "../common/structs.h"
#include "../common/debug.h"
#include "../common/objects.h"
#include "../common/debug.h"
#include "../common/structs.h"
#include "../common/buffer.h"
#include "../common/colors.h"

extern scene_data* main_scene;




FORCE_INLINE int array_offset(int x, int y)
{
	static int ptr;  //static to avoid redeclaration each call
	printd(INSANE, "Getting offset for: %i, %i\n", x, y);
	ptr = x + y * main_scene->width;
	return ptr;
}


FORCE_INLINE void clear_idata_buffer()
{
	intersect_data *ptr;
	intersect_data *length;

	ptr = main_scene->intersect_buffer;
	length = main_scene->intersect_buffer + 
		main_scene->width*main_scene->height;

	while ( ptr < length)
	{
		ptr->obj_num = NOTHING;
		ptr++;
	}
}


FORCE_INLINE void set_color(int x, int y, color *c)
{
	int offset = array_offset(x, y);
	char *dest_color;
	dest_color = (char*)&main_scene->frame_buffer[offset * 3];

	printd(INSANE, "Writing color %i, %i\n", x, y);
	normalize_color(c);

	*dest_color = (unsigned char)c->r;
	dest_color++;
	*dest_color = (unsigned char)c->g;
	dest_color++;
	*dest_color = (unsigned char)c->b;
}



FORCE_INLINE void flush_color_buffer()
{
	unsigned char* ptr;
	unsigned char* length;

	ptr=main_scene->frame_buffer;
	length=main_scene->frame_buffer + 
		3*sizeof(char)*main_scene->width*main_scene->height;

	while ( ptr < length)
	{
		*ptr=0;
		ptr++;
	}
}


FORCE_INLINE void get_color(int x, int y, color* c)
{
	int offset = array_offset(x, y);
	unsigned char* src_color;
	src_color = &main_scene->frame_buffer[offset*3];

	c->r = *src_color;
	src_color++;
	c->g = *src_color;
	src_color++;
	c->b = *src_color;
}


FORCE_INLINE intersect_data* get_idata(int x, int y)
{
	int offset = array_offset(x, y);
	void *ptr;

	ptr = (void*) (offset*sizeof(intersect_data));
	return &main_scene->intersect_buffer[offset];
}


#endif




#endif
