coeng
annotate src/gameobj.cc @ 2:4a1c9597f4d3
foo
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Thu, 05 Feb 2015 11:04:07 +0200 |
parents | b0d8d454c546 |
children |
rev | line source |
---|---|
nuclear@2 | 1 #include <stdio.h> |
nuclear@1 | 2 #include <algorithm> |
nuclear@1 | 3 #include "gameobj.h" |
nuclear@1 | 4 |
nuclear@1 | 5 GameObject::GameObject() |
nuclear@1 | 6 { |
nuclear@1 | 7 sorted = true; |
nuclear@1 | 8 } |
nuclear@1 | 9 |
nuclear@1 | 10 GameObject::~GameObject() |
nuclear@1 | 11 { |
nuclear@1 | 12 for(size_t i=0; i<comp.size(); i++) { |
nuclear@1 | 13 delete comp[i]; |
nuclear@1 | 14 } |
nuclear@1 | 15 } |
nuclear@1 | 16 |
nuclear@1 | 17 bool GameObject::add_component(Component *c) |
nuclear@1 | 18 { |
nuclear@1 | 19 const char *name = c->get_name(); |
nuclear@1 | 20 |
nuclear@1 | 21 if(comp_by_name.find(name) != comp_by_name.end()) { |
nuclear@1 | 22 fprintf(stderr, "component %s already exists in this game object (%p)\n", name, (void*)this); |
nuclear@1 | 23 return false; |
nuclear@1 | 24 } |
nuclear@1 | 25 |
nuclear@1 | 26 try { |
nuclear@1 | 27 comp.push_back(c); |
nuclear@1 | 28 comp_by_name[name] = c; |
nuclear@2 | 29 |
nuclear@2 | 30 c->gobj = this; |
nuclear@1 | 31 } |
nuclear@1 | 32 catch(...) { |
nuclear@1 | 33 fprintf(stderr, "failed to add component: %s\n", name); |
nuclear@1 | 34 return false; |
nuclear@1 | 35 } |
nuclear@1 | 36 |
nuclear@1 | 37 sorted = false; |
nuclear@1 | 38 return true; |
nuclear@1 | 39 } |
nuclear@1 | 40 |
nuclear@1 | 41 bool GameObject::remove_component(Component *c) |
nuclear@1 | 42 { |
nuclear@1 | 43 for(size_t i=0; i<comp.size(); i++) { |
nuclear@1 | 44 if(comp[i] == c) { |
nuclear@1 | 45 comp.erase(comp.begin() + i); |
nuclear@1 | 46 comp_by_name.erase(c->get_name()); |
nuclear@1 | 47 return true; |
nuclear@1 | 48 } |
nuclear@1 | 49 } |
nuclear@1 | 50 return false; |
nuclear@1 | 51 } |
nuclear@1 | 52 |
nuclear@1 | 53 bool GameObject::delete_component(Component *c) |
nuclear@1 | 54 { |
nuclear@1 | 55 if(remove_component(c)) { |
nuclear@1 | 56 delete c; |
nuclear@1 | 57 return true; |
nuclear@1 | 58 } |
nuclear@1 | 59 return false; |
nuclear@1 | 60 } |
nuclear@1 | 61 |
nuclear@1 | 62 Component *GameObject::get_component(const char *name) const |
nuclear@1 | 63 { |
nuclear@1 | 64 std::map<std::string, Component*>::const_iterator it; |
nuclear@1 | 65 if((it = comp_by_name.find(name)) != comp_by_name.end()) { |
nuclear@1 | 66 return it->second; |
nuclear@1 | 67 } |
nuclear@1 | 68 return 0; |
nuclear@1 | 69 } |
nuclear@1 | 70 |
nuclear@1 | 71 void GameObject::update() |
nuclear@1 | 72 { |
nuclear@1 | 73 if(!sorted) { |
nuclear@1 | 74 std::sort(comp.begin(), comp.end()); |
nuclear@1 | 75 } |
nuclear@1 | 76 |
nuclear@1 | 77 for(size_t i=0; i<comp.size(); i++) { |
nuclear@1 | 78 comp[i]->update(); |
nuclear@1 | 79 } |
nuclear@1 | 80 } |