00001 #include <stdlib.h>
00002 #include <vector>
00003
00004 #include "../BehaviorBase.h"
00005 #include "../../SoundPlay/SoundManager.h"
00006 #include "../StateNode.h"
00007 #include "RandomTrans.h"
00008
00009
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();
00036 if ( sound.size()!=0 )
00037 sndman->PlayFile(sound);
00038
00039 for(size_t i=0; i<srcs.size(); i++)
00040 if(srcs[i]->isActive())
00041 srcs[i]->DoStop();
00042
00043 float weightsum = 0;
00044 for (size_t i = 0; i < dsts.size(); i++)
00045 weightsum += weights[i];
00046 if (weightsum == 0)
00047 std::cerr << getName() << " has no non-zero-weighted destinations!" << std::endl;
00048 else {
00049 const float randval = weightsum * (rand()/(RAND_MAX+1.0));
00050 float s = weights[0];
00051 for (size_t i = 0; i < dsts.size(); s+=weights[++i])
00052 if (randval <= s) {
00053 if (!dsts[i]->isActive())
00054 dsts[i]->DoStart();
00055 break;
00056 };
00057 }
00058
00059 RemoveReference();
00060 }
00061