#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "AS3.h"

int* tBuffer;
unsigned int* zBuffer;
float* vertices;

#define ZBUFF_LEN ( resX * resY * sizeof(unsigned int) )

int resX = 0;
int resY = 0;
int nVertices;

AS3_Val initializeScreenBuffers(void* self, AS3_Val args)
{
	AS3_ArrayValue(args, "IntType, IntType", &resX, &resY);
	tBuffer = malloc( resX * resY * sizeof(int) );
	zBuffer = malloc( ZBUFF_LEN );
	return 0;
}

AS3_Val initializeVertexBuffers( void* self, AS3_Val args )
{
	AS3_ArrayValue(args, "IntType", &nVertices);
	vertices = malloc(nVertices * sizeof(float) * 3);
	return 0;
}

AS3_Val getTBufferPointer( void* self, AS3_Val args )
{
	return AS3_Ptr( tBuffer );
}

AS3_Val getVertexBuffer( void* self, AS3_Val args )
{
	return AS3_Ptr( vertices );
}

AS3_Val rasterize( void* self, AS3_Val args )
{
	int ct = 0;
	int length = nVertices*3;
	int pos;
	int x;
	int y;
	int z; 
	int c;

	memset( zBuffer, 0xFF, ZBUFF_LEN );

	for(ct=0; ct < length; ct+=3 ){
		z = (double)vertices[ct+2];
		if(z > 100){
			x = (int)vertices[ct];
			y = (int)vertices[ct+1];
			if(x > 0 && x < resX && y > 0 && y < resY){
				pos = y*resX+x;
				if(z > 0 && z < zBuffer[pos]) {
				  tBuffer[pos] = (200-(int)z/2) & 0xFF;
				  zBuffer[pos] = (unsigned int)z;
				}
			}
		}
	}
	return 0;
}
 
int main()
{
	AS3_Val initializeScreenBuffersMethod = AS3_Function( NULL, initializeScreenBuffers );
	AS3_Val initializeVertexBuffersMethod = AS3_Function( NULL, initializeVertexBuffers );
	AS3_Val getTBufferPointerMethod = AS3_Function( NULL, getTBufferPointer );
	AS3_Val getVertexBufferMethod = AS3_Function( NULL, getVertexBuffer );
	AS3_Val rasterizeMethod = AS3_Function( NULL, rasterize );
	
	AS3_Val result = AS3_Object("initializeScreenBuffers: AS3ValType,initializeVertexBuffers: AS3ValType,getTBufferPointer:AS3ValType,getVertexBuffer:AS3ValType,rasterize:AS3ValType"
								,initializeScreenBuffersMethod,
								initializeVertexBuffersMethod,
								getTBufferPointerMethod,
								getVertexBufferMethod,
								rasterizeMethod);
 
	AS3_Release( initializeScreenBuffersMethod );
	AS3_Release( initializeVertexBuffersMethod );
	AS3_Release( getTBufferPointerMethod );
	AS3_Release( getVertexBufferMethod );
	AS3_Release( rasterizeMethod );
		
	AS3_LibInit( result );
 
	return 0;
}
