goat3d

view 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 source
1 #include <algorithm>
2 #include <string.h>
3 #include "node.h"
5 Node::Node()
6 {
7 parent = 0;
8 }
10 Node::~Node()
11 {
12 }
14 void Node::set_name(const char *name)
15 {
16 this->name = name;
17 }
19 const char *Node::get_name() const
20 {
21 return name.c_str();
22 }
24 void Node::add_child(Node *c)
25 {
26 // make sure we don't add it twice
27 if(std::find(children.begin(), children.end(), c) != children.end()) {
28 return;
29 }
30 children.push_back(c);
31 c->parent = this;
32 }
34 int Node::get_num_children() const
35 {
36 return (int)children.size();
37 }
39 Node *Node::get_child(int idx) const
40 {
41 if(idx < 0 || idx >= get_num_children()) {
42 return 0;
43 }
44 return children[idx];
45 }
47 Node *Node::get_child(const char *name) const
48 {
49 for(size_t i=0; i<children.size(); i++) {
50 if(strcmp(children[i]->get_name(), name) == 0) {
51 return children[i];
52 }
53 }
54 return 0;
55 }
57 Node *Node::get_descendant(const char *name) const
58 {
59 Node *c = get_child(name);
60 if(c) {
61 return c;
62 }
64 // depth first search might not be ideal in this case, but it's the simplest
65 for(size_t i=0; i<children.size(); i++) {
66 if((c = children[i]->get_descendant(name))) {
67 return c;
68 }
69 }
70 return 0;
71 }
73 Node *Node::get_parent() const
74 {
75 return parent;
76 }
78 Node *Node::get_ancestor(const char *name) const
79 {
80 Node *n = (Node*)this;
82 if(!name) {
83 // just return the root
84 while(n->parent) {
85 n = n->parent;
86 }
87 return n;
88 }
90 // otherwise we're looking for a specific ancestor
91 while(n && strcmp(n->get_name(), name) != 0) {
92 n = n->parent;
93 }
94 return n;
95 }