goat3d

diff src/node.cc @ 0:2918358f5e6d

initial commit
author John Tsiombikas <nuclear@member.fsf.org>
date Sat, 17 Aug 2013 16:10:26 +0300
parents
children cd71f0b92f44
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/node.cc	Sat Aug 17 16:10:26 2013 +0300
     1.3 @@ -0,0 +1,95 @@
     1.4 +#include <algorithm>
     1.5 +#include <string.h>
     1.6 +#include "node.h"
     1.7 +
     1.8 +Node::Node()
     1.9 +{
    1.10 +	parent = 0;
    1.11 +}
    1.12 +
    1.13 +Node::~Node()
    1.14 +{
    1.15 +}
    1.16 +
    1.17 +void Node::set_name(const char *name)
    1.18 +{
    1.19 +	this->name = name;
    1.20 +}
    1.21 +
    1.22 +const char *Node::get_name() const
    1.23 +{
    1.24 +	return name.c_str();
    1.25 +}
    1.26 +
    1.27 +void Node::add_child(Node *c)
    1.28 +{
    1.29 +	// make sure we don't add it twice
    1.30 +	if(std::find(children.begin(), children.end(), c) != children.end()) {
    1.31 +		return;
    1.32 +	}
    1.33 +	children.push_back(c);
    1.34 +	c->parent = this;
    1.35 +}
    1.36 +
    1.37 +int Node::get_num_children() const
    1.38 +{
    1.39 +	return (int)children.size();
    1.40 +}
    1.41 +
    1.42 +Node *Node::get_child(int idx) const
    1.43 +{
    1.44 +	if(idx < 0 || idx >= get_num_children()) {
    1.45 +		return 0;
    1.46 +	}
    1.47 +	return children[idx];
    1.48 +}
    1.49 +
    1.50 +Node *Node::get_child(const char *name) const
    1.51 +{
    1.52 +	for(size_t i=0; i<children.size(); i++) {
    1.53 +		if(strcmp(children[i]->get_name(), name) == 0) {
    1.54 +			return children[i];
    1.55 +		}
    1.56 +	}
    1.57 +	return 0;
    1.58 +}
    1.59 +
    1.60 +Node *Node::get_descendant(const char *name) const
    1.61 +{
    1.62 +	Node *c = get_child(name);
    1.63 +	if(c) {
    1.64 +		return c;
    1.65 +	}
    1.66 +
    1.67 +	// depth first search might not be ideal in this case, but it's the simplest
    1.68 +	for(size_t i=0; i<children.size(); i++) {
    1.69 +		if((c = children[i]->get_descendant(name))) {
    1.70 +			return c;
    1.71 +		}
    1.72 +	}
    1.73 +	return 0;
    1.74 +}
    1.75 +
    1.76 +Node *Node::get_parent() const
    1.77 +{
    1.78 +	return parent;
    1.79 +}
    1.80 +
    1.81 +Node *Node::get_ancestor(const char *name) const
    1.82 +{
    1.83 +	Node *n = (Node*)this;
    1.84 +
    1.85 +	if(!name) {
    1.86 +		// just return the root
    1.87 +		while(n->parent) {
    1.88 +			n = n->parent;
    1.89 +		}
    1.90 +		return n;
    1.91 +	}
    1.92 +
    1.93 +	// otherwise we're looking for a specific ancestor
    1.94 +	while(n && strcmp(n->get_name(), name) != 0) {
    1.95 +		n = n->parent;
    1.96 +	}
    1.97 +	return n;
    1.98 +}