src/core/timing.c (view raw)
1/* Copyright (c) 2013-2016 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#include "timing.h"
7
8DEFINE_VECTOR(mTimingEventList, struct mTimingEvent*);
9
10void mTimingInit(struct mTiming* timing) {
11 mTimingEventListInit(&timing->events, 0);
12 timing->masterCycles = 0;
13}
14
15void mTimingDeinit(struct mTiming* timing) {
16 mTimingEventListDeinit(&timing->events);
17}
18
19void mTimingClear(struct mTiming* timing) {
20 mTimingEventListClear(&timing->events);
21 timing->masterCycles = 0;
22}
23
24void mTimingSchedule(struct mTiming* timing, struct mTimingEvent* event, int32_t when) {
25 event->when = when + timing->masterCycles;
26 size_t e;
27 for (e = 0; e < mTimingEventListSize(&timing->events); ++e) {
28 struct mTimingEvent* next = *mTimingEventListGetPointer(&timing->events, e);
29 int32_t nextWhen = next->when - timing->masterCycles;
30 if (nextWhen > when) {
31 mTimingEventListUnshift(&timing->events, e, 1);
32 *mTimingEventListGetPointer(&timing->events, e) = event;
33 return;
34 }
35 }
36 *mTimingEventListAppend(&timing->events) = event;
37}
38
39void mTimingTick(struct mTiming* timing, int32_t cycles) {
40 timing->masterCycles += cycles;
41 while (mTimingEventListSize(&timing->events)) {
42 struct mTimingEvent* next = *mTimingEventListGetPointer(&timing->events, 0);
43 int32_t nextWhen = next->when - timing->masterCycles;
44 if (nextWhen > 0) {
45 return;
46 }
47 mTimingEventListShift(&timing->events, 0, 1);
48 next->callback(timing, next->context, -nextWhen);
49 }
50}
51
52int32_t mTimingNextEvent(struct mTiming* timing) {
53 if (!mTimingEventListSize(&timing->events)) {
54 return INT_MAX;
55 }
56 struct mTimingEvent* next = *mTimingEventListGetPointer(&timing->events, 0);
57 return next->when - timing->masterCycles;
58}