+/* events */
+static void pwm_irq_event(unsigned int now)
+{
+ Pico32x.emu_flags &= ~P32XF_PWM_PEND;
+ p32x_pwm_schedule(now);
+
+ Pico32x.sh2irqs |= P32XI_PWM;
+ p32x_update_irls(0);
+}
+
+static void fillend_event(unsigned int now)
+{
+ Pico32x.vdp_regs[0x0a/2] &= ~P32XV_nFEN;
+ p32x_poll_event(3, 1);
+}
+
+typedef void (event_cb)(unsigned int now);
+
+static unsigned int event_times[P32X_EVENT_COUNT];
+static unsigned int event_time_next;
+static event_cb *event_cbs[] = {
+ [P32X_EVENT_PWM] = pwm_irq_event,
+ [P32X_EVENT_FILLEND] = fillend_event,
+};
+
+// schedule event at some time (in m68k clocks)
+void p32x_event_schedule(enum p32x_event event, unsigned int now, int after)
+{
+ unsigned int when = (now + after) | 1;
+
+ elprintf(EL_32X, "new event #%u %u->%u", event, now, when);
+ event_times[event] = when;
+
+ if (event_time_next == 0 || (int)(event_time_next - now) > after)
+ event_time_next = when;
+}
+
+static void run_events(unsigned int until)
+{
+ int oldest, oldest_diff, time;
+ int i, diff;
+
+ while (1) {
+ oldest = -1, oldest_diff = 0x7fffffff;
+
+ for (i = 0; i < P32X_EVENT_COUNT; i++) {
+ if (event_times[i]) {
+ diff = event_times[i] - until;
+ if (diff < oldest_diff) {
+ oldest_diff = diff;
+ oldest = i;
+ }
+ }
+ }
+
+ if (oldest_diff <= 0) {
+ time = event_times[oldest];
+ event_times[oldest] = 0;
+ elprintf(EL_32X, "run event #%d %u", oldest, time);
+ event_cbs[oldest](time);
+ }
+ else if (oldest_diff < 0x7fffffff) {
+ event_time_next = event_times[oldest];
+ break;
+ }
+ else {
+ event_time_next = 0;
+ break;
+ }
+ }
+
+ if (oldest != -1)
+ elprintf(EL_32X, "next event #%d at %u", oldest, event_time_next);
+}
+
+// compare cycles, handling overflows
+// check if a > b
+#define CYCLES_GT(a, b) \
+ ((int)((a) - (b)) > 0)
+// check if a >= b
+#define CYCLES_GE(a, b) \
+ ((int)((a) - (b)) >= 0)
+