Skip to content

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

2.0 KB
Raw Blame
//! Deterministic per-stroke PRNG (`Xoshiro256**`) seeded via SplitMix64 by stroke ID,
//! plus deterministic dab channel hashing matching `BrushEngine.ts`.

#[derive(Debug, Clone, Copy)]
pub struct Xoshiro256StarStar {
    s: [u64; 4],
}

impl Xoshiro256StarStar {
    /// Seeds a deterministic `Xoshiro256**` stream from any 64-bit stroke ID.
    pub fn seed_from_u64(seed: u64) -> Self {
        let mut sm = seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut next_sm = || {
            sm = sm.wrapping_add(0x9E37_79B9_7F4A_7C15);
            let mut z = sm;
            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
            z ^ (z >> 31)
        };
        let s = [next_sm(), next_sm(), next_sm(), next_sm()];
        Self { s }
    }

    #[inline]
    pub fn next_u64(&mut self) -> u64 {
        let result = (self.s[1].wrapping_mul(5)).rotate_left(7).wrapping_mul(9);
        let t = self.s[1] << 17;
        self.s[2] ^= self.s[0];
        self.s[3] ^= self.s[1];
        self.s[1] ^= self.s[2];
        self.s[0] ^= self.s[3];
        self.s[2] ^= t;
        self.s[3] = self.s[3].rotate_left(45);
        result
    }

    /// Uniform float in `[0.0, 1.0)`.
    #[inline]
    pub fn next_f32(&mut self) -> f32 {
        ((self.next_u64() >> 40) as f32) * (1.0 / 16_777_216.0)
    }

    /// Uniform signed float in `[-1.0, 1.0)`.
    #[inline]
    pub fn next_signed_f32(&mut self) -> f32 {
        self.next_f32() * 2.0 - 1.0
    }
}

/// Fast deterministic dab-channel hash matching `BrushEngine.ts` `dabHashFloat(index, channel)`.
#[inline]
pub fn dab_hash_float(stroke_seed: u32, dab_index: u32, channel: u32) -> f32 {
    let mut x = dab_index
        .wrapping_mul(374_761_393)
        .wrapping_add(channel.wrapping_mul(668_265_263))
        .wrapping_add(stroke_seed.wrapping_mul(2_246_822_519));
    x = (x ^ (x >> 13)).wrapping_mul(1_274_126_177);
    x ^= x >> 16;
    (x & 0x00FF_FFFF) as f32 / 16_777_216.0
}