#include "pw/scene/transform.hpp"
#include "pw/scene/node.hpp"

namespace pw {

transform::transform(node &host)
	: _node(host)
{
	_local.set_identity();
	_global.set_identity();
	_global_inverse.set_identity();
}

void transform::set_local(const matrix4x4 &local)
{
	_local = local;
	update_global_from_local();
	// TODO need to rebuild the transforms: both -> global down and global up
}

void transform::set_global(const matrix4x4 &global)
{
	//TODO need to rebuild **_local** from parent
	_global = global;
	_global_inverse = global.inverse();

	update_local_from_global();
	// TODO need to rebuild the transforms: both -> global down and global up
}

void transform::update_global_from_local()
{
	// update the global transform
	if (_node.is_root()) {
		this->_global = _local;
	} else
	{
		this->_global = _node.parent()->transform().global() * _local;
	}
	_global_inverse = _global.inverse();
}

void transform::update_local_from_global()
{
	_local = (_node.is_root()) ? _global :
								 _node.parent()->transform().global_inverse() * _global;

}

}
