#include "stdafx.h"




Area3D::Area3D(C VecI2 &xz, Ptr grid_user){
	state = AREA_UNLOADED;
	T.pos.set(xz.x,0,xz.y);
	mat.setPos(Vec(pos.x*World3D.AreaSize(), pos.y, pos.z*World3D.AreaSize()));
	blocks.del();
	img.del();
}

Area3D::~Area3D(){
	blocks.delActor();
	blocks.del();
	img.del();
}


void Area3D::Draw(){
	if (state == AREA_ACTIVE){
		if (blocks.is()){
			switch (Renderer()){
			case RM_PREPARE:{
				blocks.draw(mat);
			}break;
			case RM_BLEND:{
			}break;
			case RM_OVERLAY:{
			}break;
			case RM_SHADOW:{
				//blocks.drawShadow(mat);
			}break;
			case RM_AMBIENT:{

			}break;
			}
		}
	}
}



void Area3D::Save(){
}

void Area3D::Load(){
}

void Area3D::Unload(){
	if (state == AREA_CACHE || state == AREA_ACTIVE){
		state = AREA_UNLOADED;
		blocks.delActor();
		blocks.del();
		img.del();

	}
}

void Area3D::Build(){
	if (state == AREA_UNLOADED){
		if (!img.is()){
			img.createSoft(World3D.AreaSize(), World3D.AreaSize(), World3D.AreaSize(), IMAGE_R8G8B8A8); // create wXh image, R8G8B8A8 type, 0 mipmap
			Generate3D(VecI(pos.x, 0, pos.z), img, S + "Test1", true);
		}

		blocks.create(img.size3().x); // create blocks resolution from the map
		blocks_occlusion.create(2); // create blocks occlusion with 2 blocks range
		// dynamically adjust the blocks
		FREPD(x, img.size3().x){
			FREPD(y, img.size3().y){
				FREPD(z, img.size3().z){
					Color b = img.color3D(x, y, z);
					if (b == GREEN)
						blocks.set(x, y, z, &World3D.matA); // set Brick or null material'
					else if (b == RED)
						blocks.set(x, y, z, &World3D.matB); // set Brick or null material
					else if (b == BLUE)
						blocks.set(x, y, z, &World3D.matC); // set Brick or null material
					//else
					//blocks.set(x, y, z, MaterialPtr(UIDZero)); // set Brick or null material
				}
			}
		}
		// set blocks mesh
		blocks.setMesh(1.0f, &blocks_occlusion, nullptr, VecI2(0, 0),nullptr,NULL,true);
		state = AREA_CACHE;
		img.del();
	}
}

void Area3D::CreatePhysics(){
	if (state == AREA_CACHE){
		state = AREA_ACTIVE;
		blocks.setPhysBody(mat);
		blocks.createActor();
		
	}
}

void Area3D::RemovePhysics(){
	if (state == AREA_UNLOADED || state==AREA_CACHE){
		blocks.delActor();
	}
}


void Area3D::update() {
	if (Time.appTime() > last_update){
		last_update = Time.appTime() + 0.33;
	}
}




