kick
/Users/morten/Programmering/cpp/kick/src/kick/core/event_queue.cpp
00001 //
00002 // Created by Morten Nobel-Jørgensen on 27/10/14.
00003 //
00004 
00005 #include "event_queue.h"
00006 
00007 #include <algorithm>
00008 #include <cassert>
00009 #include "time.h"
00010 
00011 using namespace std;
00012 
00013 namespace kick{
00014     int EventQueue::scheduleEvent(std::function<void(int)> &&fn, float timeStart, float timeEnd) {
00015         assert(timeEnd >= timeStart);
00016         float time = Time::total();
00017         int id = ++queueCounter;
00018         if (updating){
00019             updatingQueue.emplace_back(std::move(fn), time+timeStart, time+timeEnd,id);
00020         } else {
00021             queue.emplace_back(std::move(fn), time+timeStart, time+timeEnd,id);
00022         }
00023         return id;
00024     }
00025 
00026     bool EventQueue::cancelEvent(int eventid) {
00027         auto found = std::find_if(queue.begin(), queue.end(), [&](EventQueueEntry& e){
00028             return e.eventid == eventid;
00029         });
00030         if (found != queue.end()){
00031             found->cancelled = true;
00032             return true;
00033         }
00034         return false;
00035     }
00036 
00037     void EventQueue::run() {
00038         updating = true;
00039         float time = Time::total();
00040 
00041         for (auto e : queue){
00042             if (e.timeStart < time && !e.cancelled){
00043                 e.fn(e.eventid);
00044             }
00045         }
00046         auto erase = std::remove_if(queue.begin(), queue.end(), [&](EventQueueEntry& e){
00047             return e.timeEnd < time || e.cancelled;
00048         });
00049         queue.erase(erase, queue.end());
00050         updating = false;
00051 
00052         for (auto e : updatingQueue){
00053             queue.emplace_back(std::move(e.fn), e.timeStart, e.timeEnd,e.eventid);
00054         }
00055         updatingQueue.clear();
00056     }
00057 
00058     EventQueueEntry::EventQueueEntry(std::function<void(int)>&& fn,float timeStart,float timeEnd,int eventid)
00059     : fn(fn), timeStart(timeStart), timeEnd(timeEnd), eventid(eventid) {
00060     }
00061 }
 All Classes Functions Variables