#include "ai.h"
#include <string>

AI_SHADER_NODE_EXPORT_METHODS(apUvRange)

enum apUvRangeParams {
	p_umin,
	p_umax,
	p_vmin,
	p_vmax,
	p_in_color,
	p_out_color
};

struct ShaderData
{
	float umin;
	float umax;
	float vmin;
	float vmax;
	AtRGB in_range;
	AtRGB out_range;
};

node_parameters
{
	AiParameterFlt("u_min", 0.0);
	AiParameterFlt("u_max", 1.0);
	AiParameterFlt("v_min", 0.0);
	AiParameterFlt("v_max", 1.0);
	AiParameterRGB("in_range", 1.0, 0, 0);
	AiParameterRGB("out_range", 0, 1.0, 0);
}

node_initialize
{
	ShaderData *data = (ShaderData*) AiMalloc(sizeof(ShaderData));
	AiNodeSetLocalData(node, data);
}

node_update
{
	ShaderData *data = (ShaderData *)AiNodeGetLocalData(node);
	data->umin = AiNodeGetFlt(node, "u_min");
	data->umax = AiNodeGetFlt(node, "u_max");
	data->vmin = AiNodeGetFlt(node, "v_min");
	data->vmax = AiNodeGetFlt(node, "v_max");
	data->in_range = AiNodeGetRGB(node, "in_range");
	data->out_range = AiNodeGetRGB(node, "out_range");
	data->umin = AiNodeGetFlt(node, "u_min");
}
node_finish
{
	ShaderData *data = (ShaderData *)AiNodeGetLocalData(node);
	AiFree(data);
}

shader_evaluate
{
	ShaderData *data = (ShaderData *)AiNodeGetLocalData(node);
	if (sg->u >= data->umin && sg->u <= data->umax && 
		sg->v >= data->vmin && sg->v <= data->umax) 
	{
		sg->out.RGB() = data->in_range;
		return;
	}
	sg->out.RGB() = data->out_range;
	return;
}

node_loader
{
	if (i > 0)
		return false;

	node->methods = apUvRange;
	node->output_type = AI_TYPE_RGBA;
	node->name = "apUvRange";
	node->node_type = AI_NODE_SHADER;
	strcpy(node->version, AI_VERSION);
	return true;
}