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(destination), weights()
00013    { if (destination!=NULL) addWeight(weight); }
00014 
00015 RandomTrans::RandomTrans(const std::string& name, StateNode* destination, float weight) : 
00016   NullTrans(name,destination), weights()
00017    { if (destination!=NULL) addWeight(weight); }
00018 
00019 void RandomTrans::addDestination(StateNode* destination, float const weight) {
00020   NullTrans::addDestination(destination);
00021   addWeight(weight);
00022 }
00023 
00024 void RandomTrans::addWeight(float weight) {
00025   weights.push_back(weight>0 ? weight : 0);
00026 }
00027 
00028 void RandomTrans::fire() {
00029   addReference(); // for safety
00030   erouter->postEvent(EventBase::stateTransitionEGID,reinterpret_cast<size_t>(this),EventBase::activateETID,0,getName(),1);
00031   
00032   if ( soundFile.size()!=0 )
00033     sndman->playFile(soundFile);
00034 
00035   for(size_t i=0; i<srcs.size(); i++)
00036     if(srcs[i]->isActive())  // don't deactivate a non-active node
00037       srcs[i]->stop();
00038 
00039   float weightsum = 0;
00040   for  (size_t i = 0; i < dsts.size(); i++)
00041     weightsum += weights[i]; // could check if not in history list, if we had one
00042   if (weightsum == 0)
00043     std::cerr << getName() << " has no non-zero-weighted destinations!" << std::endl;
00044   else {
00045     const float randval = weightsum * (rand()/(RAND_MAX+1.f));
00046     float s = weights[0];
00047     for  (size_t i = 0; i < dsts.size(); s+=weights[++i])
00048       if (randval <= s) {
00049   if (!dsts[i]->isActive())
00050     dsts[i]->start();
00051   break;
00052       };
00053   }
00054 
00055   erouter->postEvent(EventBase::stateTransitionEGID,reinterpret_cast<size_t>(this),EventBase::deactivateETID,0,getName(),0);
00056   removeReference();
00057 }
00058     

Tekkotsu v5.1CVS
Generated Mon May 9 04:58:49 2016 by Doxygen 1.6.3