1 #include "event_mgr.hxx"
3 #include <simgear/math/SGMath.hxx>
4 #include <simgear/debug/logstream.hxx>
6 void SGEventMgr::add(const std::string& name, SGCallback* cb,
7 double interval, double delay,
8 bool repeat, bool simtime)
10 // Clamp the delay value to 1 usec, so that user code can use
11 // "zero" as a synonym for "next frame".
12 if(delay <= 0) delay = 0.000001;
14 SGTimer* t = new SGTimer;
15 t->interval = interval;
20 SGTimerQueue* q = simtime ? &_simQueue : &_rtQueue;
36 void SGEventMgr::update(double delta_time_sec)
38 _simQueue.update(delta_time_sec);
40 double rt = _rtProp ? _rtProp->getDoubleValue() : 0;
44 void SGEventMgr::removeTask(const std::string& name)
46 SGTimer* t = _simQueue.findByName(name);
49 } else if ((t = _rtQueue.findByName(name))) {
52 SG_LOG(SG_GENERAL, SG_WARN, "removeTask: no task found with name:" << name);
59 ////////////////////////////////////////////////////////////////////////
61 // This is the priority queue implementation:
62 ////////////////////////////////////////////////////////////////////////
64 SGTimerQueue::SGTimerQueue(int size)
69 while(size > _tableSize)
70 _tableSize = ((_tableSize + 1)<<1) - 1;
72 _table = new HeapEntry[_tableSize];
73 for(int i=0; i<_tableSize; i++) {
80 SGTimerQueue::~SGTimerQueue()
82 for(int i=0; i<_numEntries; i++) {
83 delete _table[i].timer;
92 void SGTimerQueue::update(double deltaSecs)
95 while(_numEntries && nextTime() <= _now) {
96 SGTimer* t = remove();
99 insert(t, t->interval);
106 void SGTimerQueue::insert(SGTimer* timer, double time)
108 if(_numEntries >= _tableSize)
112 _table[_numEntries-1].pri = -(_now + time);
113 _table[_numEntries-1].timer = timer;
115 siftUp(_numEntries-1);
118 SGTimer* SGTimerQueue::remove(SGTimer* t)
121 for(entry=0; entry<_numEntries; entry++)
122 if(_table[entry].timer == t)
124 if(entry == _numEntries)
127 // Swap in the last item in the table, and sift down
128 swap(entry, _numEntries-1);
135 SGTimer* SGTimerQueue::remove()
137 if(_numEntries == 0) {
139 } else if(_numEntries == 1) {
141 return _table[0].timer;
144 SGTimer *result = _table[0].timer;
145 _table[0] = _table[_numEntries - 1];
151 void SGTimerQueue::siftDown(int n)
153 // While we have children bigger than us, swap us with the biggest
155 while(lchild(n) < _numEntries) {
156 int bigc = lchild(n);
157 if(rchild(n) < _numEntries && pri(rchild(n)) > pri(bigc))
159 if(pri(bigc) <= pri(n))
166 void SGTimerQueue::siftUp(int n)
168 while((n != 0) && (_table[n].pri > _table[parent(n)].pri)) {
175 void SGTimerQueue::growArray()
177 _tableSize = ((_tableSize+1)<<1) - 1;
178 HeapEntry *newTable = new HeapEntry[_tableSize];
179 for(int i=0; i<_numEntries; i++) {
180 newTable[i].pri = _table[i].pri;
181 newTable[i].timer = _table[i].timer;
187 SGTimer* SGTimerQueue::findByName(const std::string& name) const
189 for (int i=0; i < _numEntries; ++i) {
190 if (_table[i].timer->name == name) {
191 return _table[i].timer;