diff --git a/Cargo.lock b/Cargo.lock index 9a7bd7b6..ca02a66f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -210,7 +210,7 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5deb64efa5bd81e31fcd1938615a6d98c82eafcbcd787162b6f63b91d6bac5b3" dependencies = [ - "rustc_version", + "rustc_version 0.2.3", ] [[package]] @@ -445,6 +445,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "core-foundation" version = "0.10.0" @@ -575,6 +584,33 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" +[[package]] +name = "crossterm" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" +dependencies = [ + "bitflags 2.10.0", + "crossterm_winapi", + "derive_more", + "document-features", + "mio", + "parking_lot 0.12.5", + "rustix", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + [[package]] name = "dasp_sample" version = "0.11.0" @@ -638,6 +674,37 @@ dependencies = [ "defmt 0.3.100", ] +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version 0.4.1", + "syn 2.0.114", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + [[package]] name = "either" version = "1.15.0" @@ -746,6 +813,16 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "error-chain" version = "0.11.0" @@ -784,7 +861,7 @@ checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db" [[package]] name = "fl16-inputmodules" -version = "0.2.0" +version = "0.2.1" dependencies = [ "cortex-m", "cortex-m-rt", @@ -1065,11 +1142,13 @@ version = "0.2.0" dependencies = [ "chrono", "clap", + "crossterm", "image", "rand 0.8.5", "serialport", "static_vcruntime", "vis-core", + "windows-sys 0.52.0", ] [[package]] @@ -1183,7 +1262,7 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "ledmatrix" -version = "0.2.0" +version = "0.2.1" dependencies = [ "cortex-m", "cortex-m-rt", @@ -1203,9 +1282,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.180" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libloading" @@ -1237,6 +1316,18 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + [[package]] name = "lock_api" version = "0.1.5" @@ -1313,6 +1404,18 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + [[package]] name = "nb" version = "0.1.3" @@ -1573,7 +1676,7 @@ checksum = "94c8c7923936b28d546dfd14d4472eaf34c99b14e1c973a32b3e6d4eb04298c9" dependencies = [ "libc", "rand 0.6.5", - "rustc_version", + "rustc_version 0.2.3", "smallvec 0.6.14", "winapi", ] @@ -2059,7 +2162,16 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" dependencies = [ - "semver", + "semver 0.9.0", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver 1.0.28", ] [[package]] @@ -2076,6 +2188,19 @@ dependencies = [ "transpose", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.10.0", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustversion" version = "1.0.22" @@ -2112,6 +2237,12 @@ dependencies = [ "semver-parser", ] +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "semver-parser" version = "0.7.0" @@ -2173,6 +2304,37 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "simd-adler32" version = "0.3.8" @@ -2442,6 +2604,12 @@ version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + [[package]] name = "usb-device" version = "0.3.2" diff --git a/fl16-inputmodules/Cargo.toml b/fl16-inputmodules/Cargo.toml index dbd87997..a8bc257f 100644 --- a/fl16-inputmodules/Cargo.toml +++ b/fl16-inputmodules/Cargo.toml @@ -1,7 +1,7 @@ [package] edition = "2021" name = "fl16-inputmodules" -version = "0.2.0" +version = "0.2.1" [dependencies] crc = "3.0" diff --git a/fl16-inputmodules/src/control.rs b/fl16-inputmodules/src/control.rs index 42961486..540ed773 100644 --- a/fl16-inputmodules/src/control.rs +++ b/fl16-inputmodules/src/control.rs @@ -34,6 +34,8 @@ use crate::games::snake; #[cfg(feature = "ledmatrix")] use crate::matrix::*; #[cfg(feature = "ledmatrix")] +use crate::matrix_sync::*; +#[cfg(feature = "ledmatrix")] use crate::patterns::*; #[cfg(feature = "ledmatrix")] use is31fl3741::PwmFreq; @@ -71,6 +73,7 @@ pub enum CommandVals { PwmFreq = 0x1E, DebugMode = 0x1F, Version = 0x20, + Stats = 0x21, } #[derive(num_derive::FromPrimitive)] @@ -211,6 +214,8 @@ pub enum Command { GetPwmFreq, SetDebugMode(bool), GetDebugMode, + /// Get a page of performance counters + GetStats(u8), _Unknown, } @@ -397,6 +402,7 @@ pub fn parse_module_command(count: usize, buf: &[u8]) -> Option { } else { Command::GetDebugMode }), + Some(CommandVals::Stats) => Some(Command::GetStats(arg.unwrap_or(0))), _ => None, } } else { @@ -515,7 +521,7 @@ pub fn handle_generic_command(command: &Command) -> Option<[u8; 32]> { pub fn handle_command( command: &Command, state: &mut LedmatrixState, - matrix: &mut Foo, + display: &mut MatrixSync, random: u8, ) -> Option<[u8; 32]> { use crate::games::game_of_life; @@ -528,7 +534,7 @@ pub fn handle_command( } Command::SetBrightness(br) => { //let _ = serial.write("Brightness".as_bytes()); - set_brightness(state, *br, matrix); + state.brightness = *br; None } Command::Percentage(p) => { @@ -545,7 +551,7 @@ pub fn handle_command( PatternVals::ZigZag => state.grid = zigzag(), PatternVals::FullBrightness => { state.grid = percentage(100); - set_brightness(state, BRIGHTNESS_LEVELS, matrix); + state.brightness = BRIGHTNESS_LEVELS; } PatternVals::DisplayPanic => state.grid = display_panic(), PatternVals::DisplayLotus2 => state.grid = display_lotus2(), @@ -564,6 +570,7 @@ pub fn handle_command( } Command::Draw(vals) => { state.grid = draw(vals); + display.stats.frames_committed = display.stats.frames_committed.wrapping_add(1); None } Command::StageGreyCol(col, vals) => { @@ -575,6 +582,7 @@ pub fn handle_command( state.grid = state.col_buffer.clone(); // Zero the old staging buffer, just for good measure. state.col_buffer = percentage(0); + display.stats.frames_committed = display.stats.frames_committed.wrapping_add(1); None } // TODO: Move to handle_generic_command @@ -618,7 +626,7 @@ pub fn handle_command( } Command::SetPwmFreq(arg) => { state.pwm_freq = *arg; - matrix.device.set_pwm_freq(state.pwm_freq.into()).unwrap(); + display.set_pwm_freq(state.pwm_freq); None } Command::GetPwmFreq => { @@ -635,6 +643,7 @@ pub fn handle_command( response[0] = state.debug_mode as u8; Some(response) } + Command::GetStats(page) => Some(display.take_stats(*page)), _ => handle_generic_command(command), } } diff --git a/fl16-inputmodules/src/lib.rs b/fl16-inputmodules/src/lib.rs index df107681..84014410 100644 --- a/fl16-inputmodules/src/lib.rs +++ b/fl16-inputmodules/src/lib.rs @@ -22,6 +22,8 @@ pub mod animations; #[cfg(feature = "ledmatrix")] pub mod matrix; #[cfg(feature = "ledmatrix")] +pub mod matrix_sync; +#[cfg(feature = "ledmatrix")] pub mod patterns; #[cfg(feature = "b1display")] diff --git a/fl16-inputmodules/src/matrix_sync.rs b/fl16-inputmodules/src/matrix_sync.rs new file mode 100644 index 00000000..56aa5f61 --- /dev/null +++ b/fl16-inputmodules/src/matrix_sync.rs @@ -0,0 +1,261 @@ +use crate::control::PwmFreqArg; +use crate::led_hal as bsp; +use crate::matrix::{LedmatrixState, HEIGHT, WIDTH}; +use crate::patterns::BRIGHTNESS_LEVELS; +use embedded_hal::digital::OutputPin; +use is31fl3741::devices::LedMatrix; +use rp2040_hal::{ + gpio::{ + bank0::{Gpio26, Gpio27, Gpio29}, + FunctionI2C, FunctionSioOutput, Pin, PullDown, PullUp, + }, + pac::I2C1, + Timer, +}; + +pub type Foo = LedMatrix< + bsp::hal::I2C< + I2C1, + ( + bsp::hal::gpio::Pin, + bsp::hal::gpio::Pin, + ), + >, +>; + +/// SDB pin of the LED controller. Low shuts it down +pub type LedEnable = Pin; + +/// 0xB4 LEDs on the first page, 0xAB on the second page +const PWM_BUF_LEN: usize = 0xB4 + 0xAB; + +/// Performance counters, read by the host with the Stats command. +/// +/// Counters wrap around, the host should only look at the difference between two reads. +/// The max values are reset after every read. +#[derive(Default)] +pub struct Stats { + /// Bytes received over USB + pub bytes_received: u32, + /// Commands that were successfully parsed + pub cmds_parsed: u32, + /// USB reads that contained data but no valid command + pub cmds_rejected: u32, + /// Frames committed by Draw or DrawGreyColBuffer + pub frames_committed: u32, + /// Frames actually sent to the LED controller over I2C + pub flushes: u32, + /// Time spent sending frames over I2C in microseconds + pub flush_us_total: u32, + /// Longest time spent sending a single frame over I2C in microseconds + pub flush_us_max: u32, + /// Longest main loop iteration in microseconds + pub loop_us_max: u32, + /// Main loop iterations + pub loops: u32, + /// Main loop iterations that didn't receive any USB data + pub idle_loops: u32, + /// Time spent in main loop iterations that didn't receive any USB data in microseconds + pub idle_us_total: u32, + /// Time spent in main loop iterations that received USB data in microseconds + pub busy_us_total: u32, + /// Times the PWM values were calculated + pub calcs: u32, + /// Time spent calculating PWM values in microseconds + pub calc_us_total: u32, + /// Longest time spent calculating PWM values once in microseconds + pub calc_us_max: u32, + /// Time the CPU spent asleep waiting for an event in microseconds + pub wait_us_total: u32, + /// Times the LED controller was powered on + pub led_power_ons: u32, + /// Time the LED controller was powered off in microseconds + pub led_off_us_total: u32, +} + +impl Stats { + /// Serialize a page as little-endian u32s + /// + /// Each page resets the max values it contains. + pub fn take_response(&mut self, page: u8) -> [u8; 32] { + let vals = match page { + 0 => { + let vals = [ + self.bytes_received, + self.cmds_parsed, + self.cmds_rejected, + self.frames_committed, + self.flushes, + self.flush_us_total, + self.flush_us_max, + self.loop_us_max, + ]; + self.flush_us_max = 0; + self.loop_us_max = 0; + vals + } + 1 => { + let vals = [ + self.loops, + self.idle_loops, + self.idle_us_total, + self.busy_us_total, + self.calcs, + self.calc_us_total, + self.calc_us_max, + self.wait_us_total, + ]; + self.calc_us_max = 0; + vals + } + 2 => [self.led_power_ons, self.led_off_us_total, 0, 0, 0, 0, 0, 0], + _ => [0; 8], + }; + let mut response = [0; 32]; + for (i, val) in vals.iter().enumerate() { + response[i * 4..i * 4 + 4].copy_from_slice(&val.to_le_bytes()); + } + response + } +} + +pub struct MatrixSync { + matrix: Foo, + led_enable: LedEnable, + /// Whether the LED controller may be powered on. False while sleeping + enabled: bool, + /// Whether the LED controller is currently powered on + powered: bool, + /// When the LED controller was powered off, or when its off time was last counted + off_since: u64, + /// PWM values last sent to the LED controller. None if unknown + sent: Option<[u8; PWM_BUF_LEN]>, + /// Index into the PWM buffer of each pixel. + /// Calculated once, because calc_pixel builds its whole lookup table on every call. + pwm_index: [[u16; HEIGHT]; WIDTH], + timer: Timer, + pub stats: Stats, +} + +impl MatrixSync { + pub fn new(matrix: Foo, led_enable: LedEnable, timer: Timer) -> Self { + let mut pwm_index = [[0; HEIGHT]; WIDTH]; + for (x, col) in pwm_index.iter_mut().enumerate() { + for (y, index) in col.iter_mut().enumerate() { + let (register, page) = (matrix.device.calc_pixel)(x as u8, y as u8); + *index = (page as u16) * 0xB4 + (register as u16); + } + } + Self { + matrix, + led_enable, + // The LED controller must already be on, to set it up + enabled: true, + powered: true, + off_since: 0, + sent: None, + pwm_index, + timer, + stats: Stats::default(), + } + } + + /// Fills the grid pixels but only sends the I2C commands if the PWM values changed. + /// Powers the LED controller off while no LED is lit and back on when one is. + pub fn flush_if_dirty(&mut self, state: &LedmatrixState) { + let calc_start = self.timer.get_counter().ticks(); + let brightnesses = calc_brightnesses(state, &self.pwm_index); + let calc_elapsed = (self.timer.get_counter().ticks() - calc_start) as u32; + self.stats.calcs = self.stats.calcs.wrapping_add(1); + self.stats.calc_us_total = self.stats.calc_us_total.wrapping_add(calc_elapsed); + self.stats.calc_us_max = self.stats.calc_us_max.max(calc_elapsed); + + let lit = brightnesses.iter().any(|&b| b != 0); + self.set_powered(self.enabled && lit); + if !self.powered { + return; + } + + if self.sent.as_ref() != Some(&brightnesses) { + let start = self.timer.get_counter().ticks(); + self.matrix.device.fill_matrix(&brightnesses).unwrap(); + let elapsed = (self.timer.get_counter().ticks() - start) as u32; + self.sent = Some(brightnesses); + + self.stats.flushes = self.stats.flushes.wrapping_add(1); + self.stats.flush_us_total = self.stats.flush_us_total.wrapping_add(elapsed); + self.stats.flush_us_max = self.stats.flush_us_max.max(elapsed); + } + } + + /// Sends the full grid, even if the controller should already have it. + /// Recovers from the controller losing or corrupting its state. + pub fn force_flush(&mut self, state: &LedmatrixState) { + self.sent = None; + self.flush_if_dirty(state); + } + + /// Allow or prevent powering the LED controller on, e.g. while sleeping. + /// Even when enabled, it's only powered on while an LED is lit, after the next flush. + pub fn set_enabled(&mut self, enabled: bool) { + self.enabled = enabled; + if !enabled { + self.set_powered(false); + } + } + + fn set_powered(&mut self, powered: bool) { + if powered == self.powered { + return; + } + self.count_off_time(); + if powered { + self.led_enable.set_high().unwrap(); + // It may not have kept or accepted PWM values while off + self.sent = None; + self.stats.led_power_ons = self.stats.led_power_ons.wrapping_add(1); + } else { + self.led_enable.set_low().unwrap(); + } + self.powered = powered; + } + + /// Add the time the LED controller has been off since the last call to the stats + fn count_off_time(&mut self) { + let now = self.timer.get_counter().ticks(); + if !self.powered { + let off_us = (now - self.off_since) as u32; + self.stats.led_off_us_total = self.stats.led_off_us_total.wrapping_add(off_us); + } + self.off_since = now; + } + + /// Get a page of the stats, see [Stats::take_response] + pub fn take_stats(&mut self, page: u8) -> [u8; 32] { + self.count_off_time(); + self.stats.take_response(page) + } + + pub fn set_pwm_freq(&mut self, freq: PwmFreqArg) { + // Make sure the controller accepts the write. Powered off again on the next flush, if dark + self.set_powered(true); + self.matrix.device.set_pwm_freq(freq.into()).unwrap(); + } +} + +/// Calculate PWM values for the entire grid, so they can be sent with just two I2C commands +fn calc_brightnesses( + state: &LedmatrixState, + pwm_index: &[[u16; HEIGHT]; WIDTH], +) -> [u8; PWM_BUF_LEN] { + let mut brightnesses = [0x00; PWM_BUF_LEN]; + for y in 0..HEIGHT { + for x in 0..WIDTH { + // u32 is plenty for 255 * 255 and avoids slow 64-bit division on the Cortex-M0+ + brightnesses[pwm_index[x][y] as usize] = + ((state.grid.0[x][y] as u32) * (state.brightness as u32) + / (BRIGHTNESS_LEVELS as u32)) as u8; + } + } + brightnesses +} diff --git a/fl16-inputmodules/src/patterns.rs b/fl16-inputmodules/src/patterns.rs index e8ff33d6..09bc04a7 100644 --- a/fl16-inputmodules/src/patterns.rs +++ b/fl16-inputmodules/src/patterns.rs @@ -1,15 +1,5 @@ -use rp2040_hal::{ - gpio::{ - bank0::{Gpio26, Gpio27}, - FunctionI2C, PullUp, - }, - pac::I2C1, -}; - -use crate::led_hal as bsp; use crate::mapping::*; use crate::matrix::*; -use is31fl3741::devices::LedMatrix; /// Bytes needed to represent all LEDs with a single bit /// math.ceil(WIDTH * HEIGHT / 8) @@ -18,16 +8,6 @@ pub const DRAW_BYTES: usize = 39; /// Maximum number of brightneses levels pub const BRIGHTNESS_LEVELS: u8 = 255; -pub type Foo = LedMatrix< - bsp::hal::I2C< - I2C1, - ( - bsp::hal::gpio::Pin, - bsp::hal::gpio::Pin, - ), - >, ->; - pub fn draw(bytes: &[u8; DRAW_BYTES]) -> Grid { let mut grid = Grid::default(); @@ -308,44 +288,6 @@ pub fn double_gradient() -> Grid { grid } -/// Same as fill_grid_pixels but does each pixel individually -/// So it's much slower because it has to send 306 I2C commands -pub fn _fill_grid(grid: &Grid, matrix: &mut Foo) { - for y in 0..HEIGHT { - for x in 0..WIDTH { - matrix.device.pixel(x as u8, y as u8, grid.0[x][y]).unwrap(); - } - } -} - -pub fn set_brightness(state: &mut LedmatrixState, brightness: u8, matrix: &mut Foo) { - state.brightness = brightness; - fill_grid_pixels(state, matrix); -} - -/// Just sends two I2C commands for the entire grid -pub fn fill_grid_pixels(state: &LedmatrixState, matrix: &mut Foo) { - // 0xB4 LEDs on the first page, 0xAB on the second page - let mut brightnesses = [0x00; 0xB4 + 0xAB]; - for y in 0..HEIGHT { - for x in 0..WIDTH { - let (register, page) = (matrix.device.calc_pixel)(x as u8, y as u8); - brightnesses[(page as usize) * 0xB4 + (register as usize)] = - ((state.grid.0[x][y] as u64) * (state.brightness as u64) - / (BRIGHTNESS_LEVELS as u64)) as u8; - } - } - matrix.device.fill_matrix(&brightnesses).unwrap(); -} - -pub fn full_brightness(matrix: &mut Foo) { - // Fills every pixel individually - //matrix.fill_brightness(0xFF).unwrap(); - - // Fills full page at once - matrix.device.fill(0xFF).unwrap(); -} - pub fn zigzag() -> Grid { let mut grid = Grid::default(); diff --git a/inputmodule-control/Cargo.toml b/inputmodule-control/Cargo.toml index 27be7699..6c419ad7 100644 --- a/inputmodule-control/Cargo.toml +++ b/inputmodule-control/Cargo.toml @@ -18,6 +18,16 @@ rand = "0.8.5" # For audio visualizations # Depending on an experimental crate, therefore optional dependency vis-core = { git = 'https://github.com/Rahix/visualizer2.git', rev = '1fe908012a9c156695921f3b6bb47178e1332b92', optional = true } +crossterm = "0.29" + +[target.'cfg(windows)'.dependencies] +# To find which USB port each LED matrix is plugged into +windows-sys = { version = "0.52", features = [ + "Win32_Devices_DeviceAndDriverInstallation", + "Win32_Foundation", + "Win32_System_Registry", +] } + [features] audio-visualizations = ["vis-core"] diff --git a/inputmodule-control/src/bricks.rs b/inputmodule-control/src/bricks.rs new file mode 100644 index 00000000..5d681b01 --- /dev/null +++ b/inputmodule-control/src/bricks.rs @@ -0,0 +1,441 @@ +//! Brick breaker game, played on the host and streamed to the LED matrix + +use std::collections::VecDeque; + +use rand::prelude::*; + +use crate::hostgame::{add_rect, add_square, dark, play, to_grid, HostGame, Input, Light, FIELD_H}; +use crate::inputmodule::{GreyGrid, HEIGHT}; + +/// Physics steps per second, independent of the frame rate. +/// Small enough steps that even the fastest ball can't skip through a brick. +const STEPS_PER_SEC: f32 = 480.0; + +/// Top edge of the paddle, it's one LED tall +const PADDLE_Y: f32 = 32.0; +const PADDLE_WIDTH: f32 = 3.0; +const PADDLE_BRIGHTNESS: f32 = 0.6; +/// How fast the paddle moves while an arrow key is held, in LEDs per second +const PADDLE_KEY_SPEED: f32 = 14.0; +/// How fast the paddle catches up with the mouse or a key press, in LEDs per second +const PADDLE_MAX_SPEED: f32 = 40.0; + +/// The ball is a square, one LED wide +const BALL_RADIUS: f32 = 0.5; +/// Ball speed in LEDs per second +const START_SPEED: f32 = 12.0; +const LEVEL_SPEEDUP: f32 = 2.0; +const PADDLE_SPEEDUP: f32 = 0.4; +const MAX_SPEED: f32 = 30.0; +/// Hitting the paddle at the very edge sends the ball off at this angle from vertical +const MAX_BOUNCE_ANGLE: f32 = std::f32::consts::FRAC_PI_3; +/// Fading copies of the ball where it was this long ago, and how bright they are +const TRAIL: [(f32, f32); 3] = [(0.012, 0.35), (0.024, 0.18), (0.036, 0.08)]; + +const BRICK_WIDTH: usize = 3; +/// Row of the topmost bricks, leaves room for the ball to bounce around above them +const BRICK_TOP: usize = 2; +/// How long a broken brick takes to fade out +const BRICK_FADE_SECS: f32 = 0.3; + +const BALLS: u32 = 3; +/// The ball launches by itself if the player doesn't +const AUTO_LAUNCH_SECS: f32 = 3.0; +const LOST_SECS: f32 = 1.0; +const CLEARED_SECS: f32 = 1.2; + +struct Brick { + x: usize, + y: usize, + /// Hits left until it breaks + hits: u8, + /// When it was last hit, to flash it + hit_at: Option, +} + +impl Brick { + fn left(&self) -> f32 { + self.x as f32 + } + fn right(&self) -> f32 { + (self.x + BRICK_WIDTH) as f32 + } + fn top(&self) -> f32 { + self.y as f32 + } + fn bottom(&self) -> f32 { + (self.y + 1) as f32 + } +} + +#[derive(Clone, Copy, PartialEq)] +enum State { + /// Ball rests on the paddle until launched + Serving { + since: f32, + }, + Playing, + /// Ball fell off the bottom + Lost { + since: f32, + }, + /// All bricks broken, about to start the next level + Cleared { + since: f32, + }, + GameOver, +} + +struct Game { + rng: ThreadRng, + /// Screen width in LEDs, one or more LED matrices side by side + width: f32, + state: State, + level: u32, + score: u32, + balls: u32, + bricks: Vec, + /// Center of the paddle + paddle_x: f32, + /// Center of the ball + ball_x: f32, + ball_y: f32, + vel_x: f32, + vel_y: f32, + speed: f32, + /// Recent ball positions for the trail, newest last + trail: VecDeque<(f32, f32, f32)>, +} + +impl Game { + fn new(width: usize) -> Self { + let mut game = Self { + rng: thread_rng(), + width: width as f32, + state: State::Serving { since: 0.0 }, + level: 1, + score: 0, + balls: BALLS, + bricks: vec![], + paddle_x: width as f32 / 2.0, + ball_x: 0.0, + ball_y: 0.0, + vel_x: 0.0, + vel_y: 0.0, + speed: START_SPEED, + trail: VecDeque::new(), + }; + game.build_level(); + game + } + + /// More rows every level, and from level 2 the top rows take two hits + fn build_level(&mut self) { + let rows = (3 + self.level as usize).min(10); + let tough_rows = (self.level as usize - 1).min(rows - 2); + let cols = self.width as usize / BRICK_WIDTH; + self.bricks = (0..rows) + .flat_map(|row| { + (0..cols).map(move |col| Brick { + x: col * BRICK_WIDTH, + y: BRICK_TOP + row, + hits: if row < tough_rows { 2 } else { 1 }, + hit_at: None, + }) + }) + .collect(); + } + + fn serve(&mut self, now: f32) { + self.state = State::Serving { since: now }; + self.speed = START_SPEED + LEVEL_SPEEDUP * (self.level - 1) as f32; + self.trail.clear(); + } + + fn launch(&mut self) { + // Slightly to a random side, so it's not the same every time + let angle: f32 = self.rng.gen_range(-0.35..0.35); + self.vel_x = self.speed * angle.sin(); + self.vel_y = -self.speed * angle.cos(); + self.state = State::Playing; + } + + fn restart(&mut self, now: f32) { + self.level = 1; + self.score = 0; + self.balls = BALLS; + self.build_level(); + self.serve(now); + } + + fn step_ball(&mut self, dt: f32, now: f32) { + self.ball_x += self.vel_x * dt; + self.ball_y += self.vel_y * dt; + self.trail.push_back((now, self.ball_x, self.ball_y)); + let oldest = TRAIL[TRAIL.len() - 1].0 + 0.01; + while self + .trail + .front() + .is_some_and(|&(t, _, _)| now - t > oldest) + { + self.trail.pop_front(); + } + + // Walls + if self.ball_x - BALL_RADIUS < 0.0 { + self.ball_x = BALL_RADIUS; + self.vel_x = self.vel_x.abs(); + } + if self.ball_x + BALL_RADIUS > self.width { + self.ball_x = self.width - BALL_RADIUS; + self.vel_x = -self.vel_x.abs(); + } + if self.ball_y - BALL_RADIUS < 0.0 { + self.ball_y = BALL_RADIUS; + self.vel_y = self.vel_y.abs(); + } + + // Paddle. Where it hits decides the angle it bounces off at. + let reach = PADDLE_WIDTH / 2.0 + BALL_RADIUS; + let bottom = self.ball_y + BALL_RADIUS; + if self.vel_y > 0.0 + && (PADDLE_Y..PADDLE_Y + 0.5).contains(&bottom) + && (self.ball_x - self.paddle_x).abs() <= reach + { + let offset = ((self.ball_x - self.paddle_x) / reach).clamp(-1.0, 1.0); + let angle = offset * MAX_BOUNCE_ANGLE; + self.speed = (self.speed + PADDLE_SPEEDUP).min(MAX_SPEED); + self.vel_x = self.speed * angle.sin(); + self.vel_y = -self.speed * angle.cos(); + self.ball_y = PADDLE_Y - BALL_RADIUS; + } + + // Bricks. Bounce off the side that the ball overlaps the least, + // that's the side it came from. + let (left, right) = (self.ball_x - BALL_RADIUS, self.ball_x + BALL_RADIUS); + let (top, bottom) = (self.ball_y - BALL_RADIUS, self.ball_y + BALL_RADIUS); + if let Some(brick) = self.bricks.iter_mut().find(|b| { + b.hits > 0 + && left < b.right() + && right > b.left() + && top < b.bottom() + && bottom > b.top() + }) { + let overlap_x = (right - brick.left()).min(brick.right() - left); + let overlap_y = (bottom - brick.top()).min(brick.bottom() - top); + if overlap_x < overlap_y { + let from_left = self.ball_x < (brick.left() + brick.right()) / 2.0; + self.vel_x = if from_left { + -self.vel_x.abs() + } else { + self.vel_x.abs() + }; + self.ball_x += if from_left { -overlap_x } else { overlap_x }; + } else { + let from_above = self.ball_y < (brick.top() + brick.bottom()) / 2.0; + self.vel_y = if from_above { + -self.vel_y.abs() + } else { + self.vel_y.abs() + }; + self.ball_y += if from_above { -overlap_y } else { overlap_y }; + } + brick.hits -= 1; + brick.hit_at = Some(now); + self.score += if brick.hits == 0 { 10 } else { 5 }; + if self.bricks.iter().all(|b| b.hits == 0) { + self.score += 100 * self.level; + self.state = State::Cleared { since: now }; + } + } + + if self.ball_y - BALL_RADIUS > FIELD_H { + self.balls -= 1; + self.state = State::Lost { since: now }; + } + } +} + +impl HostGame for Game { + fn player_x(&self) -> f32 { + self.paddle_x + } + + fn update(&mut self, input: &mut Input, now: f32, dt: f32) { + let half = PADDLE_WIDTH / 2.0; + self.paddle_x = input + .steer(self.paddle_x, dt, PADDLE_KEY_SPEED, PADDLE_MAX_SPEED) + .clamp(half, self.width - half); + match self.state { + State::Serving { since } => { + self.ball_x = self.paddle_x; + self.ball_y = PADDLE_Y - BALL_RADIUS; + if input.action || now - since >= AUTO_LAUNCH_SECS { + self.launch(); + } + } + State::Playing => { + let steps = (dt * STEPS_PER_SEC).ceil().max(1.0); + for i in 0..steps as u32 { + let step_time = now - dt + dt * (i + 1) as f32 / steps; + self.step_ball(dt / steps, step_time); + if self.state != State::Playing { + break; + } + } + } + State::Lost { since } => { + if now - since >= LOST_SECS { + if self.balls == 0 { + self.state = State::GameOver; + } else { + self.serve(now); + } + } + } + State::Cleared { since } => { + if now - since >= CLEARED_SECS { + self.level += 1; + self.build_level(); + self.serve(now); + } + } + State::GameOver => { + if input.action { + self.restart(now); + } + } + } + } + + fn render(&self, now: f32) -> GreyGrid { + let mut light: Light = dark(self.width as usize); + + for brick in &self.bricks { + let since_hit = brick.hit_at.map_or(f32::MAX, |t| now - t); + let brightness = if brick.hits == 0 { + // Flash and fade out + if since_hit >= BRICK_FADE_SECS { + continue; + } + 1.0 - since_hit / BRICK_FADE_SECS + } else { + // Alternate, so neighboring bricks can be told apart + let base = match brick.hits { + 1 if (brick.x / BRICK_WIDTH + brick.y).is_multiple_of(2) => 0.3, + 1 => 0.5, + _ => 0.85, + }; + // Flash when hit but not broken yet + let flash = (1.0 - since_hit / 0.15).max(0.0); + base + (1.0 - base) * flash + }; + add_rect( + &mut light, + (brick.left(), brick.top()), + (brick.right(), brick.bottom()), + brightness, + ); + } + + // Paddle blinks after losing the ball + let paddle = match self.state { + State::Lost { since } if ((now - since) * 8.0) as u32 % 2 == 1 => 0.1, + _ => PADDLE_BRIGHTNESS, + }; + let half = PADDLE_WIDTH / 2.0; + add_rect( + &mut light, + (self.paddle_x - half, PADDLE_Y), + (self.paddle_x + half, PADDLE_Y + 1.0), + paddle, + ); + + if matches!(self.state, State::Playing | State::Serving { .. }) { + for &(ago, brightness) in &TRAIL { + if let Some(&(_, x, y)) = self.trail.iter().rev().find(|&&(t, _, _)| now - t >= ago) + { + add_square(&mut light, x, y, brightness); + } + } + add_square(&mut light, self.ball_x, self.ball_y, 1.0); + } + + // Spare balls as dim dots in the bottom right corner + let spare = match self.state { + State::Serving { .. } | State::Playing => self.balls.saturating_sub(1), + _ => self.balls, + }; + for i in 0..spare as usize { + light[self.width as usize - 1 - 2 * i][HEIGHT - 1] += 0.15; + } + + // A bright band sweeps up after clearing a level + if let State::Cleared { since } = self.state { + let y = FIELD_H - (now - since) / CLEARED_SECS * (FIELD_H + 2.0); + add_rect(&mut light, (0.0, y), (self.width, y + 2.0), 0.8); + } + + let dim = if self.state == State::GameOver { + 0.25 + } else { + 1.0 + }; + to_grid(&light, dim) + } + + fn status(&self, fps: f64) -> String { + let state = match self.state { + State::Serving { .. } => "Space to launch", + State::Playing => "", + State::Lost { .. } => "Lost the ball!", + State::Cleared { .. } => "Level cleared!", + State::GameOver => "Game over! Space to play again, Q to quit", + }; + format!( + "Level {} Score {} Balls {} {:.0} FPS {}", + self.level, self.score, self.balls, fps, state + ) + } +} + +/// Play until the player quits, as fast as possible or limited to fps +pub fn bricks_cmd(serialdevs: &[String], extend: bool, fps: Option) { + play( + serialdevs, + extend, + fps, + "Steer with the arrow keys, or move the mouse across this terminal. +Space or a click launches the ball.", + Game::new, + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::inputmodule::WIDTH; + + /// Ball that the paddle always catches clears the level and never gets stuck + #[test] + fn autoplay_clears_level() { + // One LED matrix, and two side by side with --extend + for width in [WIDTH, 2 * WIDTH] { + let mut game = Game::new(width); + let mut input = Input::default(); + let dt = 1.0 / 120.0; + let mut now: f32 = 0.0; + while game.level == 1 { + // Hit it at different spots on the paddle, so it doesn't bounce in a loop + input.target = Some(game.ball_x + 0.4 + 0.6 * (now * 0.7).sin()); + input.action = true; + now += dt; + game.update(&mut input, now, dt); + game.render(now); + assert_eq!(game.balls, BALLS, "Lost a ball"); + assert!(now < 300.0, "Didn't clear the level"); + } + println!("Cleared level 1 in {:.1}s, score {}", now, game.score); + } + } +} diff --git a/inputmodule-control/src/cave.rs b/inputmodule-control/src/cave.rs new file mode 100644 index 00000000..f270189d --- /dev/null +++ b/inputmodule-control/src/cave.rs @@ -0,0 +1,403 @@ +//! Cave descent game: fall down an endless winding cave without touching the walls. +//! The cave scrolls by fractions of an LED, so it flows smoothly at high frame rates. + +use std::collections::VecDeque; +use std::f32::consts::PI; + +use rand::prelude::*; + +use crate::hostgame::{add_rect, add_square, dark, play, to_grid, Burst, HostGame, Input, Light}; +use crate::inputmodule::{GreyGrid, HEIGHT}; + +/// Physics steps per second, independent of the frame rate +const STEPS_PER_SEC: f32 = 480.0; + +/// Center of the row the player stays in, the cave scrolls up past it. +/// Near the top, to see far ahead. +const PLAYER_Y: f32 = 5.5; +/// How fast the player moves while an arrow key is held, in LEDs per second +const PLAYER_KEY_SPEED: f32 = 12.0; +/// How fast the player catches up with the mouse or a key press, in LEDs per second +const PLAYER_MAX_SPEED: f32 = 30.0; +/// Half the size of the player's hitbox. A bit smaller than the LED, +/// so just grazing a wall doesn't count. +const PLAYER_HITBOX: f32 = 0.35; +/// Faded copies of the player where it was this long ago, and how bright they are +const TRAIL: [(f32, f32); 3] = [(0.02, 0.3), (0.04, 0.15), (0.06, 0.07)]; + +/// Falling speed in LEDs per second, grows over time +const START_SPEED: f32 = 8.0; +const ACCELERATION: f32 = 0.15; +const MAX_SPEED: f32 = 30.0; + +/// The shape of the cave is set every this many LEDs of depth, and curves smoothly in between +const SEGMENT: f32 = 5.0; +/// No curves at first, so the start is easy +const STRAIGHT_START: f32 = 20.0; +/// Half the width of the cave, it gets narrower the deeper it goes +const START_HALF_WIDTH: f32 = 3.0; +const MIN_HALF_WIDTH: f32 = 1.25; +const NARROWING: f32 = 0.004; +/// How much steeper the cave may curve than the player can follow with the arrow keys +const MAX_STEEPNESS: f32 = 0.75; + +/// Walls are dim, with a brighter rim along the edge of the cave +const WALL_BRIGHTNESS: f32 = 0.1; +const RIM_BRIGHTNESS: f32 = 0.35; +/// Samples per LED row, so the walls scroll smoothly by fractions of an LED +const ROW_SAMPLES: usize = 4; + +/// Chance of a gem in each segment, and how many points it's worth +const GEM_CHANCE: f64 = 0.4; +const GEM_POINTS: u32 = 10; +const GEM_SIZE: f32 = 0.7; +const GEM_FADE_SECS: f32 = 0.25; + +const CRASH_SECS: f32 = 1.0; + +struct Segment { + depth: f32, + center: f32, + half_width: f32, +} + +struct Gem { + depth: f32, + x: f32, + taken_at: Option, +} + +#[derive(Clone, Copy, PartialEq)] +enum State { + /// Waiting for the player to start + Ready, + Falling, + Crashed { + since: f32, + }, +} + +struct Game { + rng: ThreadRng, + /// Screen width in LEDs, one or more LED matrices side by side + width: f32, + state: State, + /// Depth of the top of the screen, how far the player has fallen + depth: f32, + speed: f32, + player_x: f32, + /// Shape of the cave, from just above the screen to beyond its bottom + segments: VecDeque, + gems: VecDeque, + gems_taken: u32, + best: u32, + /// Where the player crashed + burst: Option, + /// Recent player positions with the time, for the trail. Newest last. + trail: VecDeque<(f32, f32)>, +} + +impl Game { + fn new(width: usize) -> Self { + let mut game = Self { + rng: thread_rng(), + width: width as f32, + state: State::Ready, + depth: 0.0, + speed: START_SPEED, + player_x: width as f32 / 2.0, + segments: VecDeque::new(), + gems: VecDeque::new(), + gems_taken: 0, + best: 0, + burst: None, + trail: VecDeque::new(), + }; + game.restart(); + game + } + + fn restart(&mut self) { + self.state = State::Ready; + self.depth = 0.0; + self.speed = START_SPEED; + self.player_x = self.width / 2.0; + self.segments.clear(); + self.gems.clear(); + self.gems_taken = 0; + self.trail.clear(); + self.segments.push_back(Segment { + depth: -SEGMENT, + center: self.width / 2.0, + half_width: START_HALF_WIDTH, + }); + self.extend_cave(); + } + + fn score(&self) -> u32 { + self.depth as u32 + self.gems_taken * GEM_POINTS + } + + /// Add segments until the cave reaches past the bottom of the screen, + /// and drop the ones that scrolled off the top + fn extend_cave(&mut self) { + let bottom = self.depth + HEIGHT as f32 + SEGMENT; + while let Some(last) = self.segments.back().filter(|s| s.depth < bottom) { + let depth = last.depth + SEGMENT; + let narrowed = START_HALF_WIDTH - NARROWING * depth.max(0.0); + let half_width = (narrowed + self.rng.gen_range(-0.3..0.3)).max(MIN_HALF_WIDTH); + let center = if depth < STRAIGHT_START { + self.width / 2.0 + } else { + // Not steeper than the player can follow at the current speed. + // Curving with a cosine is steepest in the middle, at pi/2 times the average. + let steepness = (MAX_STEEPNESS * PLAYER_KEY_SPEED / self.speed).min(1.0); + let max_shift = steepness * SEGMENT * 2.0 / PI; + let shifted = last.center + self.rng.gen_range(-max_shift..max_shift); + shifted.clamp(half_width, self.width - half_width) + }; + if depth >= STRAIGHT_START && self.rng.gen_bool(GEM_CHANCE) { + let room = half_width - GEM_SIZE; + self.gems.push_back(Gem { + depth, + x: center + self.rng.gen_range(-room..room), + taken_at: None, + }); + } + self.segments.push_back(Segment { + depth, + center, + half_width, + }); + } + while self.segments.len() > 2 && self.segments[1].depth < self.depth - SEGMENT { + self.segments.pop_front(); + } + while self + .gems + .front() + .is_some_and(|g| g.depth < self.depth - 1.0) + { + self.gems.pop_front(); + } + } + + /// Left and right wall of the cave at a depth, curving smoothly between segments + fn walls(&self, depth: f32) -> (f32, f32) { + let first = self.segments[0].depth; + let i = (((depth - first) / SEGMENT).max(0.0) as usize).min(self.segments.len() - 2); + let (a, b) = (&self.segments[i], &self.segments[i + 1]); + let t = ((depth - a.depth) / SEGMENT).clamp(0.0, 1.0); + let s = (1.0 - (t * PI).cos()) / 2.0; + let center = a.center + (b.center - a.center) * s; + let half_width = a.half_width + (b.half_width - a.half_width) * s; + (center - half_width, center + half_width) + } + + fn crashed(&self) -> bool { + let player_depth = self.depth + PLAYER_Y; + [-PLAYER_HITBOX, 0.0, PLAYER_HITBOX].iter().any(|dy| { + let (left, right) = self.walls(player_depth + dy); + self.player_x - PLAYER_HITBOX < left || self.player_x + PLAYER_HITBOX > right + }) + } + + fn fall(&mut self, dt: f32, now: f32) { + self.speed = (self.speed + ACCELERATION * dt).min(MAX_SPEED); + self.depth += self.speed * dt; + self.extend_cave(); + + let player_depth = self.depth + PLAYER_Y; + for gem in self.gems.iter_mut().filter(|g| g.taken_at.is_none()) { + if (gem.depth - player_depth).abs() < 0.8 && (gem.x - self.player_x).abs() < 0.8 { + gem.taken_at = Some(now); + self.gems_taken += 1; + } + } + + if self.crashed() { + self.state = State::Crashed { since: now }; + self.best = self.best.max(self.score()); + self.burst = Some(Burst::new(&mut self.rng, self.player_x, PLAYER_Y)); + } + } +} + +impl HostGame for Game { + fn player_x(&self) -> f32 { + self.player_x + } + + fn update(&mut self, input: &mut Input, now: f32, dt: f32) { + if let State::Crashed { since } = self.state { + if input.action && now - since >= CRASH_SECS { + self.restart(); + } + return; + } + + self.player_x = input + .steer(self.player_x, dt, PLAYER_KEY_SPEED, PLAYER_MAX_SPEED) + .clamp(0.5, self.width - 0.5); + self.trail.push_back((now, self.player_x)); + while self.trail.front().is_some_and(|&(t, _)| now - t > 0.1) { + self.trail.pop_front(); + } + + match self.state { + State::Ready if input.action => self.state = State::Falling, + State::Falling => { + let steps = (dt * STEPS_PER_SEC).ceil().max(1.0); + for i in 0..steps as u32 { + let step_time = now - dt + dt * (i + 1) as f32 / steps; + self.fall(dt / steps, step_time); + if self.state != State::Falling { + break; + } + } + } + _ => {} + } + } + + fn render(&self, now: f32) -> GreyGrid { + let mut light: Light = dark(self.width as usize); + + // How much of the span x0..x1 lies within a..b + let overlap = |x0: f32, x1: f32, a: f32, b: f32| (x1.min(b) - x0.max(a)).max(0.0); + for y in 0..HEIGHT { + for sample in 0..ROW_SAMPLES { + let depth = self.depth + y as f32 + (sample as f32 + 0.5) / ROW_SAMPLES as f32; + let (left, right) = self.walls(depth); + for (x, col) in light.iter_mut().enumerate() { + let (x0, x1) = (x as f32, x as f32 + 1.0); + let wall = overlap(x0, x1, f32::MIN, left) + overlap(x0, x1, right, f32::MAX); + let rim = + overlap(x0, x1, left - 1.0, left) + overlap(x0, x1, right, right + 1.0); + col[y] += (WALL_BRIGHTNESS * wall + RIM_BRIGHTNESS * rim) / ROW_SAMPLES as f32; + } + } + } + + for gem in &self.gems { + let y = gem.depth - self.depth; + let (size, brightness) = match gem.taken_at { + // Pulse while waiting to be taken + None => (GEM_SIZE, 0.6 + 0.3 * (now * 10.0).sin()), + // Grow and fade out when taken + Some(t) if now - t < GEM_FADE_SECS => { + let age = (now - t) / GEM_FADE_SECS; + (GEM_SIZE + 1.5 * age, 1.0 - age) + } + Some(_) => continue, + }; + let half = size / 2.0; + add_rect( + &mut light, + (gem.x - half, y - half), + (gem.x + half, y + half), + brightness, + ); + } + + match self.state { + State::Crashed { since } => { + if let Some(burst) = &self.burst { + burst.draw(&mut light, now - since, CRASH_SECS); + } + } + _ => { + // The trail streams upwards, the way the cave scrolls + for &(ago, brightness) in &TRAIL { + if let Some(&(_, x)) = self.trail.iter().rev().find(|&&(t, _)| now - t >= ago) { + add_square(&mut light, x, PLAYER_Y - self.speed * ago, brightness); + } + } + add_square(&mut light, self.player_x, PLAYER_Y, 1.0); + } + } + + let dim = match self.state { + State::Crashed { since } if now - since >= CRASH_SECS => 0.4, + _ => 1.0, + }; + to_grid(&light, dim) + } + + fn status(&self, fps: f64) -> String { + let state = match self.state { + State::Ready => "Space to start", + State::Falling => "", + State::Crashed { .. } => "Crashed! Space to try again, Q to quit", + }; + format!( + "Depth {} Gems {} Score {} Best {} Speed {:.0} {:.0} FPS {}", + self.depth as u32, + self.gems_taken, + self.score(), + self.best, + self.speed, + fps, + state + ) + } +} + +/// Play until the player quits, as fast as possible or limited to fps +pub fn cave_cmd(serialdevs: &[String], extend: bool, fps: Option) { + play( + serialdevs, + extend, + fps, + "Steer with the arrow keys, or move the mouse across this terminal. +Space or a click starts.", + Game::new, + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::inputmodule::WIDTH; + + /// Following the middle of the cave gets through, even at full speed and width + #[test] + fn autoplay_survives() { + // One LED matrix, and two side by side with --extend + for width in [WIDTH, 2 * WIDTH] { + let mut game = Game::new(width); + let mut input = Input { + action: true, + ..Default::default() + }; + let dt = 1.0 / 120.0; + let mut now = 0.0; + while now < 200.0 { + let (left, right) = game.walls(game.depth + PLAYER_Y + 1.0); + input.target = Some((left + right) / 2.0); + now += dt; + game.update(&mut input, now, dt); + game.render(now); + assert!( + !matches!(game.state, State::Crashed { .. }), + "Crashed at depth {}", + game.depth + ); + + for y in 0..HEIGHT { + let (left, right) = game.walls(game.depth + y as f32); + assert!( + left >= -0.01 && right <= game.width + 0.01, + "Cave leaves the screen" + ); + assert!( + right - left >= 2.0 * MIN_HALF_WIDTH - 0.01, + "Cave too narrow" + ); + } + } + assert_eq!(game.speed, MAX_SPEED); + println!("Depth {:.0}, {} gems", game.depth, game.gems_taken); + } + } +} diff --git a/inputmodule-control/src/flap.rs b/inputmodule-control/src/flap.rs new file mode 100644 index 00000000..1ef18d22 --- /dev/null +++ b/inputmodule-control/src/flap.rs @@ -0,0 +1,415 @@ +//! One-button flying game: flap to stay up, and fly through the gaps in the walls +//! that slide in from the right. Gravity pulls down along the tall side of the +//! matrix, so every flap is a long, smooth arc. + +use std::collections::VecDeque; + +use rand::prelude::*; + +use crate::hostgame::{add_rect, add_square, dark, play, to_grid, Burst, HostGame, Input, Light}; +use crate::inputmodule::{GreyGrid, HEIGHT}; + +/// Physics steps per second, independent of the frame rate +const STEPS_PER_SEC: f32 = 480.0; + +/// Center of the column the player flies in, near the left to see the walls coming +const PLAYER_X: f32 = 2.0; +/// Half the size of the player's hitbox. A bit smaller than the LED, +/// so just grazing a wall doesn't count. +const HITBOX: f32 = 0.35; +/// Faded copies of the player where it was this long ago, and how bright they are +const TRAIL: [(f32, f32); 3] = [(0.03, 0.3), (0.06, 0.15), (0.09, 0.07)]; + +/// In LEDs per second squared, and LEDs per second +const GRAVITY: f32 = 54.0; +const FLAP_SPEED: f32 = 18.0; +const MAX_FALL_SPEED: f32 = 25.0; + +/// Top of the bottom row, which is the ground +const GROUND: f32 = (HEIGHT - 1) as f32; +const GROUND_BRIGHTNESS: f32 = 0.25; + +/// How fast the walls slide in, in LEDs per second. A bit faster with every wall passed. +const START_SPEED: f32 = 4.0; +const SPEEDUP: f32 = 0.06; +const MAX_SPEED: f32 = 6.5; +/// Distance from one wall to the next +const WALL_SPACING: f32 = 6.0; +const WALL_BRIGHTNESS: f32 = 0.4; +/// Extra brightness at the edges of the gap, to see it better +const EDGE_BRIGHTNESS: f32 = 0.45; +/// Height of the gap in a wall, a bit smaller with every wall passed +const START_GAP: f32 = 10.0; +const GAP_SHRINK: f32 = 0.15; +const MIN_GAP: f32 = 6.5; +/// How fast the player can climb by flapping, on average. +/// The next gap is never higher than that allows. +const CLIMB_SPEED: f32 = 5.0; +/// The next gap is never lower than this below the last one +const MAX_DROP: f32 = 6.0; + +const CRASH_SECS: f32 = 1.0; + +#[derive(Clone)] +struct Wall { + /// Left edge, walls are one LED wide + x: f32, + gap_top: f32, + gap_bottom: f32, + passed: bool, +} + +#[derive(Clone, Copy, PartialEq)] +enum State { + /// Hovering until the first flap + Ready, + Flying, + Crashed { + since: f32, + }, +} + +#[derive(Clone)] +struct Game { + rng: ThreadRng, + /// Screen width in LEDs, one or more LED matrices side by side + width: f32, + state: State, + /// Center of the player + y: f32, + vel_y: f32, + speed: f32, + gap: f32, + walls: VecDeque, + /// How far the ground has scrolled, for its dashes + scrolled: f32, + score: u32, + best: u32, + burst: Option, + /// Recent heights of the player with the time, for the trail. Newest last. + trail: VecDeque<(f32, f32)>, +} + +impl Game { + fn new(width: usize) -> Self { + let mut game = Self { + rng: thread_rng(), + width: width as f32, + state: State::Ready, + y: 0.0, + vel_y: 0.0, + speed: START_SPEED, + gap: START_GAP, + walls: VecDeque::new(), + scrolled: 0.0, + score: 0, + best: 0, + burst: None, + trail: VecDeque::new(), + }; + game.restart(); + game + } + + fn restart(&mut self) { + self.state = State::Ready; + self.y = GROUND / 2.0; + self.vel_y = 0.0; + self.speed = START_SPEED; + self.gap = START_GAP; + self.walls.clear(); + self.score = 0; + self.trail.clear(); + self.add_walls(); + } + + /// Add walls until the next one is off the screen on the right, + /// and drop the ones that slid off on the left + fn add_walls(&mut self) { + while self + .walls + .back() + .is_none_or(|w| w.x < self.width + WALL_SPACING) + { + let (x, center) = match self.walls.back() { + // The first wall comes in after a moment + None => (self.width + 2.0, GROUND / 2.0), + Some(last) => { + let last_center = (last.gap_top + last.gap_bottom) / 2.0; + // Anywhere, but not higher than the player can climb in time. + // Falling is quick, but not too far either + let time = WALL_SPACING / self.speed; + let up = (CLIMB_SPEED * time).min(10.0); + let center = self.rng.gen_range(0.0..GROUND); + let center = center.clamp(last_center - up, last_center + MAX_DROP); + (last.x + WALL_SPACING, center) + } + }; + let half = self.gap / 2.0; + let center = center.clamp(half + 1.0, GROUND - half - 1.0); + self.walls.push_back(Wall { + x, + gap_top: center - half, + gap_bottom: center + half, + passed: false, + }); + } + while self.walls.front().is_some_and(|w| w.x + 1.0 < 0.0) { + self.walls.pop_front(); + } + } + + fn crashed(&self) -> bool { + if self.y + HITBOX > GROUND { + return true; + } + let (left, right) = (PLAYER_X - HITBOX, PLAYER_X + HITBOX); + let (top, bottom) = (self.y - HITBOX, self.y + HITBOX); + self.walls + .iter() + .any(|w| left < w.x + 1.0 && right > w.x && (top < w.gap_top || bottom > w.gap_bottom)) + } + + fn fly(&mut self, dt: f32, now: f32) { + self.vel_y = (self.vel_y + GRAVITY * dt).min(MAX_FALL_SPEED); + self.y += self.vel_y * dt; + // Bump against the top + if self.y - HITBOX < 0.0 { + self.y = HITBOX; + self.vel_y = 0.0; + } + + for wall in &mut self.walls { + wall.x -= self.speed * dt; + if !wall.passed && wall.x + 1.0 < PLAYER_X - HITBOX { + wall.passed = true; + self.score += 1; + self.speed = (self.speed + SPEEDUP).min(MAX_SPEED); + self.gap = (self.gap - GAP_SHRINK).max(MIN_GAP); + } + } + self.scrolled += self.speed * dt; + self.add_walls(); + + if self.crashed() { + self.state = State::Crashed { since: now }; + self.best = self.best.max(self.score); + self.burst = Some(Burst::new(&mut self.rng, PLAYER_X, self.y)); + } + } +} + +impl HostGame for Game { + fn player_x(&self) -> f32 { + PLAYER_X + } + + fn update(&mut self, input: &mut Input, now: f32, dt: f32) { + match self.state { + State::Crashed { since } => { + if input.action && now - since >= CRASH_SECS { + self.restart(); + } + return; + } + State::Ready => { + // Bob up and down while waiting + self.y = GROUND / 2.0 + (now * 4.0).sin() * 0.8; + if input.action { + self.state = State::Flying; + } + } + State::Flying => {} + } + + if self.state == State::Flying { + if input.action { + self.vel_y = -FLAP_SPEED; + } + let steps = (dt * STEPS_PER_SEC).ceil().max(1.0); + for i in 0..steps as u32 { + let step_time = now - dt + dt * (i + 1) as f32 / steps; + self.fly(dt / steps, step_time); + if self.state != State::Flying { + break; + } + } + } + + self.trail.push_back((now, self.y)); + while self.trail.front().is_some_and(|&(t, _)| now - t > 0.15) { + self.trail.pop_front(); + } + } + + fn render(&self, now: f32) -> GreyGrid { + let mut light: Light = dark(self.width as usize); + + // Dashed ground, scrolling along with the walls + let offset = self.scrolled % 2.0; + for i in 0..=self.width as usize / 2 + 1 { + let x = i as f32 * 2.0 - offset; + add_rect( + &mut light, + (x, GROUND), + (x + 1.0, GROUND + 1.0), + GROUND_BRIGHTNESS, + ); + } + + for wall in &self.walls { + let (left, right) = (wall.x, wall.x + 1.0); + add_rect( + &mut light, + (left, 0.0), + (right, wall.gap_top), + WALL_BRIGHTNESS, + ); + add_rect( + &mut light, + (left, wall.gap_bottom), + (right, GROUND), + WALL_BRIGHTNESS, + ); + let (top, bottom) = (wall.gap_top, wall.gap_bottom); + add_rect(&mut light, (left, top - 1.0), (right, top), EDGE_BRIGHTNESS); + add_rect( + &mut light, + (left, bottom), + (right, bottom + 1.0), + EDGE_BRIGHTNESS, + ); + } + + match self.state { + State::Crashed { since } => { + if let Some(burst) = &self.burst { + burst.draw(&mut light, now - since, CRASH_SECS); + } + } + _ => { + // The trail streams to the left, the way the walls slide + let speed = if self.state == State::Flying { + self.speed + } else { + 0.0 + }; + for &(ago, brightness) in &TRAIL { + if let Some(&(_, y)) = self.trail.iter().rev().find(|&&(t, _)| now - t >= ago) { + add_square(&mut light, PLAYER_X - speed * ago, y, brightness); + } + } + add_square(&mut light, PLAYER_X, self.y, 1.0); + } + } + + let dim = match self.state { + State::Crashed { since } if now - since >= CRASH_SECS => 0.4, + _ => 1.0, + }; + to_grid(&light, dim) + } + + fn status(&self, fps: f64) -> String { + let state = match self.state { + State::Ready => "Space to flap", + State::Flying => "", + State::Crashed { .. } => "Crashed! Space to try again, Q to quit", + }; + format!( + "Score {} Best {} Speed {:.1} {:.0} FPS {}", + self.score, self.best, self.speed, fps, state + ) + } +} + +/// Play until the player quits, as fast as possible or limited to fps +pub fn flap_cmd(serialdevs: &[String], extend: bool, fps: Option) { + play( + serialdevs, + extend, + fps, + "Space, up or a click flaps.", + Game::new, + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::inputmodule::WIDTH; + + /// Simple rule: flap whenever below the middle of the next gap, + /// but while in a wall or about to enter one, stay in its gap + fn greedy_flap(game: &Game) -> bool { + // A flap goes up about 3 LEDs, so aim a bit below the middle + let next = game.walls.iter().find(|w| w.x > PLAYER_X + HITBOX).unwrap(); + let mut target = (next.gap_top + next.gap_bottom) / 2.0 + 1.0; + let inside = |w: &&Wall| w.x < PLAYER_X + HITBOX + 1.0 && w.x + 1.0 > PLAYER_X - HITBOX; + if let Some(wall) = game.walls.iter().find(inside) { + target = target.clamp(wall.gap_top + 3.5, wall.gap_bottom - 1.0); + } + game.y > target && game.vel_y > 0.0 + } + + /// How long the game lasts after flapping or not, then following the simple rule + fn survives(mut game: Game, flap: bool, now: f32, dt: f32, secs: f32) -> f32 { + let mut input = Input { + action: flap, + ..Default::default() + }; + let mut t = 0.0; + while t < secs { + t += dt; + game.update(&mut input, now + t, dt); + if game.state != State::Flying { + return t; + } + input.action = greedy_flap(&game); + } + secs + } + + /// A player who looks ahead gets through every wall, even at full speed with + /// the smallest gaps, so the hardest walls are still fair + #[test] + fn autoplay_survives() { + // One LED matrix, and two side by side with --extend + for width in [WIDTH, 2 * WIDTH] { + let mut game = Game::new(width); + let mut input = Input::default(); + let dt = 1.0 / 60.0; + let lookahead = 1.0; + let mut now = 0.0; + while now < 150.0 { + let without = survives(game.clone(), false, now, dt, lookahead); + input.action = game.state == State::Ready + || if without < lookahead { + // Not flapping would crash, flap if that's better + survives(game.clone(), true, now, dt, lookahead) > without + } else { + // Nothing in the way yet, like while the first wall is far away + // on a wide screen. Head for the next gap. + greedy_flap(&game) + }; + now += dt; + game.update(&mut input, now, dt); + game.render(now); + assert!( + !matches!(game.state, State::Crashed { .. }), + "Crashed after {} walls at y {:.2}, speed {:.1}, walls {:?}", + game.score, + game.y, + game.vel_y, + game.walls + .iter() + .map(|w| (w.x, w.gap_top, w.gap_bottom)) + .collect::>() + ); + } + assert_eq!(game.speed, MAX_SPEED); + assert_eq!(game.gap, MIN_GAP); + println!("Passed {} walls", game.score); + } + } +} diff --git a/inputmodule-control/src/hostgame.rs b/inputmodule-control/src/hostgame.rs new file mode 100644 index 00000000..29401ec2 --- /dev/null +++ b/inputmodule-control/src/hostgame.rs @@ -0,0 +1,313 @@ +//! Shared parts of the games that run on the host and stream frames to the LED matrix: +//! drawing by area, terminal input and the frame loop. +//! +//! Positions are in LEDs, but not rounded to whole LEDs. Each LED lights up by how +//! much of it a shape covers, so things glide smoothly instead of jumping from LED +//! to LED. The higher the frame rate, the smoother it looks. + +use std::io::{stdout, Write}; +use std::time::{Duration, Instant}; + +use crossterm::event::{ + self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers, + KeyboardEnhancementFlags, MouseButton, MouseEventKind, PopKeyboardEnhancementFlags, + PushKeyboardEnhancementFlags, +}; +use crossterm::{cursor, execute, terminal}; +use rand::Rng; + +use crate::inputmodule::{GreyGrid, Matrices, HEIGHT}; + +pub const FIELD_H: f32 = HEIGHT as f32; + +/// Brightness of each LED, 1.0 is fully on. Adds up where shapes overlap. +/// Indexed [x][y], as wide as the screen, which can be several LED matrices. +pub type Light = Vec<[f32; HEIGHT]>; + +/// All LEDs off, for a screen this many LEDs wide +pub fn dark(width: usize) -> Light { + vec![[0.0; HEIGHT]; width] +} + +/// Light up the LEDs by how much of them the rectangle covers +pub fn add_rect(light: &mut Light, (x0, y0): (f32, f32), (x1, y1): (f32, f32), brightness: f32) { + let cols = (x0.floor().max(0.0) as usize)..(x1.ceil().min(light.len() as f32) as usize); + let rows = (y0.floor().max(0.0) as usize)..(y1.ceil().min(FIELD_H) as usize); + for x in cols { + let cover_x = x1.min(x as f32 + 1.0) - x0.max(x as f32); + for y in rows.clone() { + let cover_y = y1.min(y as f32 + 1.0) - y0.max(y as f32); + light[x][y] += brightness * cover_x * cover_y; + } + } +} + +/// A square one LED wide, centered on x, y +pub fn add_square(light: &mut Light, x: f32, y: f32, brightness: f32) { + add_rect(light, (x - 0.5, y - 0.5), (x + 0.5, y + 0.5), brightness); +} + +/// Sparks flying apart from a point, like when the player crashes +#[derive(Clone)] +pub struct Burst { + x: f32, + y: f32, + /// Velocity of each spark in LEDs per second + sparks: Vec<(f32, f32)>, +} + +impl Burst { + pub fn new(rng: &mut impl Rng, x: f32, y: f32) -> Self { + const SPARKS: usize = 14; + let sparks = (0..SPARKS) + .map(|i| { + // Evenly around the circle, a bit random so it's different every time + let angle = + i as f32 / SPARKS as f32 * std::f32::consts::TAU + rng.gen_range(0.0..0.4); + let speed = rng.gen_range(3.0..10.0); + (speed * angle.cos(), speed * angle.sin()) + }) + .collect(); + Self { x, y, sparks } + } + + /// Draw it age seconds after it started, faded out after duration + pub fn draw(&self, light: &mut Light, age: f32, duration: f32) { + let age = age.clamp(0.0, duration); + let fade = 1.0 - age / duration; + for &(vel_x, vel_y) in &self.sparks { + add_square( + light, + self.x + vel_x * age, + self.y + vel_y * age, + 0.8 * fade, + ); + } + } +} + +/// Convert to a frame for the LED matrix, scaling everything by dim +pub fn to_grid(light: &Light, dim: f32) -> GreyGrid { + light + .iter() + .map(|col| { + // Linear instead of gamma, so the total light stays the same while moving + col.map(|l| (l.clamp(0.0, 1.0) * dim * 255.0) as u8) + }) + .collect() +} + +/// What the player wants, collected from terminal events +#[derive(Default)] +pub struct Input { + /// Where the player should go, from the mouse or arrow key presses + pub target: Option, + /// Arrow keys currently held, only known if the terminal reports key releases + pub held_left: bool, + pub held_right: bool, + /// Space, Enter, up arrow or a click since the last update + pub action: bool, + /// Every key pressed since the last update, including key repeats, in order + pub presses: Vec, + pub quit: bool, +} + +impl Input { + /// Move x the way the player steers: at key_speed while an arrow key is held, + /// otherwise towards the mouse or the last key press, at most at max_speed + pub fn steer(&mut self, x: f32, dt: f32, key_speed: f32, max_speed: f32) -> f32 { + let held = self.held_right as i32 - self.held_left as i32; + if held != 0 { + self.target = None; + x + held as f32 * key_speed * dt + } else if let Some(target) = self.target { + let max_step = max_speed * dt; + x + (target - x).clamp(-max_step, max_step) + } else { + x + } + } +} + +/// A game that runs on the host, see play() +pub trait HostGame { + /// Where the player is, arrow key presses move on from there + fn player_x(&self) -> f32; + /// Advance to now, dt seconds after the last update + fn update(&mut self, input: &mut Input, now: f32, dt: f32); + fn render(&self, now: f32) -> GreyGrid; + /// One line for the terminal, like the score + fn status(&self, fps: f64) -> String; +} + +/// Puts the terminal into raw mode with mouse reporting, and back when dropped, +/// even if the game panics +struct RawTerminal { + /// Whether the terminal reports key releases, so keys can be held + key_releases: bool, +} + +impl RawTerminal { + fn new() -> std::io::Result { + terminal::enable_raw_mode()?; + execute!(stdout(), EnableMouseCapture, cursor::Hide)?; + // Windows always reports releases, other terminals only with the kitty keyboard protocol + let enhanced = matches!(terminal::supports_keyboard_enhancement(), Ok(true)); + if enhanced { + execute!( + stdout(), + PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::REPORT_EVENT_TYPES) + )?; + } + Ok(Self { + key_releases: enhanced || cfg!(windows), + }) + } +} + +impl Drop for RawTerminal { + fn drop(&mut self) { + if self.key_releases && !cfg!(windows) { + let _ = execute!(stdout(), PopKeyboardEnhancementFlags); + } + let _ = execute!(stdout(), DisableMouseCapture, cursor::Show); + let _ = terminal::disable_raw_mode(); + println!(); + } +} + +/// Apply all pending terminal events to the input, for a screen width LEDs wide +fn read_input( + input: &mut Input, + key_releases: bool, + player_x: f32, + width: f32, +) -> std::io::Result<()> { + while event::poll(Duration::ZERO)? { + match event::read()? { + Event::Key(key) => { + let pressed = key.kind != KeyEventKind::Release; + if pressed { + input.presses.push(key.code); + } + let ctrl_c = + key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL); + let dir = match key.code { + KeyCode::Left | KeyCode::Char('a') | KeyCode::Char('h') => -1.0, + KeyCode::Right | KeyCode::Char('d') | KeyCode::Char('l') => 1.0, + _ => 0.0, + }; + if dir != 0.0 { + if key_releases { + if dir < 0.0 { + input.held_left = pressed; + } else { + input.held_right = pressed; + } + } else if pressed { + // Without releases, every press and key repeat moves by one LED + let from = input.target.unwrap_or(player_x); + input.target = Some(from + dir); + } + } else if pressed { + match key.code { + KeyCode::Char(' ') | KeyCode::Up | KeyCode::Enter => input.action = true, + KeyCode::Char('q') | KeyCode::Esc => input.quit = true, + _ if ctrl_c => input.quit = true, + _ => {} + } + } + } + Event::Mouse(mouse) => { + // The width of the terminal maps to the width of the screen + let (cols, _) = terminal::size()?; + let x = (mouse.column as f32 + 0.5) / cols.max(1) as f32 * width; + match mouse.kind { + MouseEventKind::Moved | MouseEventKind::Drag(_) => input.target = Some(x), + MouseEventKind::Down(MouseButton::Left) => input.action = true, + _ => {} + } + } + _ => {} + } + } + Ok(()) +} + +/// Play until the player quits, as fast as possible or limited to fps. +/// help explains the controls. new_game makes the game for a screen that many LEDs wide. +/// With extend, that's all LED matrices side by side. +pub fn play( + serialdevs: &[String], + extend: bool, + fps: Option, + help: &str, + new_game: impl FnOnce(usize) -> G, +) { + let mut matrices = Matrices::open(serialdevs, extend); + let width = matrices.width(); + let mut game = new_game(width); + println!("{} Q or Esc quits.", help); + + let term = RawTerminal::new().expect("Failed to set up the terminal"); + let mut input = Input::default(); + + let start = Instant::now(); + let mut last = 0.0; + let mut frames: u64 = 0; + let mut fps_frames = 0; + let mut fps_since = start; + let mut measured_fps = 0.0; + loop { + read_input(&mut input, term.key_releases, game.player_x(), width as f32) + .expect("Failed to read input"); + if input.quit { + break; + } + let now = start.elapsed().as_secs_f32(); + // Don't jump ahead after a hiccup, like the matrix not responding for a while + let dt = (now - last).min(0.05); + last = now; + game.update(&mut input, now, dt); + input.action = false; + input.presses.clear(); + matrices.send(&game.render(now)); + frames += 1; + + fps_frames += 1; + if fps_since.elapsed() >= Duration::from_millis(500) { + measured_fps = fps_frames as f64 / fps_since.elapsed().as_secs_f64(); + fps_frames = 0; + fps_since = Instant::now(); + print!("\r{}\x1b[K", game.status(measured_fps)); + let _ = stdout().flush(); + } + + if let Some(fps) = fps { + let next_frame = start + Duration::from_secs_f64(frames as f64 / fps as f64); + if let Some(wait) = next_frame.checked_duration_since(Instant::now()) { + std::thread::sleep(wait); + } + } + } + + // Leave the matrix dark instead of on the last frame + matrices.clear(); + drop(term); + println!("{}", game.status(measured_fps)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn square_covers_partial_leds() { + let mut light = dark(crate::inputmodule::WIDTH); + add_square(&mut light, 1.25, 1.5, 1.0); + let total: f32 = light.iter().flatten().sum(); + assert!((total - 1.0).abs() < 1e-5); + assert!((light[0][1] - 0.25).abs() < 1e-5); + assert!((light[1][1] - 0.75).abs() < 1e-5); + } +} diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index 8008cbb4..bab63a65 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -11,12 +11,13 @@ use serialport::{SerialPort, SerialPortInfo, SerialPortType}; use crate::b1display::{B1Pattern, Fps, PowerMode}; use crate::c1minimal::Color; use crate::font::{convert_font, convert_symbol}; -use crate::ledmatrix::{Game, GameOfLifeStartParam, Pattern}; +use crate::ledmatrix::{BenchmarkMode, Demo, Game, GameOfLifeStartParam, Pattern}; const FWK_MAGIC: &[u8] = &[0x32, 0xAC]; pub const FRAMEWORK_VID: u16 = 0x32AC; pub const LED_MATRIX_PID: u16 = 0x0020; pub const B1_LCD_PID: u16 = 0x0021; +pub const C1_MINIMAL_PID: u16 = 0x0022; type Brightness = u8; @@ -50,6 +51,7 @@ enum Command { PwmFreq = 0x1E, DebugMode = 0x1F, Version = 0x20, + Stats = 0x21, } enum GameControlArg { @@ -62,30 +64,31 @@ enum GameControlArg { _SecondRight = 6, } -const WIDTH: usize = 9; -const HEIGHT: usize = 34; +pub const WIDTH: usize = 9; +pub const HEIGHT: usize = 34; const SERIAL_TIMEOUT: Duration = Duration::from_millis(20); fn match_serialdevs( ports: &[SerialPortInfo], - requested: &Option, + requested: &[String], pid: Option, ) -> Vec { - if let Some(requested) = requested { - for p in ports { - if requested == &p.port_name { - return vec![p.port_name.clone()]; - } + if !requested.is_empty() { + // All of them in the order requested, or none if one is missing + let found = |name: &String| ports.iter().any(|p| &p.port_name == name); + if requested.iter().all(found) { + requested.to_vec() + } else { + vec![] } - vec![] } else { let mut compatible_devs = vec![]; let pids = if let Some(pid) = pid { vec![pid] } else { // By default accept any type - vec![LED_MATRIX_PID, B1_LCD_PID, 0x22, 0xFF] + vec![LED_MATRIX_PID, B1_LCD_PID, C1_MINIMAL_PID, 0xFF] }; // Find all supported Framework devices for p in ports { @@ -124,6 +127,22 @@ pub fn find_serialdevs(args: &crate::ClapCli, wait_for_device: bool) -> (Vec println!(" FW {}", version), + Err(err) => println!(" FW unknown ({})", err), + } + } } _ => { //println!("{}", p.port_name); @@ -246,7 +265,31 @@ pub fn serial_commands(args: &crate::ClapCli) { if ledmatrix_args.version { get_device_version(serialdev); } + if let Some(secs) = ledmatrix_args.benchmark { + benchmark_cmd( + serialdev, + Duration::from_secs(secs), + ledmatrix_args.benchmark_mode, + ); + } } + + // Streaming to all LED matrices side by side. Without --serial-dev, they're + // found in no particular order. Order them by their slot in the + // Framework 16 input deck. Else at least the same every time. + let extend = ledmatrix_args.extend; + let mut serialdevs = serialdevs; + if extend && args.serial_dev.is_empty() { + // Known slots first, then COM9 before COM10 + serialdevs.sort_by_cached_key(|dev| { + let slot = crate::usbport::fw16_position_of(dev); + (slot.is_none(), slot, dev.len(), dev.clone()) + }); + if args.verbose { + println!("Left to right: {:?}", serialdevs); + } + } + // Commands that block and need manual looping if ledmatrix_args.blinking { blinking_cmd(&serialdevs); @@ -267,6 +310,41 @@ pub fn serial_commands(args: &crate::ClapCli) { if ledmatrix_args.clock { clock_cmd(&serialdevs); } + + if let Some(path) = &ledmatrix_args.video { + video_cmd(&serialdevs, extend, path, ledmatrix_args.fps); + } + + if let Some(device) = &ledmatrix_args.camera { + camera_cmd(&serialdevs, extend, device.as_deref(), ledmatrix_args.fps); + } + + if ledmatrix_args.bricks { + crate::bricks::bricks_cmd(&serialdevs, extend, ledmatrix_args.fps); + } + + if ledmatrix_args.cave { + crate::cave::cave_cmd(&serialdevs, extend, ledmatrix_args.fps); + } + + if ledmatrix_args.flap { + crate::flap::flap_cmd(&serialdevs, extend, ledmatrix_args.fps); + } + + if ledmatrix_args.ledris { + crate::ledris::ledris_cmd(&serialdevs, extend, ledmatrix_args.fps); + } + + if let Some(demo) = ledmatrix_args.demo { + demo_cmd( + &serialdevs, + extend, + demo, + &ledmatrix_args.demo_text, + &ledmatrix_args.demo_minutes, + ledmatrix_args.fps, + ); + } } Some(crate::Commands::B1Display(b1display_args)) => { for serialdev in &serialdevs { @@ -345,27 +423,41 @@ pub fn serial_commands(args: &crate::ClapCli) { } } -fn get_device_version(serialdev: &str) { +/// Ask the firmware for its version, formatted like "0.2.1" or "0.2.1 (Pre-Release)" +fn query_device_version(serialdev: &str) -> Result { + // Longer than SERIAL_TIMEOUT, the first response after opening the port + // sometimes takes longer than 20ms let mut port = serialport::new(serialdev, 115_200) - .timeout(SERIAL_TIMEOUT) + .timeout(Duration::from_millis(500)) .open() - .expect("Failed to open port"); + .map_err(|e| format!("failed to open port: {e}"))?; - simple_cmd_port(&mut port, Command::Version, &[]); + let mut buffer = [0; 3]; + buffer[..2].copy_from_slice(FWK_MAGIC); + buffer[2] = Command::Version as u8; + port.write_all(&buffer) + .map_err(|e| format!("write failed: {e}"))?; - let mut response: Vec = vec![0; 32]; - port.read_exact(response.as_mut_slice()) - .expect("Found no data!"); + let mut response = [0; 32]; + port.read_exact(&mut response) + .map_err(|e| format!("no response: {e}"))?; let major = response[0]; let minor = (response[1] & 0xF0) >> 4; let patch = response[1] & 0x0F; let pre_release = response[2] == 1; - print!("Device Version: {major}.{minor}.{patch}"); + let mut version = format!("{major}.{minor}.{patch}"); if pre_release { - print!(" (Pre-Release)"); + version.push_str(" (Pre-Release)"); + } + Ok(version) +} + +fn get_device_version(serialdev: &str) { + match query_device_version(serialdev) { + Ok(version) => println!("Device Version: {version}"), + Err(err) => println!("Failed to get device version: {err}"), } - println!(); } fn bootloader_cmd(serialdev: &str) { @@ -530,6 +622,271 @@ fn commit_cols(port: &mut Box) { simple_cmd_port(port, Command::CommitCols, &[]); } +/// Performance counters of the LED matrix firmware, see Stats in matrix_sync.rs +#[derive(Debug, Clone, Copy)] +struct DeviceStats { + bytes_received: u32, + cmds_parsed: u32, + cmds_rejected: u32, + frames_committed: u32, + flushes: u32, + flush_us_total: u32, + flush_us_max: u32, + loop_us_max: u32, + loops: u32, + idle_loops: u32, + idle_us_total: u32, + busy_us_total: u32, + calcs: u32, + calc_us_total: u32, + calc_us_max: u32, + wait_us_total: u32, + led_power_ons: u32, + led_off_us_total: u32, +} + +/// Read one page of performance counters. None if the firmware doesn't support it. +fn get_stats_page(port: &mut Box, page: u8) -> Option<[u32; 8]> { + simple_cmd_port(port, Command::Stats, &[page]); + + let mut response = [0; 32]; + port.read_exact(&mut response).ok()?; + let mut vals = [0; 8]; + for (i, val) in vals.iter_mut().enumerate() { + *val = u32::from_le_bytes(response[i * 4..i * 4 + 4].try_into().unwrap()); + } + Some(vals) +} + +/// Read the performance counters. None if the firmware doesn't support it. +/// Also acts as a barrier, the firmware only responds after processing all previous commands. +/// Sends three commands of 4 bytes each. +fn get_stats(port: &mut Box) -> Option { + let page0 = get_stats_page(port, 0)?; + let page1 = get_stats_page(port, 1)?; + let page2 = get_stats_page(port, 2)?; + Some(DeviceStats { + bytes_received: page0[0], + cmds_parsed: page0[1], + cmds_rejected: page0[2], + frames_committed: page0[3], + flushes: page0[4], + flush_us_total: page0[5], + flush_us_max: page0[6], + loop_us_max: page0[7], + loops: page1[0], + idle_loops: page1[1], + idle_us_total: page1[2], + busy_us_total: page1[3], + calcs: page1[4], + calc_us_total: page1[5], + calc_us_max: page1[6], + wait_us_total: page1[7], + led_power_ons: page2[0], + led_off_us_total: page2[1], + }) +} + +/// Wake up the LED matrix and wait until it's done fading in. +/// While fading in, the firmware doesn't service USB, so sending frames would stall. +/// The port needs a long enough timeout. +fn wake_and_wait(port: &mut Box) { + simple_cmd_port(port, Command::Sleeping, &[0]); + // Only responds after the fade-in, because commands are handled in order + simple_cmd_port(port, Command::Version, &[]); + let mut response = [0; 32]; + port.read_exact(&mut response) + .expect("Device didn't respond to version request"); +} + +/// Stream changing greyscale frames as fast as possible and report the throughput +fn benchmark_cmd(serialdev: &str, duration: Duration, mode: BenchmarkMode) { + // Long timeout, because the firmware doesn't service USB while fading in after waking up + let mut port = serialport::new(serialdev, 115_200) + .timeout(Duration::from_secs(10)) + .open() + .expect("Failed to open port"); + + // So the fade-in doesn't count towards the benchmark + wake_and_wait(&mut port); + + // Old firmware doesn't respond to the stats command, don't wait too long + port.set_timeout(Duration::from_millis(500)).unwrap(); + let before = get_stats(&mut port); + port.set_timeout(Duration::from_secs(10)).unwrap(); + if before.is_none() { + println!("Firmware doesn't support stats, only measuring host side throughput"); + // Make sure the unknown command doesn't leave anything behind + let _ = port.clear(serialport::ClearBuffer::All); + } + + let mut frames: u32 = 0; + let mut cmds: u32 = 0; + let mut bytes: u32 = 0; + // How long each write call blocked + let mut write_times: Vec = vec![]; + let start = std::time::Instant::now(); + while start.elapsed() < duration { + // Bright row moving down, so that every frame is different + let head = frames as usize % HEIGHT; + match mode { + BenchmarkMode::Grey => { + // With a fading tail + for x in 0..WIDTH { + let mut vals = [0; HEIGHT]; + for (y, val) in vals.iter_mut().enumerate() { + let dist = (head + HEIGHT - y) % HEIGHT; + *val = 255usize.saturating_sub(dist * 32) as u8; + } + let write_start = std::time::Instant::now(); + send_col(&mut port, x as u8, &vals); + write_times.push(write_start.elapsed()); + bytes += 3 + 1 + HEIGHT as u32; + } + let write_start = std::time::Instant::now(); + commit_cols(&mut port); + write_times.push(write_start.elapsed()); + bytes += 3; + cmds += WIDTH as u32 + 1; + } + BenchmarkMode::Bw => { + let mut vals = [0; 39]; + for x in 0..WIDTH { + let i = x + head * WIDTH; + vals[i / 8] |= 1 << (i % 8); + } + let write_start = std::time::Instant::now(); + simple_cmd_port(&mut port, Command::DisplayBwImage, &vals); + write_times.push(write_start.elapsed()); + bytes += 3 + vals.len() as u32; + cmds += 1; + } + BenchmarkMode::Idle => { + thread::sleep(duration); + break; + } + } + frames += 1; + } + + // Wait until the device processed everything + let after = if before.is_some() { + get_stats(&mut port) + } else { + simple_cmd_port(&mut port, Command::Version, &[]); + let mut response = [0; 32]; + port.read_exact(&mut response) + .expect("Device didn't respond after benchmark"); + None + }; + let elapsed = start.elapsed().as_secs_f64(); + + println!("Duration: {:.2}s", elapsed); + println!("Frames sent: {}", frames); + println!( + "Host send rate: {:.1} FPS ({:.1} KiB/s)", + frames as f64 / elapsed, + bytes as f64 / elapsed / 1024.0 + ); + + write_times.sort(); + let write_total: Duration = write_times.iter().sum(); + if !write_times.is_empty() { + let percentile = |p: usize| write_times[(write_times.len() - 1) * p / 100].as_micros(); + println!( + "Host write time: {}us avg, {}us p50, {}us p99, {}us max, {:.0}% of total time", + write_total.as_micros() / write_times.len() as u128, + percentile(50), + percentile(99), + percentile(100), + write_total.as_secs_f64() / elapsed * 100.0 + ); + } + + let (Some(before), Some(after)) = (before, after) else { + return; + }; + let delta = |f: fn(&DeviceStats) -> u32| f(&after).wrapping_sub(f(&before)); + // The second and third request of the first get_stats and the first request + // of the last get_stats are counted too, one command of 4 bytes each + let bytes_received = delta(|s| s.bytes_received).wrapping_sub(12); + let cmds_parsed = delta(|s| s.cmds_parsed).wrapping_sub(3); + let cmds_rejected = delta(|s| s.cmds_rejected); + let frames_committed = delta(|s| s.frames_committed); + let flushes = delta(|s| s.flushes); + let flush_us_total = delta(|s| s.flush_us_total); + + println!("Bytes received: {} of {} sent", bytes_received, bytes); + println!( + "Commands: {} parsed, {} rejected, {} lost", + cmds_parsed, + cmds_rejected, + cmds.saturating_sub(cmds_parsed + cmds_rejected) + ); + println!( + "Frames committed: {} of {} ({:.1} FPS)", + frames_committed, + frames, + frames_committed as f64 / elapsed + ); + println!( + "I2C flushes: {} ({:.1} FPS, {:.1} per frame)", + flushes, + flushes as f64 / elapsed, + flushes as f64 / frames_committed.max(1) as f64 + ); + println!( + "I2C flush time: {:.0}us avg, {}us max, {:.0}% of total time", + flush_us_total as f64 / flushes.max(1) as f64, + after.flush_us_max, + flush_us_total as f64 / 1e6 / elapsed * 100.0 + ); + println!("Main loop: {}us max", after.loop_us_max); + + let loops = delta(|s| s.loops); + let idle_loops = delta(|s| s.idle_loops); + let busy_loops = loops - idle_loops; + let idle_us = delta(|s| s.idle_us_total) as f64; + let busy_us = delta(|s| s.busy_us_total) as f64; + let device_us = (idle_us + busy_us).max(1.0); + println!( + "Device busy: {} loops with data, {:.0}us avg, {:.0}% of device time", + busy_loops, + busy_us / busy_loops.max(1) as f64, + busy_us / device_us * 100.0 + ); + println!( + "Device idle: {} loops without data, {:.0}us avg, {:.0}% of device time", + idle_loops, + idle_us / idle_loops.max(1) as f64, + idle_us / device_us * 100.0 + ); + + let calcs = delta(|s| s.calcs); + let calc_us = delta(|s| s.calc_us_total) as f64; + println!( + "PWM calculation: {} times ({:.1} per command), {:.0}us avg, {}us max, {:.0}% of device time", + calcs, + calcs as f64 / cmds_parsed.max(1) as f64, + calc_us / calcs.max(1) as f64, + after.calc_us_max, + calc_us / device_us * 100.0 + ); + + let wait_us = delta(|s| s.wait_us_total) as f64; + println!( + "CPU asleep: {:.0}% of device time", + wait_us / device_us * 100.0 + ); + + let led_off_us = delta(|s| s.led_off_us_total) as f64; + println!( + "LED controller: off {:.0}% of device time, powered on {} times", + led_off_us / device_us * 100.0, + delta(|s| s.led_power_ons) + ); +} + ///Increase the brightness with each pixel. ///Only 0-255 available, so it can't fill all 306 LEDs fn all_brightnesses_cmd(serialdev: &str) { @@ -664,6 +1021,739 @@ fn display_gray_image_cmd(serialdev: &str, image_path: &str) { commit_cols(&mut port); } +/// Greyscale frame, indexed [x][y]. As wide as one LED matrix, +/// or as all of them side by side with --extend. +pub type GreyGrid = Vec<[u8; HEIGHT]>; + +/// Make dim values dimmer, so the LEDs show more contrast +fn gamma(brightness: f32) -> u8 { + let brightness = brightness.clamp(0.0, 1.0); + (brightness * brightness * 255.0) as u8 +} + +/// Overlapping sine waves, depends only on the time, not on the frame rate +fn plasma_frame(t: f32, width: usize) -> GreyGrid { + let mut grid = vec![[0; HEIGHT]; width]; + // Center of the circular wave moves around + let half = width as f32 / 2.0; + let cx = half - 0.5 + (t * 0.5).sin() * (half - 1.5); + let cy = 17.0 + (t * 0.3).cos() * 12.0; + for (x, col) in grid.iter_mut().enumerate() { + for (y, val) in col.iter_mut().enumerate() { + let (fx, fy) = (x as f32, y as f32); + let dist = ((fx - cx).powi(2) + (fy - cy).powi(2)).sqrt(); + let v = (fx * 0.7 + t * 1.1).sin() + + (fy * 0.23 - t * 1.7).sin() + + (fx * 0.5 + fy * 0.15 + t * 0.9).sin() + + (dist * 0.35 - t * 2.0).sin(); + // v is in -4..4 + *val = gamma(0.5 + 0.5 * (v * std::f32::consts::FRAC_PI_2).sin()); + } + } + grid +} + +/// Fire simulation steps per second, independent of the frame rate +const FIRE_STEPS_PER_SEC: f32 = 30.0; + +/// Fire effect like in PSX Doom: heat rises from the bottom row, cools down and drifts sideways +struct Fire { + /// Heat from 0.0 to 1.0 after the previous and the next simulation step + prev: Vec<[f32; HEIGHT]>, + next: Vec<[f32; HEIGHT]>, + steps: u64, + rng: ThreadRng, +} + +impl Fire { + fn new(width: usize) -> Self { + Self { + prev: vec![[0.0; HEIGHT]; width], + next: vec![[0.0; HEIGHT]; width], + steps: 0, + rng: thread_rng(), + } + } + + fn step(&mut self) { + self.prev.clone_from(&self.next); + let heat = &mut self.next; + let width = heat.len(); + // Flickering source of heat in the bottom row + for col in heat.iter_mut() { + col[HEIGHT - 1] = self.rng.gen_range(0.6..1.0); + } + // Each pixel takes the heat of the pixel below, cooled down and moved sideways. + // Top to bottom, so every row only moves up by one per step. + for y in 0..HEIGHT - 1 { + for x in 0..width { + let drift: isize = self.rng.gen_range(-1..=1); + let to_x = (x as isize + drift).clamp(0, width as isize - 1) as usize; + let cooling = self.rng.gen_range(0.0..0.09); + heat[to_x][y] = (heat[x][y + 1] - cooling).max(0.0); + } + } + self.steps += 1; + } + + /// Blend between simulation steps, so it's smooth at frame rates above the step rate + fn frame(&mut self, t: f32) -> GreyGrid { + let pos = t * FIRE_STEPS_PER_SEC; + while self.steps <= pos as u64 + 1 { + self.step(); + } + let blend = pos - (self.steps - 2) as f32; + let mut grid = vec![[0; HEIGHT]; self.next.len()]; + for (x, col) in grid.iter_mut().enumerate() { + for (y, val) in col.iter_mut().enumerate() { + let heat = self.prev[x][y] + (self.next[x][y] - self.prev[x][y]) * blend; + *val = gamma(heat); + } + } + grid + } +} + +/// Rows per second that the text moves up +const TEXT_ROWS_PER_SEC: f32 = 12.0; + +/// Text stacked vertically, scrolling up by fractions of a pixel. +/// On several LED matrices side by side, it continues like columns in a newspaper: +/// from the top of the left one down to its bottom, then on the next one. +struct ScrollingText { + /// Brightness from 0.0 to 1.0 of each row of the rendered text, starting with an empty screen + rows: Vec<[f32; WIDTH]>, + /// How many LED matrices the text continues on + matrices: usize, +} + +impl ScrollingText { + fn new(text: &str, width: usize) -> Self { + let matrices = (width / WIDTH).max(1); + // Start with all screens empty, so the text scrolls in from the bottom and out at the top + let mut rows = vec![[0.0; WIDTH]; HEIGHT * matrices]; + // Same layout as show_font: 5x6 pixel characters, two columns from the left, one row apart + for c in text.to_uppercase().chars() { + let pixels = convert_font(c); + for y in 0..6 { + let mut row = [0.0; WIDTH]; + for x in 0..5 { + row[2 + x] = pixels[x + y * 5] as f32; + } + rows.push(row); + } + rows.push([0.0; WIDTH]); + } + Self { rows, matrices } + } + + /// Blend between neighboring rows, so the text glides instead of jumping by whole pixels + fn frame(&self, t: f32) -> GreyGrid { + let len = self.rows.len(); + let offset = (t * TEXT_ROWS_PER_SEC) % len as f32; + let mut grid = vec![[0; HEIGHT]; WIDTH * self.matrices]; + for matrix in 0..self.matrices { + for y in 0..HEIGHT { + let pos = offset + (matrix * HEIGHT + y) as f32; + let blend = pos.fract(); + let upper = &self.rows[pos as usize % len]; + let lower = &self.rows[(pos as usize + 1) % len]; + for x in 0..WIDTH { + // Linear instead of gamma, so the total light stays the same while moving + let brightness = upper[x] * (1.0 - blend) + lower[x] * blend; + grid[matrix * WIDTH + x][y] = (brightness * 255.0) as u8; + } + } + } + grid + } +} + +/// Each LED is split into this many sand cells per side, so grains move by a fraction of an LED +const SAND_SUB: usize = 4; +const SAND_H: usize = HEIGHT * SAND_SUB; +/// First row of the bottom chamber, the neck is between this and the row above +const SAND_NECK: usize = SAND_H / 2; +/// Sand simulation steps per second, grains fall by one cell per step +const SAND_STEPS_PER_SEC: f32 = 60.0; +/// Share of one chamber that's filled with sand +const SAND_FILL: f32 = 0.65; +/// Brightness of the LEDs that the edge of the glass goes through +const GLASS_BRIGHTNESS: f32 = 0.06; +/// How long the sand blinks after running out, before the hourglass flips over +const SAND_BLINK_SECS: f32 = 2.0; + +/// One flag per sand cell, indexed like GreyGrid: [x][y] +type SandGrid = Vec<[bool; SAND_H]>; + +/// Whether a sand cell is inside the glass. +/// Two chambers, joined by a neck two cells wide. Towards the neck and the ends, +/// the walls slant by one cell per row, which is the steepest slope sand can rest on, +/// so it all runs out. +fn inside_glass(x: usize, y: usize, sand_w: usize) -> bool { + let (to_neck, to_end) = if y < SAND_NECK { + (SAND_NECK - 1 - y, y) + } else { + (y - SAND_NECK, SAND_H - 1 - y) + }; + let half = sand_w / 2; + // The ends are a bit less than half as wide as the middle + let end = half * 4 / 9; + let half_width = half.min(1 + to_neck).min(end + to_end); + (half - half_width..half + half_width).contains(&x) +} + +/// Hourglass timer with falling sand. Lets sand through the neck just fast enough +/// that the top chamber runs out when the time is up. Then it blinks, flips over +/// and starts the next timer. +struct Hourglass { + glass: SandGrid, + /// LEDs that the edge of the glass goes through, to show its outline + edge: Vec<[bool; HEIGHT]>, + /// Sand after the previous and the next simulation step + prev: SandGrid, + next: SandGrid, + steps: u64, + rng: ThreadRng, + /// Seconds of each timer, repeating + timers: Vec, + timer: usize, + /// Simulation time when the current timer is up + timer_end: f32, + /// Grains in the top chamber + top: usize, + /// How many grains may pass the neck, adds up to whole grains over several steps + allowance: f32, + /// Simulation time when the top chamber ran empty and all sand settled + empty_since: Option, +} + +impl Hourglass { + fn new(minutes: &[f32], width: usize) -> Self { + let sand_w = width * SAND_SUB; + let mut glass = vec![[false; SAND_H]; sand_w]; + for (x, col) in glass.iter_mut().enumerate() { + for (y, cell) in col.iter_mut().enumerate() { + *cell = inside_glass(x, y, sand_w); + } + } + + let mut edge = vec![[false; HEIGHT]; width]; + for (x, col) in edge.iter_mut().enumerate() { + for (y, led) in col.iter_mut().enumerate() { + let inside = (0..SAND_SUB * SAND_SUB) + .filter(|i| glass[x * SAND_SUB + i % SAND_SUB][y * SAND_SUB + i / SAND_SUB]) + .count(); + *led = inside > 0 && inside < SAND_SUB * SAND_SUB; + } + } + + // Fill the top chamber from the neck upwards, whole rows at a time + let chamber: usize = glass.iter().flatten().filter(|&&cell| cell).count() / 2; + let mut sand = vec![[false; SAND_H]; sand_w]; + let mut grains = 0; + for y in (0..SAND_NECK).rev() { + let row = (0..sand_w).filter(|&x| glass[x][y]).count(); + if (grains + row) as f32 > chamber as f32 * SAND_FILL { + break; + } + for x in 0..sand_w { + sand[x][y] = glass[x][y]; + } + grains += row; + } + + let timers: Vec = minutes.iter().map(|m| m * 60.0).collect(); + Self { + glass, + edge, + prev: sand.clone(), + next: sand, + steps: 0, + rng: thread_rng(), + timer_end: timers[0], + timers, + timer: 0, + top: grains, + allowance: 0.0, + empty_since: None, + } + } + + /// Turn upside down and start the next timer + fn flip(&mut self, now: f32) { + let old = self.next.clone(); + let sand_w = old.len(); + for x in 0..sand_w { + for y in 0..SAND_H { + self.next[x][y] = old[sand_w - 1 - x][SAND_H - 1 - y]; + } + } + // Don't blend between before and after flipping + self.prev.clone_from(&self.next); + self.top = self + .next + .iter() + .flat_map(|col| &col[..SAND_NECK]) + .filter(|&&g| g) + .count(); + self.allowance = 0.0; + self.empty_since = None; + self.timer = (self.timer + 1) % self.timers.len(); + self.timer_end = now + self.timers[self.timer]; + } + + fn step(&mut self) { + self.prev.clone_from(&self.next); + let dt = 1.0 / SAND_STEPS_PER_SEC; + let now = self.steps as f32 * dt; + self.steps += 1; + + if let Some(empty_since) = self.empty_since { + if now - empty_since >= SAND_BLINK_SECS { + self.flip(now); + } + return; + } + + // Spread the remaining grains evenly over the remaining time. + // At most as many as fit through the neck in one step. + let time_left = (self.timer_end - now).max(dt); + self.allowance = (self.allowance + self.top as f32 * dt / time_left).min(2.0); + + let sand_w = self.next.len(); + let glass = &self.glass; + let sand = &mut self.next; + let mut moved = false; + // Bottom to top, so every grain moves at most once per step. + // Alternate the direction, so piles don't lean to one side. + let right_to_left = self.steps.is_multiple_of(2); + for y in (0..SAND_H - 1).rev() { + let through_neck = y == SAND_NECK - 1; + let free = |sand: &SandGrid, x: usize| glass[x][y + 1] && !sand[x][y + 1]; + // First let the whole row fall straight down, then slide down diagonally. + // So a gap gets filled from above before from the side, and travels up + // the middle. The middle drains first and leaves a crater, like in a real + // hourglass, instead of the sand flowing down along the walls. + for diagonal in [false, true] { + for i in 0..sand_w { + if through_neck && self.allowance < 1.0 { + break; + } + let x = if right_to_left { sand_w - 1 - i } else { i }; + if !sand[x][y] { + continue; + } + let to = if diagonal { + // To a random side first + let (first, second) = if self.rng.gen() { + (x.checked_sub(1), Some(x + 1).filter(|&x| x < sand_w)) + } else { + (Some(x + 1).filter(|&x| x < sand_w), x.checked_sub(1)) + }; + [first, second] + .into_iter() + .flatten() + .find(|&to| free(sand, to)) + } else { + Some(x).filter(|&to| free(sand, to)) + }; + if let Some(to) = to { + sand[x][y] = false; + sand[to][y + 1] = true; + moved = true; + if through_neck { + self.top -= 1; + self.allowance -= 1.0; + } + } + } + } + } + + if self.top == 0 && !moved { + self.empty_since = Some(now); + } + } + + /// Time left on the current timer, for showing in the terminal + fn status(&self, t: f32) -> String { + let counter = if self.timers.len() > 1 { + format!("Timer {}/{}: ", self.timer + 1, self.timers.len()) + } else { + String::new() + }; + if self.empty_since.is_some() { + return format!("{}Time's up!", counter); + } + let secs = (self.timer_end - t).max(0.0).ceil() as u32; + format!("{}{}:{:02} left", counter, secs / 60, secs % 60) + } + + /// Each LED is as bright as the share of its cells that hold sand. + /// Blends between simulation steps, so falling grains glide at any frame rate. + fn frame(&mut self, t: f32) -> GreyGrid { + let pos = t * SAND_STEPS_PER_SEC; + while self.steps <= pos as u64 + 1 { + self.step(); + } + let blend = (pos - (self.steps - 2) as f32).clamp(0.0, 1.0); + + // Blink three times per second when the time is up + let sand_brightness = match self.empty_since { + Some(since) if ((t - since).max(0.0) * 6.0) as u32 % 2 == 1 => 0.15, + _ => 1.0, + }; + + let cells = (SAND_SUB * SAND_SUB) as f32; + let mut grid = vec![[0; HEIGHT]; self.edge.len()]; + for x in 0..grid.len() { + for y in 0..HEIGHT { + let count = |sand: &SandGrid| { + (0..SAND_SUB * SAND_SUB) + .filter(|i| sand[x * SAND_SUB + i % SAND_SUB][y * SAND_SUB + i / SAND_SUB]) + .count() as f32 + }; + let prev = count(&self.prev); + let coverage = (prev + (count(&self.next) - prev) * blend) / cells; + let glass = if self.edge[x][y] { + GLASS_BRIGHTNESS + } else { + 0.0 + }; + // Linear instead of gamma, so the total light stays the same while moving + let brightness = glass + coverage * sand_brightness * (1.0 - glass); + grid[x][y] = (brightness * 255.0) as u8; + } + } + grid + } +} + +/// LED matrices that frames are streamed to +pub struct Matrices { + ports: Vec>, + /// Side by side as one wide screen, instead of all showing the same + extend: bool, +} + +impl Matrices { + /// Open the ports and wake up the LED matrices. + /// With extend, they are side by side from left to right in the order of serialdevs. + pub fn open(serialdevs: &[String], extend: bool) -> Self { + let ports = serialdevs + .iter() + .map(|serialdev| { + // Long timeout, for waiting until the LED matrix is done fading in + let mut port = serialport::new(serialdev, 115_200) + .timeout(Duration::from_secs(10)) + .open() + .expect("Failed to open port"); + wake_and_wait(&mut port); + port + }) + .collect(); + if extend && serialdevs.len() > 1 { + println!("LED matrices from left to right: {}", serialdevs.join(", ")); + println!("If that's the wrong order, list them with --serial-dev in the right order."); + } + Self { ports, extend } + } + + /// Width of the frames to send, in LEDs + pub fn width(&self) -> usize { + if self.extend { + WIDTH * self.ports.len() + } else { + WIDTH + } + } + + /// Send a greyscale frame, as wide as width(). Each LED matrix gets its part + /// of it with --extend, otherwise all of it. + pub fn send(&mut self, grid: &GreyGrid) { + assert_eq!(grid.len(), self.width(), "Frame has the wrong width"); + fn send_cols(port: &mut Box, cols: &[[u8; HEIGHT]]) { + for (x, col) in cols.iter().enumerate() { + send_col(port, x as u8, col); + } + commit_cols(port); + } + let extend = self.extend; + if let [port] = &mut self.ports[..] { + send_cols(port, grid); + return; + } + // All at the same time, so more LED matrices don't make the frame rate drop + thread::scope(|s| { + for (i, port) in self.ports.iter_mut().enumerate() { + let cols = if extend { + &grid[i * WIDTH..(i + 1) * WIDTH] + } else { + &grid[..] + }; + s.spawn(move || send_cols(port, cols)); + } + }); + } + + /// Turn all LEDs off, instead of leaving them on the last frame + pub fn clear(&mut self) { + self.send(&vec![[0; HEIGHT]; self.width()]); + } +} + +/// Prints the achieved frame rate once per second +struct FpsReporter { + /// When the first frame of the current second was sent + start: Option, + /// Frames sent since then + frames: u64, + /// Shown after the frame rate + status: String, +} + +impl FpsReporter { + fn new() -> Self { + Self { + start: None, + frames: 0, + status: String::new(), + } + } + + fn frame_sent(&mut self) { + // Start at the first frame, so startup time, like opening a camera, doesn't count + let Some(start) = self.start else { + self.start = Some(std::time::Instant::now()); + return; + }; + self.frames += 1; + if start.elapsed() >= Duration::from_secs(1) { + let rate = self.frames as f64 / start.elapsed().as_secs_f64(); + print!("\r{:.1} FPS {} ", rate, self.status); + let _ = std::io::Write::flush(&mut std::io::stdout()); + self.start = Some(std::time::Instant::now()); + self.frames = 0; + } + } +} + +/// Frame rate of the first video stream, using ffprobe +fn video_frame_rate(path: &str) -> Option { + let output = std::process::Command::new("ffprobe") + .args(["-v", "error", "-select_streams", "v:0"]) + .args(["-show_entries", "stream=avg_frame_rate"]) + .args(["-of", "default=noprint_wrappers=1:nokey=1", path]) + .output() + .ok()?; + // For example "30000/1001" + let rate = String::from_utf8(output.stdout).ok()?; + let (num, den) = rate.trim().split_once('/')?; + let rate = num.parse::().ok()? / den.parse::().ok()?; + (rate.is_finite() && rate > 0.0).then_some(rate) +} + +/// Whether ffmpeg can be run. Prints a message if not +fn ffmpeg_available() -> bool { + let available = std::process::Command::new("ffmpeg") + .arg("-version") + .output() + .is_ok(); + if !available { + println!("ffmpeg not found. Please install it and make sure it's in PATH"); + } + available +} + +/// Play a video in greyscale at its own frame rate, or resampled to fps +fn video_cmd(serialdevs: &[String], extend: bool, path: &str, fps: Option) { + if !ffmpeg_available() { + return; + } + let frame_rate = match fps { + Some(fps) => fps as f64, + None => video_frame_rate(path).unwrap_or_else(|| { + println!("Couldn't get the video's frame rate with ffprobe, using 30 FPS"); + 30.0 + }), + }; + ffmpeg_stream(serialdevs, extend, &["-i", path], fps, Some(frame_rate)); +} + +/// Name of the first DirectShow video device, like "Laptop Webcam Module (2nd Gen)" +#[cfg(target_os = "windows")] +fn first_dshow_camera() -> Option { + let output = std::process::Command::new("ffmpeg") + .args([ + "-hide_banner", + "-list_devices", + "true", + "-f", + "dshow", + "-i", + "dummy", + ]) + .output() + .ok()?; + // Devices are listed in stderr, like: [in#0 @ 0000020c351e1b40] "Laptop Webcam Module (2nd Gen)" (video) + String::from_utf8_lossy(&output.stderr) + .lines() + .filter(|line| line.ends_with("(video)")) + .find_map(|line| line.split('"').nth(1).map(String::from)) +} + +/// Show a live view from the webcam in greyscale. +/// Uses the first camera by default, or the device name or path. +fn camera_cmd(serialdevs: &[String], extend: bool, device: Option<&str>, fps: Option) { + if !ffmpeg_available() { + return; + } + + #[cfg(target_os = "windows")] + let input = { + let Some(name) = device.map(String::from).or_else(first_dshow_camera) else { + println!("No camera found"); + return; + }; + [ + "-f".to_string(), + "dshow".into(), + "-i".into(), + format!("video={name}"), + ] + }; + #[cfg(target_os = "linux")] + let input = [ + "-f".to_string(), + "v4l2".into(), + "-i".into(), + device.unwrap_or("/dev/video0").into(), + ]; + #[cfg(target_os = "macos")] + let input = [ + "-f".to_string(), + "avfoundation".into(), + "-i".into(), + device.unwrap_or("0").into(), + ]; + + let input: Vec<&str> = input.iter().map(String::as_str).collect(); + // Frames come in live, no need to pace them + ffmpeg_stream(serialdevs, extend, &input, fps, None); +} + +/// Stream greyscale frames from ffmpeg to the LED matrices until the input ends. +/// ffmpeg decodes, scales and crops the input, which is given as ffmpeg arguments. +/// If frame_rate is set, frames are sent at that rate, otherwise as soon as they are decoded. +fn ffmpeg_stream( + serialdevs: &[String], + extend: bool, + input: &[&str], + fps: Option, + frame_rate: Option, +) { + // Before starting ffmpeg, so a camera doesn't have to buffer frames while the matrix wakes up + let mut matrices = Matrices::open(serialdevs, extend); + let width = matrices.width(); + + // Scale to the height of the matrix and crop the middle, like the Python version. + // Videos narrower than the matrix get padded. + let mut filter = format!( + "scale=-2:{HEIGHT}:flags=area,crop=w=min({width}\\,iw):h={HEIGHT},pad={width}:{HEIGHT}:(ow-iw)/2:0,format=gray" + ); + if let Some(fps) = fps { + filter = format!("fps={fps},{filter}"); + } + let mut ffmpeg = std::process::Command::new("ffmpeg") + .args(["-loglevel", "error", "-nostdin"]) + .args(input) + .args(["-vf", &filter, "-f", "rawvideo", "-"]) + .stdout(std::process::Stdio::piped()) + .spawn() + .expect("Failed to run ffmpeg"); + let mut video = ffmpeg.stdout.take().unwrap(); + + let mut reporter = FpsReporter::new(); + // One byte per pixel, row by row + let mut pixels = vec![0; width * HEIGHT]; + let mut start = None; + let mut frames: u64 = 0; + while std::io::Read::read_exact(&mut video, &mut pixels).is_ok() { + if let Some(frame_rate) = frame_rate { + // ffmpeg decodes faster than real time, so wait until the frame is due. + // Start the clock at the first frame, so ffmpeg's startup time doesn't count. + let start = *start.get_or_insert_with(std::time::Instant::now); + let due = start + Duration::from_secs_f64(frames as f64 / frame_rate); + if let Some(wait) = due.checked_duration_since(std::time::Instant::now()) { + thread::sleep(wait); + } + frames += 1; + } + + let mut grid = vec![[0; HEIGHT]; width]; + for (x, col) in grid.iter_mut().enumerate() { + for (y, val) in col.iter_mut().enumerate() { + // Video brightness is gamma encoded, LED brightness is linear + *val = gamma(pixels[x + y * width] as f32 / 255.0); + } + } + matrices.send(&grid); + reporter.frame_sent(); + } + let _ = ffmpeg.wait(); + println!(); +} + +/// Run a greyscale demo forever, as fast as possible or limited to fps. +/// The hourglass runs at its simulation rate by default, it doesn't get smoother beyond that. +fn demo_cmd( + serialdevs: &[String], + extend: bool, + demo: Demo, + text: &str, + minutes: &[f32], + fps: Option, +) { + let mut matrices = Matrices::open(serialdevs, extend); + let width = matrices.width(); + + let mut fire = Fire::new(width); + let scrolling_text = ScrollingText::new(text, width); + let mut hourglass = Hourglass::new(minutes, width); + let fps = match demo { + Demo::Hourglass => fps.or(Some(SAND_STEPS_PER_SEC as u32)), + _ => fps, + }; + + let start = std::time::Instant::now(); + let mut frames: u64 = 0; + let mut reporter = FpsReporter::new(); + loop { + let t = start.elapsed().as_secs_f32(); + let grid = match demo { + Demo::Plasma => plasma_frame(t, width), + Demo::Fire => fire.frame(t), + Demo::Text => scrolling_text.frame(t), + Demo::Hourglass => { + let grid = hourglass.frame(t); + reporter.status = hourglass.status(t); + grid + } + }; + matrices.send(&grid); + frames += 1; + reporter.frame_sent(); + + if let Some(fps) = fps { + let next_frame = start + Duration::from_secs_f64(frames as f64 / fps as f64); + if let Some(wait) = next_frame.checked_duration_since(std::time::Instant::now()) { + thread::sleep(wait); + } + } + } +} + /// Display an equlizer looking animation with random values. fn random_eq_cmd(serialdevs: &Vec) { loop { @@ -1181,3 +2271,42 @@ fn b1_display_pattern(serialdev: &str, pattern: B1Pattern) { B1Pattern::White => b1_display_color(serialdev, false), } } + +#[cfg(test)] +mod tests { + use super::*; + + fn grains(sand: &SandGrid) -> usize { + sand.iter().flatten().filter(|&&g| g).count() + } + + #[test] + fn hourglass_runs_out_on_time() { + // One LED matrix, and two side by side with --extend + for (minutes, width) in [(0.5, WIDTH), (2.0, WIDTH), (1.0, 2 * WIDTH)] { + let mut hourglass = Hourglass::new(&[minutes, 0.25], width); + let total = grains(&hourglass.next); + assert_eq!(hourglass.top, total); + + let mut t = 0.0; + while hourglass.empty_since.is_none() { + hourglass.frame(t); + t += 1.0 / 30.0; + assert!(t < minutes * 60.0 + 10.0, "Sand didn't run out"); + } + let ran_out = hourglass.empty_since.unwrap(); + println!( + "{} min, {} wide ran out after {:.1}s", + minutes, width, ran_out + ); + assert!((ran_out - minutes * 60.0).abs() < 2.0); + assert_eq!(grains(&hourglass.next), total); + + // Flips over and starts the second timer, with all sand on top + hourglass.frame(t + SAND_BLINK_SECS + 0.1); + assert!(hourglass.empty_since.is_none()); + assert_eq!(hourglass.timer, 1); + assert_eq!(hourglass.top, total); + } + } +} diff --git a/inputmodule-control/src/ledmatrix.rs b/inputmodule-control/src/ledmatrix.rs index 656ddee6..0f2a5ddc 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -24,6 +24,28 @@ pub enum Game { GameOfLife = 3, } +#[derive(Copy, Clone, Debug, PartialEq, clap::ValueEnum)] +pub enum BenchmarkMode { + /// Greyscale: 9 StageGreyCol + 1 DrawGreyColBuffer command per frame + Grey, + /// Black and white: 1 Draw command per frame + Bw, + /// Don't send anything, to measure how the device behaves when idle + Idle, +} + +#[derive(Copy, Clone, Debug, PartialEq, clap::ValueEnum)] +pub enum Demo { + /// Flowing greyscale sine waves + Plasma, + /// Flames rising from the bottom + Fire, + /// Text scrolling up smoothly, set with --demo-text + Text, + /// Falling-sand hourglass timer, set the time with --demo-minutes + Hourglass, +} + #[derive(Copy, Clone, Debug, PartialEq, clap::ValueEnum)] pub enum GameOfLifeStartParam { CurrentMatrix = 0x00, @@ -137,6 +159,66 @@ pub struct LedMatrixSubcommand { #[arg(long)] pub debug_mode: Option>, + /// Stream frames for this many seconds and report throughput + #[arg(long)] + pub benchmark: Option, + + /// Which kind of frames to stream for the benchmark + #[arg(long)] + #[clap(value_enum, default_value_t = BenchmarkMode::Grey)] + pub benchmark_mode: BenchmarkMode, + + /// Run a greyscale demo animation + #[arg(long)] + #[clap(value_enum)] + pub demo: Option, + + /// Text for --demo text + #[arg(long, default_value = "FRAMEWORK")] + pub demo_text: String, + + /// Minutes until the sand of --demo hourglass runs out. With several values + /// it flips over after each and cycles through them, like 25 5 for Pomodoro + #[arg(long, num_args = 1.., default_values_t = [1.0])] + pub demo_minutes: Vec, + + /// Play a video file in greyscale. Requires ffmpeg in PATH + #[arg(long)] + pub video: Option, + + /// Show a live view from the webcam in greyscale. Requires ffmpeg in PATH. + /// Optionally the camera's name (Windows), path (Linux) or index (macOS) + #[arg(long)] + pub camera: Option>, + + /// Play a brick breaker game, with the arrow keys or the mouse in the terminal + #[arg(long)] + pub bricks: bool, + + /// Play a cave descent game, with the arrow keys or the mouse in the terminal + #[arg(long)] + pub cave: bool, + + /// Play a one-button flying game, flap with space, up or a click + #[arg(long)] + pub flap: bool, + + /// Play Ledris, a falling block puzzle, with the arrow keys in the terminal + #[arg(long)] + pub ledris: bool, + + /// Show --demo, the games, --video and --camera across all LED matrices, + /// as one wide screen, instead of the same on each. They're side by side from + /// left to right in the order of --serial-dev, or sorted by name without it + #[arg(long)] + pub extend: bool, + + /// Limit --demo, the games, --video or --camera to this many frames per second. + /// Uncapped for --demo and the games, the video's frame rate for --video + /// and the camera's frame rate for --camera by default + #[arg(long)] + pub fps: Option, + /// Crash the firmware (TESTING ONLY!) #[arg(long)] pub panic: bool, diff --git a/inputmodule-control/src/ledris.rs b/inputmodule-control/src/ledris.rs new file mode 100644 index 00000000..624cb318 --- /dev/null +++ b/inputmodule-control/src/ledris.rs @@ -0,0 +1,698 @@ +//! Ledris, a falling block puzzle: blocks of four fall into the well, move and turn +//! them so they fill whole rows, which then disappear. It gets faster every ten rows, +//! and is over when the blocks pile up to the top. +//! +//! The next block is shown above the well. The falling block glides down smoothly +//! between rows, and a dim copy shows where it will land. + +use crossterm::event::KeyCode; +use rand::prelude::*; + +use crate::hostgame::{add_rect, dark, play, to_grid, Burst, HostGame, Input, Light}; +use crate::inputmodule::{GreyGrid, HEIGHT}; + +/// The next block is shown in the rows above the well, separated by a dashed line +const SEPARATOR_ROW: usize = 2; +const WELL_TOP: usize = SEPARATOR_ROW + 1; +const WELL_H: usize = HEIGHT - WELL_TOP; + +const PIECE_BRIGHTNESS: f32 = 1.0; +const BLOCK_BRIGHTNESS: f32 = 0.45; +const GHOST_BRIGHTNESS: f32 = 0.12; +const NEXT_BRIGHTNESS: f32 = 0.35; +const SEPARATOR_BRIGHTNESS: f32 = 0.15; + +/// How fast blocks fall, in rows per second. Faster with every level. +const START_GRAVITY: f32 = 2.5; +const GRAVITY_PER_LEVEL: f32 = 1.25; +const MAX_GRAVITY: f32 = 40.0; +const LINES_PER_LEVEL: u32 = 10; +/// How long a block can still be moved after it lands, and how often moving +/// it starts that time over, so it can't be moved around forever +const LOCK_DELAY: f32 = 0.5; +const MAX_LOCK_RESETS: u32 = 15; + +/// How long full rows flash before they disappear +const CLEAR_SECS: f32 = 0.3; +const OVER_SECS: f32 = 1.0; + +/// Points for clearing 1 to 4 rows at once, times the level plus one +const LINE_POINTS: [u32; 4] = [100, 300, 500, 800]; + +/// The seven blocks: the size of the square they turn in, and their cells in it +const SHAPES: [(i32, [(i32, i32); 4]); 7] = [ + (4, [(0, 1), (1, 1), (2, 1), (3, 1)]), // I + (2, [(0, 0), (1, 0), (0, 1), (1, 1)]), // O + (3, [(1, 0), (0, 1), (1, 1), (2, 1)]), // T + (3, [(1, 0), (2, 0), (0, 1), (1, 1)]), // S + (3, [(0, 0), (1, 0), (1, 1), (2, 1)]), // Z + (3, [(0, 0), (0, 1), (1, 1), (2, 1)]), // J + (3, [(2, 0), (0, 1), (1, 1), (2, 1)]), // L +]; + +/// Where to try to put a turned block if it doesn't fit where it is, +/// like when it's against a wall. Negative y is up. +const KICKS: [(i32, i32); 6] = [(0, 0), (-1, 0), (1, 0), (0, -1), (-2, 0), (2, 0)]; + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Piece { + kind: usize, + /// Quarter turns clockwise + rot: usize, + /// Top left of the square it turns in, in cells of the well + x: i32, + y: i32, +} + +impl Piece { + /// A new block at the top in the middle + fn spawn(kind: usize, width: usize) -> Self { + let (size, cells) = SHAPES[kind]; + let top = cells.iter().map(|&(_, y)| y).min().unwrap(); + Self { + kind, + rot: 0, + x: (width as i32 - size) / 2, + y: -top, + } + } + + /// Column and row of each cell in the well + fn cells(self) -> [(i32, i32); 4] { + let (size, cells) = SHAPES[self.kind]; + cells.map(|(mut x, mut y)| { + for _ in 0..self.rot % 4 { + (x, y) = (size - 1 - y, x); + } + (self.x + x, self.y + y) + }) + } + + fn moved(self, dx: i32, dy: i32) -> Self { + Self { + x: self.x + dx, + y: self.y + dy, + ..self + } + } +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum State { + /// Waiting for the first key press + Ready, + Playing, + /// Full rows flash before they disappear + Clearing { + since: f32, + }, + Over { + since: f32, + }, +} + +#[derive(Clone)] +struct Game { + rng: ThreadRng, + /// Screen width in LEDs, one or more LED matrices side by side + width: usize, + state: State, + /// Cells of blocks that landed, indexed [row][column], row 0 at the top of the well + well: Vec>, + piece: Piece, + next: usize, + /// The next blocks, each of the seven once in random order, so none is missing for long + bag: Vec, + /// How far the block has fallen towards the next row, to draw it in between + fall: f32, + /// How long the block has been lying on something + lock_time: f32, + lock_resets: u32, + /// Lowest row the block reached, getting lower allows moving it longer again + lowest: i32, + /// Full rows that are flashing + clearing: Vec, + score: u32, + lines: u32, + best: u32, + burst: Option, +} + +impl Game { + fn new(width: usize) -> Self { + let mut game = Self { + rng: thread_rng(), + width, + state: State::Ready, + well: Vec::new(), + piece: Piece::spawn(0, width), + next: 0, + bag: Vec::new(), + fall: 0.0, + lock_time: 0.0, + lock_resets: 0, + lowest: 0, + clearing: Vec::new(), + score: 0, + lines: 0, + best: 0, + burst: None, + }; + game.restart(); + game + } + + fn restart(&mut self) { + self.state = State::Ready; + self.well = vec![vec![false; self.width]; WELL_H]; + self.bag.clear(); + self.clearing.clear(); + self.score = 0; + self.lines = 0; + self.next = self.take_from_bag(); + self.spawn(0.0); + self.state = State::Ready; + } + + fn take_from_bag(&mut self) -> usize { + if self.bag.is_empty() { + self.bag = (0..SHAPES.len()).collect(); + self.bag.shuffle(&mut self.rng); + } + self.bag.pop().unwrap() + } + + fn level(&self) -> u32 { + self.lines / LINES_PER_LEVEL + } + + /// Rows per second + fn gravity(&self) -> f32 { + (START_GRAVITY * GRAVITY_PER_LEVEL.powi(self.level() as i32)).min(MAX_GRAVITY) + } + + /// Inside the well and not on any block. Above the top is free. + fn fits(&self, piece: Piece) -> bool { + piece.cells().iter().all(|&(x, y)| { + x >= 0 + && (x as usize) < self.width + && y < WELL_H as i32 + && (y < 0 || !self.well[y as usize][x as usize]) + }) + } + + fn landing(&self) -> Piece { + let mut piece = self.piece; + while self.fits(piece.moved(0, 1)) { + piece = piece.moved(0, 1); + } + piece + } + + fn spawn(&mut self, now: f32) { + self.piece = Piece::spawn(self.next, self.width); + self.next = self.take_from_bag(); + self.fall = 0.0; + self.lock_time = 0.0; + self.lock_resets = 0; + self.lowest = self.piece.y; + self.state = State::Playing; + if !self.fits(self.piece) { + self.game_over(now); + } + } + + fn game_over(&mut self, now: f32) { + self.state = State::Over { since: now }; + self.best = self.best.max(self.score); + let cells = self.piece.cells(); + let x = cells.iter().map(|&(x, _)| x as f32 + 0.5).sum::() / 4.0; + let y = cells.iter().map(|&(_, y)| y as f32 + 0.5).sum::() / 4.0; + self.burst = Some(Burst::new(&mut self.rng, x, WELL_TOP as f32 + y.max(0.5))); + } + + /// The player moved or turned the block. If it's lying on something, + /// that gives a bit more time before it locks. + fn moved(&mut self) { + if !self.fits(self.piece.moved(0, 1)) && self.lock_resets < MAX_LOCK_RESETS { + self.lock_time = 0.0; + self.lock_resets += 1; + } + } + + fn shift(&mut self, dx: i32) { + let moved = self.piece.moved(dx, 0); + if self.fits(moved) { + self.piece = moved; + self.moved(); + } + } + + fn rotate(&mut self, quarter_turns: usize) { + let turned = Piece { + rot: (self.piece.rot + quarter_turns) % 4, + ..self.piece + }; + let kicked = KICKS + .iter() + .map(|&(dx, dy)| turned.moved(dx, dy)) + .find(|&p| self.fits(p)); + if let Some(piece) = kicked { + self.piece = piece; + self.moved(); + } + } + + /// Down one row, if there's room + fn step_down(&mut self) -> bool { + let down = self.piece.moved(0, 1); + if !self.fits(down) { + return false; + } + self.piece = down; + if down.y > self.lowest { + self.lowest = down.y; + self.lock_time = 0.0; + self.lock_resets = 0; + } + true + } + + fn soft_drop(&mut self) { + if self.step_down() { + self.fall = 0.0; + self.score += 1; + } + } + + fn hard_drop(&mut self, now: f32) { + while self.step_down() { + self.score += 2; + } + self.lock(now); + } + + /// The block becomes part of the well + fn lock(&mut self, now: f32) { + let mut above_top = false; + for (x, y) in self.piece.cells() { + if y < 0 { + above_top = true; + } else { + self.well[y as usize][x as usize] = true; + } + } + if above_top { + self.game_over(now); + return; + } + + self.clearing = (0..WELL_H) + .filter(|&y| self.well[y].iter().all(|&c| c)) + .collect(); + if self.clearing.is_empty() { + self.spawn(now); + } else { + self.score += LINE_POINTS[self.clearing.len() - 1] * (self.level() + 1); + self.lines += self.clearing.len() as u32; + self.state = State::Clearing { since: now }; + } + } + + /// Take out the full rows, the ones above drop down + fn remove_full_rows(&mut self) { + for &y in &self.clearing { + self.well.remove(y); + self.well.insert(0, vec![false; self.width]); + } + self.clearing.clear(); + } + + fn fall(&mut self, now: f32, dt: f32) { + if self.fits(self.piece.moved(0, 1)) { + self.fall += self.gravity() * dt; + while self.fall >= 1.0 && self.step_down() { + self.fall -= 1.0; + } + if !self.fits(self.piece.moved(0, 1)) { + self.fall = 0.0; + } + } else { + self.fall = 0.0; + self.lock_time += dt; + if self.lock_time >= LOCK_DELAY { + self.lock(now); + } + } + } +} + +/// Light up a cell of the well, at a row that can be in between rows. +/// Nothing above the well, that's where the next block is shown. +fn add_cell(light: &mut Light, x: i32, y: f32, brightness: f32) { + let top = WELL_TOP as f32 + y; + let clipped = top.max(WELL_TOP as f32); + if top + 1.0 > clipped { + add_rect( + light, + (x as f32, clipped), + (x as f32 + 1.0, top + 1.0), + brightness, + ); + } +} + +impl HostGame for Game { + fn player_x(&self) -> f32 { + self.piece.x as f32 + } + + fn update(&mut self, input: &mut Input, now: f32, dt: f32) { + match self.state { + State::Ready => { + if !input.presses.is_empty() { + self.state = State::Playing; + } + return; + } + State::Over { since } => { + let again = input + .presses + .iter() + .any(|k| matches!(k, KeyCode::Char(' ') | KeyCode::Enter)); + if again && now - since >= OVER_SECS { + self.restart(); + self.state = State::Playing; + } + return; + } + State::Clearing { since } => { + if now - since >= CLEAR_SECS { + self.remove_full_rows(); + self.spawn(now); + } + return; + } + State::Playing => {} + } + + for &key in &input.presses { + match key { + KeyCode::Left | KeyCode::Char('a') | KeyCode::Char('h') => self.shift(-1), + KeyCode::Right | KeyCode::Char('d') | KeyCode::Char('l') => self.shift(1), + KeyCode::Up | KeyCode::Char('x') | KeyCode::Char('w') | KeyCode::Char('k') => { + self.rotate(1) + } + KeyCode::Char('z') => self.rotate(3), + KeyCode::Down | KeyCode::Char('s') | KeyCode::Char('j') => self.soft_drop(), + KeyCode::Char(' ') | KeyCode::Enter => self.hard_drop(now), + _ => {} + } + if self.state != State::Playing { + return; + } + } + self.fall(now, dt); + } + + fn render(&self, now: f32) -> GreyGrid { + let mut light: Light = dark(self.width); + + for x in (0..self.width).step_by(2) { + add_rect( + &mut light, + (x as f32, SEPARATOR_ROW as f32), + (x as f32 + 1.0, SEPARATOR_ROW as f32 + 1.0), + SEPARATOR_BRIGHTNESS, + ); + } + + // The next block, in the middle above the well + let next = Piece { + kind: self.next, + rot: 0, + x: 0, + y: 0, + } + .cells(); + let min_x = next.iter().map(|&(x, _)| x).min().unwrap(); + let max_x = next.iter().map(|&(x, _)| x).max().unwrap(); + let min_y = next.iter().map(|&(_, y)| y).min().unwrap(); + let offset_x = (self.width as i32 - (max_x - min_x + 1)) / 2 - min_x; + for (x, y) in next { + let (x, y) = ((x + offset_x) as f32, (y - min_y) as f32); + add_rect(&mut light, (x, y), (x + 1.0, y + 1.0), NEXT_BRIGHTNESS); + } + + // Full rows light up and fade out before they disappear + let flash = match self.state { + State::Clearing { since } => 1.0 - ((now - since) / CLEAR_SECS).clamp(0.0, 1.0), + _ => 0.0, + }; + for (y, row) in self.well.iter().enumerate() { + let brightness = if self.clearing.contains(&y) { + flash + } else { + BLOCK_BRIGHTNESS + }; + for (x, &filled) in row.iter().enumerate() { + if filled { + add_cell(&mut light, x as i32, y as f32, brightness); + } + } + } + + match self.state { + State::Ready | State::Playing => { + let landing = self.landing(); + if landing != self.piece { + for (x, y) in landing.cells() { + add_cell(&mut light, x, y as f32, GHOST_BRIGHTNESS); + } + } + for (x, y) in self.piece.cells() { + add_cell(&mut light, x, y as f32 + self.fall, PIECE_BRIGHTNESS); + } + } + State::Over { since } => { + if let Some(burst) = &self.burst { + burst.draw(&mut light, now - since, OVER_SECS); + } + } + State::Clearing { .. } => {} + } + + let dim = match self.state { + State::Over { since } if now - since >= OVER_SECS => 0.4, + _ => 1.0, + }; + to_grid(&light, dim) + } + + fn status(&self, fps: f64) -> String { + let state = match self.state { + State::Ready => "Press any key to start", + State::Over { .. } => "Game over! Space to play again, Q to quit", + _ => "", + }; + format!( + "Score {} Lines {} Level {} Best {} {:.0} FPS {}", + self.score, + self.lines, + self.level(), + self.best, + fps, + state + ) + } +} + +/// Play until the player quits, as fast as possible or limited to fps +pub fn ledris_cmd(serialdevs: &[String], extend: bool, fps: Option) { + play( + serialdevs, + extend, + fps, + "Left and right move, up or X turns, Z turns the other way,\n\ + down drops faster and space drops all the way.", + Game::new, + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::inputmodule::WIDTH; + + fn sorted(mut cells: [(i32, i32); 4]) -> [(i32, i32); 4] { + cells.sort(); + cells + } + + #[test] + fn four_turns_go_all_the_way_around() { + for kind in 0..SHAPES.len() { + let piece = Piece::spawn(kind, WIDTH); + let mut turned = piece; + for _ in 0..4 { + turned.rot += 1; + // Turning keeps it in its square + let size = SHAPES[kind].0; + assert!(turned.cells().iter().all(|&(x, y)| { + (piece.x..piece.x + size).contains(&x) && (piece.y..piece.y + size).contains(&y) + })); + } + assert_eq!(sorted(turned.cells()), sorted(piece.cells())); + } + } + + #[test] + fn bag_has_each_block_once() { + let mut game = Game::new(WIDTH); + game.bag.clear(); + let mut kinds: Vec = (0..14).map(|_| game.take_from_bag()).collect(); + kinds[..7].sort(); + kinds[7..].sort(); + assert_eq!(kinds[..7], [0, 1, 2, 3, 4, 5, 6]); + assert_eq!(kinds[7..], [0, 1, 2, 3, 4, 5, 6]); + } + + #[test] + fn turning_against_the_wall_kicks_away_from_it() { + let mut game = Game::new(WIDTH); + game.state = State::Playing; + // The long block, standing up against the left wall + game.piece = Piece { + kind: 0, + rot: 1, + x: -2, + y: 5, + }; + assert!(game.fits(game.piece)); + game.rotate(1); + assert_eq!(game.piece.rot, 2); + assert!(game.fits(game.piece)); + } + + #[test] + fn full_rows_disappear_and_the_rest_drops() { + let mut game = Game::new(WIDTH); + game.state = State::Playing; + let bottom = WELL_H - 1; + // Bottom row full except where the long block goes, something on top + for x in 0..WIDTH - 4 { + game.well[bottom][x] = true; + } + game.well[bottom - 1][0] = true; + game.piece = Piece::spawn(0, WIDTH); + game.piece.x = WIDTH as i32 - 4; + game.hard_drop(1.0); + assert_eq!(game.state, State::Clearing { since: 1.0 }); + assert_eq!(game.clearing, [bottom]); + assert_eq!(game.lines, 1); + + game.update(&mut Input::default(), 1.1 + CLEAR_SECS, CLEAR_SECS); + assert_eq!(game.state, State::Playing); + assert!(game.well[bottom][0]); + assert_eq!(game.well.iter().flatten().filter(|&&c| c).count(), 1); + } + + #[test] + fn blocks_lock_after_landing() { + let mut game = Game::new(WIDTH); + game.state = State::Playing; + let mut now = 0.0; + let dt = 1.0 / 60.0; + let mut input = Input::default(); + while game.well.iter().flatten().all(|&c| !c) { + now += dt; + game.update(&mut input, now, dt); + assert!(now < WELL_H as f32 / START_GRAVITY + LOCK_DELAY + 1.0); + } + assert!(game.well[WELL_H - 1].iter().any(|&c| c)); + } + + /// Height of each column, holes, and how uneven it is, after the block lands at piece + fn placement_cost(game: &Game, piece: Piece) -> f32 { + let mut well = game.well.clone(); + for (x, y) in piece.cells() { + well[y as usize][x as usize] = true; + } + let full = well.iter().filter(|row| row.iter().all(|&c| c)).count(); + well.retain(|row| !row.iter().all(|&c| c)); + while well.len() < WELL_H { + well.insert(0, vec![false; game.width]); + } + let heights: Vec = (0..game.width) + .map(|x| (0..WELL_H).find(|&y| well[y][x]).map_or(0, |y| WELL_H - y)) + .collect(); + let holes = (0..game.width) + .map(|x| { + (WELL_H - heights[x]..WELL_H) + .filter(|&y| !well[y][x]) + .count() + }) + .sum::(); + let bumps: usize = heights.windows(2).map(|w| w[0].abs_diff(w[1])).sum(); + let total: usize = heights.iter().sum(); + 0.51 * total as f32 + 0.36 * holes as f32 + 0.18 * bumps as f32 - 0.76 * full as f32 + } + + /// A player who tries every place for each block clears plenty of rows, + /// so full rows are found, scored and removed right, also with --extend + #[test] + fn autoplay_clears_rows() { + for (width, min_lines) in [(WIDTH, 300), (2 * WIDTH, 120)] { + let mut game = Game::new(width); + game.state = State::Playing; + let mut now = 0.0; + for _ in 0..1500 { + let start = Piece::spawn(game.piece.kind, width); + let best = (0..4) + .flat_map(|rot| (-3..width as i32).map(move |x| Piece { rot, x, ..start })) + .filter(|&p| game.fits(p)) + .map(|p| { + let mut game = game.clone(); + game.piece = p; + let landing = game.landing(); + (placement_cost(&game, landing), p) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .unwrap() + .1; + game.piece = best; + game.hard_drop(now); + while game.state != State::Playing { + assert!( + !matches!(game.state, State::Over { .. }), + "Game over after {} rows +{}", + game.lines, + game.well + .iter() + .map(|row| row + .iter() + .map(|&c| if c { '#' } else { '.' }) + .collect::()) + .collect::>() + .join( + " +" + ) + ); + now += 0.1; + game.update(&mut Input::default(), now, 0.1); + } + game.render(now); + } + assert!( + game.lines >= min_lines, + "Only {} rows at width {}", + game.lines, + width + ); + assert!(game.level() > 0); + println!("Cleared {} rows, score {}", game.lines, game.score); + } + } +} diff --git a/inputmodule-control/src/main.rs b/inputmodule-control/src/main.rs index 8348ad74..96fe9aac 100644 --- a/inputmodule-control/src/main.rs +++ b/inputmodule-control/src/main.rs @@ -1,10 +1,16 @@ #![allow(clippy::needless_range_loop)] #![allow(clippy::single_match)] mod b1display; +mod bricks; mod c1minimal; +mod cave; +mod flap; mod font; +mod hostgame; mod inputmodule; mod ledmatrix; +mod ledris; +mod usbport; use clap::{Parser, Subcommand}; use inputmodule::find_serialdevs; @@ -14,6 +20,8 @@ use crate::c1minimal::C1MinimalSubcommand; use crate::inputmodule::{serial_commands, B1_LCD_PID, LED_MATRIX_PID}; use crate::ledmatrix::LedMatrixSubcommand; +// Parsed once at startup, the size doesn't matter +#[allow(clippy::large_enum_variant)] #[derive(Subcommand, Debug)] enum Commands { LedMatrix(LedMatrixSubcommand), @@ -46,9 +54,10 @@ pub struct ClapCli { #[arg(short, long)] verbose: bool, - /// Serial device, like /dev/ttyACM0 or COM0 + /// Serial device, like /dev/ttyACM0 or COM0. + /// Repeat it for several, like for --extend, which puts them left to right in this order #[arg(long)] - pub serial_dev: Option, + pub serial_dev: Vec, /// Retry connecting to the device until it works #[arg(long)] diff --git a/inputmodule-control/src/usbport.rs b/inputmodule-control/src/usbport.rs new file mode 100644 index 00000000..69f95589 --- /dev/null +++ b/inputmodule-control/src/usbport.rs @@ -0,0 +1,183 @@ +//! Where a serial device is plugged in, to put several LED matrices in a stable order. +//! +//! COM port numbers and /dev/ttyACM* names depend on enumeration order, and not +//! every module reports a serial number. But the USB port of each input deck slot +//! is fixed, and on the Framework 16 a lower hub port is further left. + +/// USB location of a serial device, ending in root port and hub port, +/// like [.., 4, 2] for root port 4, hub port 2. +/// None if it can't be found out on this platform. +pub fn location(port_name: &str) -> Option> { + imp::location(port_name) +} + +/// Framework 16 input deck slots from left to right, as (root port, hub port). +/// The left two are behind one hub, the right two behind another. +const FW16_SLOTS: [(u32, u32); 4] = [(4, 2), (4, 3), (3, 2), (3, 3)]; + +/// Position from the left of a module in the Framework 16 input deck +pub fn fw16_position(location: &[u32]) -> Option { + let [.., root, port] = location else { + return None; + }; + FW16_SLOTS.iter().position(|&slot| slot == (*root, *port)) +} + +/// Position from the left of a serial device in the Framework 16 input deck +pub fn fw16_position_of(port_name: &str) -> Option { + fw16_position(&location(port_name)?) +} + +/// Numbers in a Linux USB device name, like [1, 4, 2] for "1-4.2" +#[allow(dead_code)] +fn numbers(s: &str) -> Vec { + s.split(|c: char| !c.is_ascii_digit()) + .filter(|n| !n.is_empty()) + .filter_map(|n| n.parse().ok()) + .collect() +} + +/// Hex numbers in a Windows location path, like [0, 0x803, 0, 0, 4, 2] for +/// "PCIROOT(0)#PCI(0803)#PCI(0000)#USBROOT(0)#USB(4)#USB(2)" +#[allow(dead_code)] +fn path_numbers(path: &str) -> Option> { + path.split('#') + // Interface of a composite device, not part of the port path + .filter(|seg| !seg.starts_with("USBMI(")) + .map(|seg| { + let n = seg.split_once('(')?.1.strip_suffix(')')?; + u32::from_str_radix(n, 16).ok() + }) + .collect() +} + +#[cfg(target_os = "linux")] +mod imp { + /// /sys/class/tty/ttyACM0/device links to the USB interface, like + /// .../usb1/1-4/1-4.2/1-4.2:1.0, whose parent is the USB device at 1-4.2. + pub fn location(port_name: &str) -> Option> { + let name = port_name.rsplit('/').next()?; + let dev = std::fs::canonicalize(format!("/sys/class/tty/{}/device", name)).ok()?; + let usb_dev = dev.parent()?.file_name()?.to_str()?; + Some(super::numbers(usb_dev)) + } +} + +#[cfg(windows)] +mod imp { + use std::ptr; + use windows_sys::Win32::Devices::DeviceAndDriverInstallation::{ + SetupDiDestroyDeviceInfoList, SetupDiEnumDeviceInfo, SetupDiGetClassDevsW, + SetupDiGetDeviceRegistryPropertyW, SetupDiOpenDevRegKey, DICS_FLAG_GLOBAL, DIGCF_PRESENT, + DIREG_DEV, GUID_DEVCLASS_PORTS, SPDRP_LOCATION_PATHS, SP_DEVINFO_DATA, + }; + use windows_sys::Win32::System::Registry::{RegCloseKey, RegQueryValueExW, KEY_READ}; + + fn wide(s: &str) -> Vec { + s.encode_utf16().chain(Some(0)).collect() + } + + fn from_wide(buf: &[u16]) -> String { + let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len()); + String::from_utf16_lossy(&buf[..end]) + } + + /// Goes through the present devices of the Ports class to find the one with + /// this COM name and reads its location, like "Port_#0002.Hub_#0008". + pub fn location(port_name: &str) -> Option> { + unsafe { + let set = SetupDiGetClassDevsW(&GUID_DEVCLASS_PORTS, ptr::null(), 0, DIGCF_PRESENT); + if set == -1 { + return None; + } + let mut result = None; + let mut index = 0; + loop { + let mut info: SP_DEVINFO_DATA = std::mem::zeroed(); + info.cbSize = std::mem::size_of::() as u32; + if SetupDiEnumDeviceInfo(set, index, &mut info) == 0 { + break; + } + index += 1; + + let key = SetupDiOpenDevRegKey(set, &info, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ); + if key == -1 { + continue; + } + let mut name = [0u16; 64]; + let mut size = std::mem::size_of_val(&name) as u32; + let found = RegQueryValueExW( + key, + wide("PortName").as_ptr(), + ptr::null(), + ptr::null_mut(), + name.as_mut_ptr() as *mut u8, + &mut size, + ) == 0 + && from_wide(&name).eq_ignore_ascii_case(port_name); + RegCloseKey(key); + if !found { + continue; + } + + // Like PCIROOT(0)#PCI(0803)#PCI(0000)#USBROOT(0)#USB(4)#USB(2), which is + // fixed by the hardware, unlike the hub number Windows assigns + let mut loc = [0u16; 512]; + if SetupDiGetDeviceRegistryPropertyW( + set, + &info, + SPDRP_LOCATION_PATHS, + ptr::null_mut(), + loc.as_mut_ptr() as *mut u8, + std::mem::size_of_val(&loc) as u32, + ptr::null_mut(), + ) != 0 + { + // First of the list of paths is the PCI one + result = super::path_numbers(&from_wide(&loc)); + } + break; + } + SetupDiDestroyDeviceInfoList(set); + result + } + } +} + +#[cfg(not(any(target_os = "linux", windows)))] +mod imp { + pub fn location(_port_name: &str) -> Option> { + None + } +} + +#[cfg(test)] +mod tests { + use super::{fw16_position, numbers, path_numbers}; + + #[test] + fn fw16_slots() { + let win = |p| path_numbers(p).unwrap(); + let left = win("PCIROOT(0)#PCI(0803)#PCI(0000)#USBROOT(0)#USB(4)#USB(2)"); + let right = win("PCIROOT(0)#PCI(0803)#PCI(0000)#USBROOT(0)#USB(3)#USB(3)"); + assert_eq!(fw16_position(&left), Some(0)); + assert_eq!(fw16_position(&right), Some(3)); + assert_eq!(fw16_position(&numbers("1-4.3")), Some(1)); + assert_eq!(fw16_position(&numbers("1-3.2")), Some(2)); + // Keyboard interface, not a slot for an LED matrix in this position + let kbd = win("PCIROOT(0)#PCI(0803)#PCI(0000)#USBROOT(0)#USB(3)#USB(1)#USBMI(0)"); + assert_eq!(fw16_position(&kbd), None); + assert_eq!(fw16_position(&[]), None); + } + + #[test] + fn location_numbers() { + assert_eq!(numbers("1-4.2"), vec![1, 4, 2]); + assert_eq!(numbers(""), Vec::::new()); + assert_eq!( + path_numbers("PCIROOT(0)#PCI(0803)#PCI(0000)#USBROOT(0)#USB(4)#USB(2)"), + Some(vec![0, 0x803, 0, 0, 4, 2]) + ); + assert_eq!(path_numbers("ACPI(_SB_)"), None); + } +} diff --git a/ledmatrix/Cargo.toml b/ledmatrix/Cargo.toml index 7f56d910..f7409fbd 100644 --- a/ledmatrix/Cargo.toml +++ b/ledmatrix/Cargo.toml @@ -1,7 +1,7 @@ [package] edition = "2021" name = "ledmatrix" -version = "0.2.0" +version = "0.2.1" [features] 10k = [] diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index 9337f053..75df4abe 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -4,14 +4,12 @@ #![allow(clippy::needless_range_loop)] use cortex_m::delay::Delay; +use cortex_m::peripheral::NVIC; //use defmt::*; use defmt_rtt as _; use embedded_hal::digital::{InputPin, OutputPin}; -use rp2040_hal::{ - gpio::bank0::Gpio29, - rosc::{Enabled, RingOscillator}, -}; +use rp2040_hal::rosc::{Enabled, RingOscillator}; //#[cfg(debug_assertions)] //use panic_probe as _; use rp2040_panic_usb_boot as _; @@ -36,6 +34,15 @@ const STARTUP_ANIMATION: bool = true; /// Go to sleep after 60s awake const SLEEP_TIMEOUT: u64 = 60_000_000; +/// Resend the full grid every 1s, in case the LED controller lost its state +const DISPLAY_REFRESH_PERIOD: u64 = 1_000_000; + +/// Sleep at most 100ms at a time, so the DIP switch is still checked often enough. +/// The SLEEP# pin wakes the CPU up by itself. +const MAX_WAIT_US: u64 = 100_000; +/// Don't bother sleeping for less than this. Also makes sure the alarm isn't scheduled in the past. +const MIN_WAIT_US: u64 = 20; + /// List maximum current as 500mA in the USB descriptor const MAX_CURRENT: usize = 500; @@ -74,6 +81,7 @@ const MAX_BRIGHTNESS: u8 = 50; // .unwrap(); // // let mut delay = cortex_m::delay::Delay::new(core.SYST, clocks.system_clock.freq().to_Hz()); +// let timer = Timer::new(pac.TIMER, &mut pac.RESETS, &clocks); // // let pins = bsp::Pins::new( // pac.IO_BANK0, @@ -99,9 +107,10 @@ const MAX_BRIGHTNESS: u8 = 50; // .setup(&mut delay) // .expect("failed to setup rgb controller"); // -// set_brightness(state, 255, &mut matrix); -// let grid = display_panic(); -// fill_grid_pixels(state, &mut matrix); +// let mut display = MatrixSync::new(matrix, led_enable, timer); +// state.brightness = 255; +// state.grid = display_panic(); +// display.force_flush(state); // // loop {} //} @@ -125,11 +134,12 @@ use bsp::hal::{ clocks::{init_clocks_and_plls, Clock}, gpio, pac, sio::Sio, + timer::Alarm, usb, watchdog::Watchdog, Timer, }; -use fugit::RateExtU32; +use fugit::{ExtU32, RateExtU32}; // USB Device support use usb_device::descriptor::lang_id::LangID; @@ -146,6 +156,7 @@ use heapless::String; use fl16_inputmodules::control::*; use fl16_inputmodules::games::{pong, snake}; use fl16_inputmodules::matrix::*; +use fl16_inputmodules::matrix_sync::*; use fl16_inputmodules::patterns::*; use fl16_inputmodules::serialnum::{device_release, get_serialnum}; @@ -188,7 +199,15 @@ fn main() -> ! { ); // Create timer before USB bus since USB bus moves clocks.usb_clock - let timer = Timer::new(pac.TIMER, &mut pac.RESETS, &clocks); + let mut timer = Timer::new(pac.TIMER, &mut pac.RESETS, &clocks); + + // Let pending interrupts wake the CPU from WFE, even though none are enabled in the NVIC. + // That way the main loop can sleep until there's USB activity or the alarm fires, + // without needing any interrupt handlers. + // Safety: Only sets SEVONPEND, which doesn't affect anything else + unsafe { core.SCB.scr.modify(|scr| scr | (1 << 4)) }; + let mut alarm = timer.alarm_0().unwrap(); + alarm.enable_interrupt(); // Set up the USB driver let usb_bus = UsbBusAllocator::new(usb::UsbBus::new( @@ -296,11 +315,12 @@ fn main() -> ! { .set_scaling(MAX_BRIGHTNESS) .expect("failed to set scaling"); - matrix.device.set_pwm_freq(state.pwm_freq.into()).unwrap(); - - fill_grid_pixels(&state, &mut matrix); + let mut display = MatrixSync::new(matrix, led_enable, timer); + display.set_pwm_freq(state.pwm_freq); + display.flush_if_dirty(&state); let mut animation_timer = timer.get_counter().ticks(); + let mut refresh_timer = timer.get_counter().ticks(); let mut game_timer = timer.get_counter().ticks(); let mut sleep_timer = timer.get_counter().ticks(); @@ -316,6 +336,11 @@ fn main() -> ! { if sleep.is_high().unwrap() { sleep_present = true; } + // Wake up from WFE when the host goes to sleep or wakes up + if sleep_present { + sleep.set_interrupt_enabled(gpio::Interrupt::EdgeLow, true); + sleep.set_interrupt_enabled(gpio::Interrupt::EdgeHigh, true); + } let mut usb_initialized = false; let mut usb_suspended = false; @@ -325,10 +350,15 @@ fn main() -> ! { let mut last_host_sleep = sleep.is_low().unwrap(); loop { + let loop_start = timer.get_counter().ticks(); + let mut received_data = false; last_sleep_reason = sleep_reason; state.debug_mode = dip1.is_low().unwrap(); if sleep_present { + // Clear before reading the pin, so that a change after reading it wakes up from WFE + sleep.clear_interrupt(gpio::Interrupt::EdgeLow); + sleep.clear_interrupt(gpio::Interrupt::EdgeHigh); // Go to sleep if the host is sleeping let host_sleeping = sleep.is_low().unwrap(); let host_sleep_changed = host_sleeping != last_host_sleep; @@ -382,27 +412,25 @@ fn main() -> ! { sleep_timer = timer.get_counter().ticks(); } - handle_sleep( - sleep_reason, - &mut state, - &mut matrix, - &mut delay, - &mut led_enable, - ); + handle_sleep(sleep_reason, &mut state, &mut display, &mut delay); // Handle period display updates. Don't do it too often + // Without an animation, the display only changes through commands and games, + // which update it themselves. So there's no need to wake up for it. + let animating = state.upcoming_frames.is_some() || state.animate; let render_again = timer.get_counter().ticks() > animation_timer + state.animation_period; - if matches!(state.sleeping, SleepState::Awake) && render_again { + if matches!(state.sleeping, SleepState::Awake) && animating && render_again { if let Some(ref mut upcoming) = state.upcoming_frames { if let Some(next_frame) = upcoming.next() { state.grid = next_frame; } else { // Animation is over. Clear screen state.grid = Grid::default(); + state.upcoming_frames = None; } } - fill_grid_pixels(&state, &mut matrix); + display.flush_if_dirty(&state); if state.animate { for x in 0..WIDTH { state.grid.0[x].rotate_right(1); @@ -411,6 +439,13 @@ fn main() -> ! { animation_timer = timer.get_counter().ticks(); } + // Periodically resend the full grid, even if it hasn't changed + let refresh_again = timer.get_counter().ticks() > refresh_timer + DISPLAY_REFRESH_PERIOD; + if matches!(state.sleeping, SleepState::Awake) && refresh_again { + display.force_flush(&state); + refresh_timer = timer.get_counter().ticks(); + } + // Check for new data if usb_dev.poll(&mut [&mut serial]) { match usb_dev.state() { @@ -440,14 +475,18 @@ fn main() -> ! { // Do nothing } Ok(count) => { + received_data = true; + display.stats.bytes_received = + display.stats.bytes_received.wrapping_add(count as u32); let random = get_random_byte(&rosc); match (parse_command(count, &buf), &state.sleeping) { // Handle bootloader command without any delay // No need, it'll reset the device anyways (Some(c @ Command::BootloaderReset), _) => { - handle_command(&c, &mut state, &mut matrix, random); + handle_command(&c, &mut state, &mut display, random); } (Some(command), _) => { + display.stats.cmds_parsed = display.stats.cmds_parsed.wrapping_add(1); if let Command::Sleep(go_sleeping) = command { sleep_reason = assign_sleep_reason( last_sleep_reason, @@ -470,13 +509,7 @@ fn main() -> ! { SleepState::Sleeping((grid.clone(), new_brightness)); } } - handle_sleep( - sleep_reason, - &mut state, - &mut matrix, - &mut delay, - &mut led_enable, - ); + handle_sleep(sleep_reason, &mut state, &mut display, &mut delay); // If there's a very early command, cancel the startup animation state.upcoming_frames = None; @@ -486,7 +519,7 @@ fn main() -> ! { sleep_timer = timer.get_counter().ticks(); if let Some(response) = - handle_command(&command, &mut state, &mut matrix, random) + handle_command(&command, &mut state, &mut display, random) { let _ = serial.write(&response); }; @@ -501,9 +534,15 @@ fn main() -> ! { .unwrap(); // let _ = serial.write(text.as_bytes()); - fill_grid_pixels(&state, &mut matrix); + // Only send if the output changed. Most commands don't change it, + // like staging a greyscale column. Recovering from a corrupted + // controller state is handled by the periodic refresh. + display.flush_if_dirty(&state); + } + (None, _) => { + display.stats.cmds_rejected = + display.stats.cmds_rejected.wrapping_add(1); } - (None, _) => {} } } } @@ -562,8 +601,60 @@ fn main() -> ! { } None => {} } + if matches!(state.sleeping, SleepState::Awake) { + display.flush_if_dirty(&state); + } game_timer = timer.get_counter().ticks(); } + + // Sleep until the next deadline instead of busy polling. + // Waking up early because of USB activity is fine, the loop just runs again. + let now = timer.get_counter().ticks(); + let mut deadline = (now + MAX_WAIT_US).min(game_timer + game_step_diff); + if matches!(state.sleeping, SleepState::Awake) { + deadline = deadline.min(refresh_timer + DISPLAY_REFRESH_PERIOD); + if state.upcoming_frames.is_some() || state.animate { + deadline = deadline.min(animation_timer + state.animation_period); + } + } + if !state.debug_mode { + deadline = deadline.min(sleep_timer + SLEEP_TIMEOUT); + } + let wait = deadline.saturating_sub(now); + let mut wait_us = 0; + if wait >= MIN_WAIT_US { + alarm.clear_interrupt(); + alarm.schedule((wait as u32).micros()).unwrap(); + // Interrupts are level triggered, so these become pending again right away, + // if the USB controller or the alarm is still asserting them. + NVIC::unpend(pac::Interrupt::USBCTRL_IRQ); + NVIC::unpend(pac::Interrupt::TIMER_IRQ_0); + NVIC::unpend(pac::Interrupt::IO_IRQ_BANK0); + // Clear the event register, it might still be set from an earlier event + cortex_m::asm::sev(); + cortex_m::asm::wfe(); + // Any interrupt becoming pending after this check sets the event register again, + // so WFE can't miss it + if !NVIC::is_pending(pac::Interrupt::USBCTRL_IRQ) + && !NVIC::is_pending(pac::Interrupt::TIMER_IRQ_0) + && !NVIC::is_pending(pac::Interrupt::IO_IRQ_BANK0) + { + cortex_m::asm::wfe(); + } + wait_us = (timer.get_counter().ticks() - now) as u32; + display.stats.wait_us_total = display.stats.wait_us_total.wrapping_add(wait_us); + } + + let loop_us = (timer.get_counter().ticks() - loop_start) as u32; + // Only the time spent working, sleeping isn't what makes the loop slow + display.stats.loop_us_max = display.stats.loop_us_max.max(loop_us - wait_us); + display.stats.loops = display.stats.loops.wrapping_add(1); + if received_data { + display.stats.busy_us_total = display.stats.busy_us_total.wrapping_add(loop_us); + } else { + display.stats.idle_loops = display.stats.idle_loops.wrapping_add(1); + display.stats.idle_us_total = display.stats.idle_us_total.wrapping_add(loop_us); + } } } @@ -613,9 +704,8 @@ fn assign_sleep_reason( fn handle_sleep( sleep_reason: Option, state: &mut LedmatrixState, - matrix: &mut Foo, + display: &mut MatrixSync, delay: &mut Delay, - led_enable: &mut gpio::Pin, ) { match (state.sleeping.clone(), sleep_reason) { // Awake and staying awake @@ -628,7 +718,8 @@ fn handle_sleep( loop { delay.delay_ms(100); brightness = brightness.saturating_sub(5); - set_brightness(state, brightness, matrix); + state.brightness = brightness; + display.flush_if_dirty(state); if brightness == 0 { break; } @@ -637,10 +728,10 @@ fn handle_sleep( if debug_mode(state) { state.grid = display_sleep_reason(sleep_reason); - fill_grid_pixels(state, matrix); + display.flush_if_dirty(state); } else { // Turn LED controller off to save power - led_enable.set_low().unwrap(); + display.set_enabled(false); } // TODO: Set up SLEEP# pin as interrupt and wfi @@ -651,7 +742,7 @@ fn handle_sleep( // If debug mode is enabled, then make sure the latest sleep reason is displayed if debug_mode(state) { state.grid = display_sleep_reason(sleep_reason); - fill_grid_pixels(state, matrix); + display.flush_if_dirty(state); } } // Sleeping and need to wake up @@ -659,24 +750,24 @@ fn handle_sleep( // Restore back grid before sleeping state.sleeping = SleepState::Awake; state.grid = old_grid; - fill_grid_pixels(state, matrix); - // Power LED controller back on - if !debug_mode(state) { - led_enable.set_high().unwrap(); - } + // Allow powering the LED controller back on. Even in debug mode, because it + // might have been turned off before debug mode was enabled. + display.set_enabled(true); + display.force_flush(state); // Slowly increase brightness if dyn_sleep_mode(state) == SleepMode::Fading { let mut brightness = 0; loop { delay.delay_ms(100); - brightness = if brightness >= old_brightness - 5 { + brightness = if brightness >= old_brightness.saturating_sub(5) { old_brightness } else { brightness + 5 }; - set_brightness(state, brightness, matrix); + state.brightness = brightness; + display.flush_if_dirty(state); if brightness == old_brightness { break; }