Tekkotsu Homepage
Demos
Overview
Downloads
Dev. Resources
Reference
Credits

RandomTrans.cc

Go to the documentation of this file.
00001 #include <stdlib.h>
00002 #include <vector>
00003 
00004 #include "../BehaviorBase.h"
00005 #include "../../Sound/SoundManager.h"
00006 #include "../StateNode.h"
00007 #include "RandomTrans.h"
00008 
00009 // Constructors
00010 
00011 RandomTrans::RandomTrans(StateNode* destination, float weight) :
00012   NullTrans("RandomTrans",destination), weights()
00013    { if (destination!=NULL) addWeight(weight); }
00014 
00015 RandomTrans::RandomTrans(const std::string& name, StateNode* destination, float weight) : 
00016   NullTrans("RandomTrans",name,destination), weights()
00017    { if (destination!=NULL) addWeight(weight); }
00018 
00019 RandomTrans::RandomTrans(const std::string &classname, const std::string &instancename, 
00020        StateNode* destination, float weight) :
00021   NullTrans(classname,instancename,destination), weights()
00022    { if (destination!=NULL) 
00023      addWeight(weight>0 ? weight : 0); }
00024 
00025 void RandomTrans::addDestination(StateNode* destination, float weight) {
00026   NullTrans::addDestination(destination);
00027   addWeight(weight);
00028 }
00029 
00030 void RandomTrans::addWeight(float weight) {
00031   weights.push_back(weight);
00032 }
00033 
00034 void RandomTrans::fire() {
00035   AddReference(); // for safety
00036   
00037   erouter->postEvent(EventBase::stateTransitionEGID,reinterpret_cast<size_t>(this),EventBase::activateETID,0,getName(),1);
00038   
00039   if ( sound.size()!=0 )
00040     sndman->playFile(sound);
00041 
00042   for(size_t i=0; i<srcs.size(); i++)
00043     if(srcs[i]->isActive())  // don't deactivate a non-active node
00044       srcs[i]->DoStop();
00045 
00046   float weightsum = 0;
00047   for  (size_t i = 0; i < dsts.size(); i++)
00048     weightsum += weights[i]; // could check if not in history list, if we had one
00049   if (weightsum == 0)
00050     std::cerr << getName() << " has no non-zero-weighted destinations!" << std::endl;
00051   else {
00052     const float randval = weightsum * (rand()/(RAND_MAX+1.0));
00053     float s = weights[0];
00054     for  (size_t i = 0; i < dsts.size(); s+=weights[++i])
00055       if (randval <= s) {
00056   if (!dsts[i]->isActive())
00057     dsts[i]->DoStart();
00058   break;
00059       };
00060   }
00061 
00062   erouter->postEvent(EventBase::stateTransitionEGID,reinterpret_cast<size_t>(this),EventBase::deactivateETID,0,getName(),0);
00063   
00064   RemoveReference();
00065 }
00066     

Tekkotsu v4.0
Generated Thu Nov 22 00:54:55 2007 by Doxygen 1.5.4