Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

6.2 KB
Raw Blame
//! Lock-free wait-free SPSC (`rtrb`) input ring buffers and immediate wake signaling.
//!
//! Separate dedicated SPSC rings are provided for:
//! - WinTab high-priority thread (`wintab`)
//! - Windows Ink UI-thread `WM_POINTER` hook (`winink`)
//! - Native mouse/wheel navigation & hover hook (`nav`)
//!
//! Each producer lives exclusively on its owning OS thread (zero mutexes on the hot path!).

use crate::types::{NativeInputSample, NativeNavEvent};
use rtrb::{Consumer, Producer, RingBuffer};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::Duration;

pub const TABLET_RING_CAPACITY: usize = 4096;
pub const NAV_RING_CAPACITY: usize = 1024;

/// Low-latency wake-on-input signal for the dedicated render thread.
/// Avoids locking the mutex on the producer hot path if a wakeup is already latched.
#[derive(Debug, Default)]
pub struct WakeSignal {
    pending: AtomicBool,
    mutex: Mutex<()>,
    cvar: Condvar,
}

impl WakeSignal {
    pub fn new() -> Arc<Self> {
        Arc::new(Self::default())
    }

    /// Signals the engine thread immediately. Lock-free fast path when already awake/pending.
    #[inline]
    pub fn wake(&self) {
        if !self.pending.swap(true, Ordering::AcqRel) {
            // Brief lock ensures the waiting thread cannot miss the notification between
            // checking `pending` and entering `cvar.wait`.
            let _guard = self.mutex.lock();
            self.cvar.notify_one();
        }
    }

    /// Blocks until `wake()` is called or `timeout` elapses. Returns `true` if woken.
    pub fn wait_timeout(&self, timeout: Duration) -> bool {
        if self.pending.swap(false, Ordering::AcqRel) {
            return true;
        }
        let Ok(guard) = self.mutex.lock() else {
            return false;
        };
        if self.pending.swap(false, Ordering::AcqRel) {
            return true;
        }
        let (_guard, _) = match self.cvar.wait_timeout(guard, timeout) {
            Ok(res) => res,
            Err(poisoned) => poisoned.into_inner(),
        };
        self.pending.swap(false, Ordering::AcqRel)
    }
}

/// Wait-free SPSC producer wrapper for pushing `NativeInputSample`s into `ink-engine`.
pub struct TabletRingProducer {
    producer: Producer<NativeInputSample>,
    wake: Arc<WakeSignal>,
}

impl TabletRingProducer {
    /// Pushes a single sample without blocking or allocating. Silently drops only if the
    /// 4096-sample ring overflows (e.g. >16 seconds of uninterrupted stalls).
    #[inline]
    pub fn push(&mut self, sample: NativeInputSample) -> bool {
        let ok = self.producer.push(sample).is_ok();
        if ok {
            self.wake.wake();
        }
        ok
    }

    /// Pushes a slice of samples and triggers a single wake signal at the end of the burst.
    #[inline]
    pub fn push_batch(&mut self, samples: &[NativeInputSample]) -> usize {
        let mut pushed = 0;
        for &s in samples {
            if self.producer.push(s).is_ok() {
                pushed += 1;
            } else {
                break;
            }
        }
        if pushed > 0 {
            self.wake.wake();
        }
        pushed
    }
}

/// Wait-free SPSC producer wrapper for pushing `NativeNavEvent`s into `ink-engine`.
pub struct NavRingProducer {
    producer: Producer<NativeNavEvent>,
    wake: Arc<WakeSignal>,
}

impl NavRingProducer {
    #[inline]
    pub fn push(&mut self, event: NativeNavEvent) -> bool {
        let ok = self.producer.push(event).is_ok();
        if ok {
            self.wake.wake();
        }
        ok
    }
}

/// All producer handles returned to the host when creating an engine instance.
pub struct InputProducers {
    pub wintab: TabletRingProducer,
    pub winink: TabletRingProducer,
    pub nav: NavRingProducer,
}

/// Consumer ends owned exclusively by the dedicated engine/render thread.
pub(crate) struct InputConsumers {
    pub wintab: Consumer<NativeInputSample>,
    pub winink: Consumer<NativeInputSample>,
    pub nav: Consumer<NativeNavEvent>,
}

pub(crate) fn create_input_rings(wake: &Arc<WakeSignal>) -> (InputProducers, InputConsumers) {
    let (wt_tx, wt_rx) = RingBuffer::new(TABLET_RING_CAPACITY);
    let (ink_tx, ink_rx) = RingBuffer::new(TABLET_RING_CAPACITY);
    let (nav_tx, nav_rx) = RingBuffer::new(NAV_RING_CAPACITY);

    (
        InputProducers {
            wintab: TabletRingProducer {
                producer: wt_tx,
                wake: Arc::clone(wake),
            },
            winink: TabletRingProducer {
                producer: ink_tx,
                wake: Arc::clone(wake),
            },
            nav: NavRingProducer {
                producer: nav_tx,
                wake: Arc::clone(wake),
            },
        },
        InputConsumers {
            wintab: wt_rx,
            winink: ink_rx,
            nav: nav_rx,
        },
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_spsc_tablet_ring_fifo_order_and_wake() {
        let wake = WakeSignal::new();
        let (mut producers, mut consumers) = create_input_rings(&wake);

        let batch = [
            NativeInputSample {
                phys_x: 100.5,
                phys_y: 200.25,
                pressure: 0.2,
                tilt_x: 1.0,
                tilt_y: -2.0,
                twist: 0.0,
                timestamp_ms: 10.0,
                buttons: 1,
                phase: 1,
                backend: 1,
            },
            NativeInputSample {
                phys_x: 105.0,
                phys_y: 204.5,
                pressure: 0.85,
                tilt_x: 2.0,
                tilt_y: -1.0,
                twist: 15.0,
                timestamp_ms: 14.0,
                buttons: 1,
                phase: 2,
                backend: 1,
            },
        ];

        assert_eq!(producers.wintab.push_batch(&batch), 2);
        assert!(wake.wait_timeout(Duration::from_millis(5)));

        let s0 = consumers.wintab.pop().expect("first sample");
        let s1 = consumers.wintab.pop().expect("second sample");
        assert!(consumers.wintab.pop().is_err());

        assert_eq!(s0.phase, 1);
        assert!((s0.phys_x - 100.5).abs() < 1e-4);
        assert_eq!(s1.phase, 2);
        assert!((s1.pressure - 0.85).abs() < 1e-4);
    }
}