coeng

annotate src/gameobj.cc @ 1:b0d8d454c546

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