#include <cstdio>
#include "world_map_data.h"
#include "density_map.h"

void DensityMap::_get_property_list(List<PropertyInfo> *p_list) const
{
	// p_list->push_back(PropertyInfo(Variant::INT, "world/grid_size"));
	p_list->push_back(PropertyInfo(Variant::OBJECT, "noise", PROPERTY_HINT_RESOURCE_TYPE, "OpenSimplexNoise"));
	p_list->push_back(PropertyInfo(Variant::INT, "rnd_seed"));
	p_list->push_back(PropertyInfo(Variant::OBJECT, "curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"));
	p_list->push_back(PropertyInfo(Variant::OBJECT, "height_map", PROPERTY_HINT_RESOURCE_TYPE, "WorldHeightMap"));
}

bool DensityMap::_get(const StringName &p_name, Variant &r_ret) const
{
	if (p_name == "noise") {
		r_ret = noise;
		return true;
	} else if (p_name == "rnd_seed") {
		r_ret = seed;
		return true;
	} else if (p_name == "curve") {
		r_ret = curve;
		return true;
	} else if (p_name == "height_map") {
		r_ret = height_map;
		return true;
	}

	const String pv = p_name.operator String();
	return false;
}
bool DensityMap::_set(const StringName &p_name, const Variant &p_value)
{
	bool update = false;
	if (p_name == "noise") {
		noise = p_value;
		update = true;
	} else if (p_name == "rnd_seed") {
		seed = p_value;
		update = true;
	} else if (p_name == "curve") {
		curve = p_value;
		update = true;
	} else if (p_name == "height_map") {
		curve = p_value;
		update = true;
	}
	if (update) {
		update_all();
		_change_notify();
	}

	return update;
}

void DensityMap::update_all()
{
	if (!curve.ptr() || !rnd.ptr() || !noise.ptr() || !height_map.ptr())
		return;
	rnd->set_seed(seed);
}
void DensityMap::_bind_methods()
{
	ClassDB::bind_method(D_METHOD("get_population_density", "x", "y"), &DensityMap::get_population_density);
}
float DensityMap::get_population_density(float x, float y)
{
#if 0
	float n = (noise->get_noise_2d(x, y) + 1.0f) * 0.5f;
	float d = curve->interpolate_baked(n);
#endif
	float h = height_map->get_surface_height(x, y);
	if (h < 0.0f || h > max_height)
		return 0.0f;
	float s = height_map->get_base_steepness(x, y);
	if (s > 0.3f)
		return 0.0f;
	float d = 0.0f;
	/* Still use curve for it? */
	if (h < max_height * 0.3f)
		d = 1.0f;
	else
		d = max_height * 0.3f / h;
	return d * s;
}

DensityMap::DensityMap()
{
	rnd.instance();
	seed = rnd->get_seed();
	max_height = 300.0f;
}

DensityMap::~DensityMap()
{
}

