+ p32x_trigger_irq(NULL, SekCyclesDone(), P32XI_VINT);
+ p32x_sh2_poll_event(&msh2, SH2_STATE_VPOLL, 0);
+ p32x_sh2_poll_event(&ssh2, SH2_STATE_VPOLL, 0);
+}
+
+void p32x_schedule_hint(SH2 *sh2, int m68k_cycles)
+{
+ // rather rough, 32x hint is useless in practice
+ int after;
+
+ if (!((Pico32x.sh2irq_mask[0] | Pico32x.sh2irq_mask[1]) & 4))
+ return; // nobody cares
+ // note: when Pico.m.scanline is 224, SH2s might
+ // still be at scanline 93 (or so)
+ if (!(Pico32x.sh2_regs[0] & 0x80) && Pico.m.scanline > 224)
+ return;
+
+ after = (Pico32x.sh2_regs[4 / 2] + 1) * 488;
+ if (sh2 != NULL)
+ p32x_event_schedule_sh2(sh2, P32X_EVENT_HINT, after);
+ else
+ p32x_event_schedule(m68k_cycles, P32X_EVENT_HINT, after);
+}
+
+/* events */
+static void fillend_event(unsigned int now)
+{
+ Pico32x.vdp_regs[0x0a/2] &= ~P32XV_nFEN;
+ p32x_sh2_poll_event(&msh2, SH2_STATE_VPOLL, now);
+ p32x_sh2_poll_event(&ssh2, SH2_STATE_VPOLL, now);
+}
+
+static void hint_event(unsigned int now)
+{
+ p32x_trigger_irq(NULL, now, P32XI_HINT);
+ p32x_schedule_hint(NULL, now);
+}
+
+typedef void (event_cb)(unsigned int now);
+
+/* times are in m68k (7.6MHz) cycles */
+unsigned int p32x_event_times[P32X_EVENT_COUNT];
+static unsigned int event_time_next;
+static event_cb *p32x_event_cbs[P32X_EVENT_COUNT] = {
+ [P32X_EVENT_PWM] = p32x_pwm_irq_event,
+ [P32X_EVENT_FILLEND] = fillend_event,
+ [P32X_EVENT_HINT] = hint_event,
+};
+
+// schedule event at some time 'after', in m68k clocks
+void p32x_event_schedule(unsigned int now, enum p32x_event event, int after)
+{
+ unsigned int when;
+
+ when = (now + after) | 1;
+
+ elprintf(EL_32X, "32x: new event #%u %u->%u", event, now, when);
+ p32x_event_times[event] = when;
+
+ if (event_time_next == 0 || CYCLES_GT(event_time_next, when))
+ event_time_next = when;
+}
+
+void p32x_event_schedule_sh2(SH2 *sh2, enum p32x_event event, int after)
+{
+ unsigned int now = sh2_cycles_done_m68k(sh2);
+ int left_to_next;
+
+ p32x_event_schedule(now, event, after);
+
+ left_to_next = (event_time_next - now) * 3;
+ sh2_end_run(sh2, left_to_next);
+}
+
+static void p32x_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 (p32x_event_times[i]) {
+ diff = p32x_event_times[i] - until;
+ if (diff < oldest_diff) {
+ oldest_diff = diff;
+ oldest = i;
+ }
+ }
+ }
+
+ if (oldest_diff <= 0) {
+ time = p32x_event_times[oldest];
+ p32x_event_times[oldest] = 0;
+ elprintf(EL_32X, "32x: run event #%d %u", oldest, time);
+ p32x_event_cbs[oldest](time);
+ }
+ else if (oldest_diff < 0x7fffffff) {
+ event_time_next = p32x_event_times[oldest];
+ break;
+ }
+ else {
+ event_time_next = 0;
+ break;
+ }
+ }
+
+ if (oldest != -1)
+ elprintf(EL_32X, "32x: next event #%d at %u",
+ oldest, event_time_next);