
#include <WFX/scene/Node.h>
#include <WFX/renderer/Renderer.h>
#include <WFX/scene/SceneGraphVisitor.h>

using namespace WFX;
using namespace WFX::math;
using namespace WFX::scene;
using namespace WFX::renderer;

using namespace std;

Node::Node() : AbstractNode() {
}

void Node::draw(Renderer* renderer) {
    list<Spatial*>::iterator it;
    for (it = Children.begin();it != Children.end();it++) {
        (*it)->onDraw(renderer);
    }
}

void Node::addChild(Spatial* c) {
    if (c == NULL)
        THROW("tried to add a NULL-Pointer");

    Children.push_back(c);
    c->setParent(this);
}

void Node::destroy() {
    LOG("Node::destroy()");
    //loop through the list and destroy all children
    list<Spatial*>::iterator it;
    for (it = Children.begin();it != Children.end();it++) {
        delete (*it);
    }
}

void Node::updateDown() {
    if (!Dirty) return;
    //call super class
    Spatial::updateDown();
    //update Children
    list<Spatial*>::iterator it;
    for (it = Children.begin();it != Children.end();it++) {
        // call update down on children
        (*it)->updateDown();
        //collect WorldBound
        WorldBound->merge((*it)->getWorldBound());
    }
    Dirty = false;
}

void Node::accept(SceneGraphVisitor& s) {
    s.visitNode(*this);
}

//////////////////////////////////////////////////////////////

GeometryNode::GeometryNode() : AbstractNode() {
    VertexCount = 0;
    Vertices = NULL;
    Normals = NULL;
    Colors = NULL;
    TexCoords = NULL;
    MyMaterial = NULL;
    DrawVertexNormals = false;
}

void GeometryNode::calcModelBound() {
    assert(Vertices != NULL);
    markDirty();
    if (!ModelBound)
        ModelBound = new Sphere();
    ModelBound->computeFromVertices(VertexCount, Vertices);
}

void GeometryNode::updateDown() {
    //call Spatial
    Spatial::updateDown();

    if (!Parent) return;
}

void GeometryNode::setColor(const WFX::scene::Color& c) {
    if (Colors) delete Colors;
    Colors = new Color[VertexCount];
    for (UInt i=0;i<VertexCount;i++) {
        Colors[i] = c;
    }
}

