From 9fecd98bb0ee57eb5975ea5209ef762446755a0c Mon Sep 17 00:00:00 2001 From: Androo Frowns Date: Fri, 17 Jul 2026 02:45:39 -0400 Subject: [PATCH 01/48] fix(ledmatrix): prevent redundant I2C redraws during commands --- fl16-inputmodules/src/control.rs | 10 ++-- fl16-inputmodules/src/lib.rs | 2 + fl16-inputmodules/src/matrix.rs | 2 +- fl16-inputmodules/src/matrix_sync.rs | 84 ++++++++++++++++++++++++++++ fl16-inputmodules/src/patterns.rs | 58 ------------------- ledmatrix/src/main.rs | 30 +++++----- 6 files changed, 110 insertions(+), 76 deletions(-) create mode 100644 fl16-inputmodules/src/matrix_sync.rs diff --git a/fl16-inputmodules/src/control.rs b/fl16-inputmodules/src/control.rs index 42961486..2073a21d 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; @@ -515,7 +517,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 +530,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 +547,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(), @@ -618,7 +620,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 => { 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.rs b/fl16-inputmodules/src/matrix.rs index 71a625fd..f775b3e4 100644 --- a/fl16-inputmodules/src/matrix.rs +++ b/fl16-inputmodules/src/matrix.rs @@ -8,7 +8,7 @@ pub const WIDTH: usize = 9; pub const HEIGHT: usize = 34; pub const LEDS: usize = WIDTH * HEIGHT; -#[derive(Clone)] +#[derive(Clone, PartialEq)] pub struct Grid(pub [[u8; HEIGHT]; WIDTH]); impl Default for Grid { fn default() -> Self { diff --git a/fl16-inputmodules/src/matrix_sync.rs b/fl16-inputmodules/src/matrix_sync.rs new file mode 100644 index 00000000..307bf284 --- /dev/null +++ b/fl16-inputmodules/src/matrix_sync.rs @@ -0,0 +1,84 @@ +use crate::control::PwmFreqArg; +use crate::led_hal as bsp; +use crate::matrix::{Grid, LedmatrixState, HEIGHT, WIDTH}; +use crate::patterns::BRIGHTNESS_LEVELS; +use is31fl3741::devices::LedMatrix; +use rp2040_hal::{ + gpio::{ + bank0::{Gpio26, Gpio27}, + FunctionI2C, PullUp, + }, + pac::I2C1, +}; + +pub type Foo = LedMatrix< + bsp::hal::I2C< + I2C1, + ( + bsp::hal::gpio::Pin, + bsp::hal::gpio::Pin, + ), + >, +>; + +pub struct MatrixSync { + matrix: Foo, + sent_grid: Grid, + sent_brightness: u8, +} + +impl MatrixSync { + pub fn new(matrix: Foo) -> Self { + Self { + matrix, + sent_grid: Grid::default(), + sent_brightness: 0, + } + } + + /// Fills the grid pixels but only sends the I2C commands if we expect it to update displayed state + pub fn flush_if_dirty(&mut self, state: &LedmatrixState) { + if state.grid != self.sent_grid || state.brightness != self.sent_brightness { + fill_grid_pixels(state, &mut self.matrix); + self.sent_grid = state.grid.clone(); + self.sent_brightness = state.brightness; + } + } + + pub fn set_pwm_freq(&mut self, freq: PwmFreqArg) { + self.matrix.device.set_pwm_freq(freq.into()).unwrap(); + } +} + +/// Just sends two I2C commands for the entire grid +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(); +} + +/// 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 full_brightness(matrix: &mut Foo) { + // Fills every pixel individually + //matrix.fill_brightness(0xFF).unwrap(); + + // Fills full page at once + matrix.device.fill(0xFF).unwrap(); +} 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/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index 9337f053..ed9c3156 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -146,6 +146,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}; @@ -298,7 +299,8 @@ fn main() -> ! { matrix.device.set_pwm_freq(state.pwm_freq.into()).unwrap(); - fill_grid_pixels(&state, &mut matrix); + let mut display = MatrixSync::new(matrix); + display.flush_if_dirty(&state); let mut animation_timer = timer.get_counter().ticks(); let mut game_timer = timer.get_counter().ticks(); @@ -385,7 +387,7 @@ fn main() -> ! { handle_sleep( sleep_reason, &mut state, - &mut matrix, + &mut display, &mut delay, &mut led_enable, ); @@ -402,7 +404,7 @@ fn main() -> ! { } } - 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); @@ -445,7 +447,7 @@ fn main() -> ! { // 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), _) => { if let Command::Sleep(go_sleeping) = command { @@ -473,7 +475,7 @@ fn main() -> ! { handle_sleep( sleep_reason, &mut state, - &mut matrix, + &mut display, &mut delay, &mut led_enable, ); @@ -486,7 +488,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,7 +503,7 @@ fn main() -> ! { .unwrap(); // let _ = serial.write(text.as_bytes()); - fill_grid_pixels(&state, &mut matrix); + display.flush_if_dirty(&state); } (None, _) => {} } @@ -613,7 +615,7 @@ 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, ) { @@ -628,7 +630,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,7 +640,7 @@ 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(); @@ -651,7 +654,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,7 +662,7 @@ fn handle_sleep( // Restore back grid before sleeping state.sleeping = SleepState::Awake; state.grid = old_grid; - fill_grid_pixels(state, matrix); + display.flush_if_dirty(state); // Power LED controller back on if !debug_mode(state) { @@ -676,7 +679,8 @@ fn handle_sleep( } else { brightness + 5 }; - set_brightness(state, brightness, matrix); + state.brightness = brightness; + display.flush_if_dirty(state); if brightness == old_brightness { break; } From bb0745d7de7914a39ad9f3e8e5c598c99930d818 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 01:58:03 +0800 Subject: [PATCH 02/48] ledmatrix: Compare sent PWM values and resend grid periodically Cache the PWM buffer that was actually sent to the LED controller instead of the grid and brightness. That skips redundant writes that don't change the output, like grid changes at brightness 0. Before, the full grid was resent on every animation tick and after every command, so if the controller lost or corrupted its state, it recovered quickly. Restore that by always resending after a command and once per second while awake. Co-Authored-By: Claude Opus 5.5 --- fl16-inputmodules/src/matrix.rs | 2 +- fl16-inputmodules/src/matrix_sync.rs | 41 ++++++++++++++++------------ ledmatrix/src/main.rs | 13 ++++++++- 3 files changed, 36 insertions(+), 20 deletions(-) diff --git a/fl16-inputmodules/src/matrix.rs b/fl16-inputmodules/src/matrix.rs index f775b3e4..71a625fd 100644 --- a/fl16-inputmodules/src/matrix.rs +++ b/fl16-inputmodules/src/matrix.rs @@ -8,7 +8,7 @@ pub const WIDTH: usize = 9; pub const HEIGHT: usize = 34; pub const LEDS: usize = WIDTH * HEIGHT; -#[derive(Clone, PartialEq)] +#[derive(Clone)] pub struct Grid(pub [[u8; HEIGHT]; WIDTH]); impl Default for Grid { fn default() -> Self { diff --git a/fl16-inputmodules/src/matrix_sync.rs b/fl16-inputmodules/src/matrix_sync.rs index 307bf284..b3b43394 100644 --- a/fl16-inputmodules/src/matrix_sync.rs +++ b/fl16-inputmodules/src/matrix_sync.rs @@ -21,39 +21,44 @@ pub type Foo = LedMatrix< >, >; +/// 0xB4 LEDs on the first page, 0xAB on the second page +const PWM_BUF_LEN: usize = 0xB4 + 0xAB; + pub struct MatrixSync { matrix: Foo, - sent_grid: Grid, - sent_brightness: u8, + /// PWM values last sent to the LED controller. None if unknown + sent: Option<[u8; PWM_BUF_LEN]>, } impl MatrixSync { pub fn new(matrix: Foo) -> Self { - Self { - matrix, - sent_grid: Grid::default(), - sent_brightness: 0, - } + Self { matrix, sent: None } } - /// Fills the grid pixels but only sends the I2C commands if we expect it to update displayed state + /// Fills the grid pixels but only sends the I2C commands if the PWM values changed pub fn flush_if_dirty(&mut self, state: &LedmatrixState) { - if state.grid != self.sent_grid || state.brightness != self.sent_brightness { - fill_grid_pixels(state, &mut self.matrix); - self.sent_grid = state.grid.clone(); - self.sent_brightness = state.brightness; + let brightnesses = calc_brightnesses(state, &self.matrix); + if self.sent.as_ref() != Some(&brightnesses) { + self.matrix.device.fill_matrix(&brightnesses).unwrap(); + self.sent = Some(brightnesses); } } + /// 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); + } + pub fn set_pwm_freq(&mut self, freq: PwmFreqArg) { self.matrix.device.set_pwm_freq(freq.into()).unwrap(); } } -/// Just sends two I2C commands for the entire grid -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]; +/// Calculate PWM values for the entire grid, so they can be sent with just two I2C commands +fn calc_brightnesses(state: &LedmatrixState, matrix: &Foo) -> [u8; PWM_BUF_LEN] { + let mut brightnesses = [0x00; PWM_BUF_LEN]; for y in 0..HEIGHT { for x in 0..WIDTH { let (register, page) = (matrix.device.calc_pixel)(x as u8, y as u8); @@ -62,10 +67,10 @@ fn fill_grid_pixels(state: &LedmatrixState, matrix: &mut Foo) { / (BRIGHTNESS_LEVELS as u64)) as u8; } } - matrix.device.fill_matrix(&brightnesses).unwrap(); + brightnesses } -/// Same as fill_grid_pixels but does each pixel individually +/// Same as MatrixSync::flush_if_dirty 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 { diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index ed9c3156..a65c0001 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -36,6 +36,9 @@ 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; + /// List maximum current as 500mA in the USB descriptor const MAX_CURRENT: usize = 500; @@ -303,6 +306,7 @@ fn main() -> ! { 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(); @@ -413,6 +417,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() { @@ -503,7 +514,7 @@ fn main() -> ! { .unwrap(); // let _ = serial.write(text.as_bytes()); - display.flush_if_dirty(&state); + display.force_flush(&state); } (None, _) => {} } From 15e397d7d64f787f573167a55f4398c93737a13a Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 01:58:10 +0800 Subject: [PATCH 03/48] ledmatrix: Fix underflow when fading in with brightness below 5 If the brightness before sleep was below 5, `old_brightness - 5` underflowed. Debug builds would panic, release builds would fade up to full brightness before dropping back. Co-Authored-By: Claude Opus 5.5 --- ledmatrix/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index a65c0001..19978db4 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -685,7 +685,7 @@ fn handle_sleep( 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 From 1d7203a45bd77b7f87855038466480ccdd7e1cd2 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 01:58:18 +0800 Subject: [PATCH 04/48] ledmatrix: Restore grid after powering LED controller on On wake the grid was written before the controller's SDB pin was set high, and the write was recorded as sent. If the controller ignored it, nothing would write it again. Co-Authored-By: Claude Opus 5.5 --- ledmatrix/src/main.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index 19978db4..cc3b3ba2 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -673,12 +673,13 @@ fn handle_sleep( // Restore back grid before sleeping state.sleeping = SleepState::Awake; state.grid = old_grid; - display.flush_if_dirty(state); // Power LED controller back on if !debug_mode(state) { led_enable.set_high().unwrap(); } + // Must be after powering on, the controller may not have accepted writes while off + display.force_flush(state); // Slowly increase brightness if dyn_sleep_mode(state) == SleepMode::Fading { From c435f85d5eb0ecbc30c98b400b445dfe0963cd27 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 01:58:25 +0800 Subject: [PATCH 05/48] ledmatrix: Always power LED controller on when waking up The controller is turned off when going to sleep outside of debug mode. If debug mode was enabled during sleep (DIP1), it would stay off after waking up and the display would stay dark. Co-Authored-By: Claude Opus 5.5 --- ledmatrix/src/main.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index cc3b3ba2..f4a394a6 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -674,10 +674,9 @@ fn handle_sleep( state.sleeping = SleepState::Awake; state.grid = old_grid; - // Power LED controller back on - if !debug_mode(state) { - led_enable.set_high().unwrap(); - } + // Power LED controller back on. Even in debug mode, because it + // might have been turned off before debug mode was enabled. + led_enable.set_high().unwrap(); // Must be after powering on, the controller may not have accepted writes while off display.force_flush(state); From 1509b6ffcb70175dc7c7873a06cf34da590dbf60 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 01:58:34 +0800 Subject: [PATCH 06/48] fl16-inputmodules: Remove unused LED matrix helpers _fill_grid and full_brightness were never called. They wrote to the controller directly, bypassing MatrixSync's cache of what was sent. Co-Authored-By: Claude Opus 5.5 --- fl16-inputmodules/src/matrix_sync.rs | 20 +------------------- 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/fl16-inputmodules/src/matrix_sync.rs b/fl16-inputmodules/src/matrix_sync.rs index b3b43394..08ba0f95 100644 --- a/fl16-inputmodules/src/matrix_sync.rs +++ b/fl16-inputmodules/src/matrix_sync.rs @@ -1,6 +1,6 @@ use crate::control::PwmFreqArg; use crate::led_hal as bsp; -use crate::matrix::{Grid, LedmatrixState, HEIGHT, WIDTH}; +use crate::matrix::{LedmatrixState, HEIGHT, WIDTH}; use crate::patterns::BRIGHTNESS_LEVELS; use is31fl3741::devices::LedMatrix; use rp2040_hal::{ @@ -69,21 +69,3 @@ fn calc_brightnesses(state: &LedmatrixState, matrix: &Foo) -> [u8; PWM_BUF_LEN] } brightnesses } - -/// Same as MatrixSync::flush_if_dirty 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 full_brightness(matrix: &mut Foo) { - // Fills every pixel individually - //matrix.fill_brightness(0xFF).unwrap(); - - // Fills full page at once - matrix.device.fill(0xFF).unwrap(); -} From 373dac79be1307e635f9a83d6045826aef619333 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 01:58:40 +0800 Subject: [PATCH 07/48] ledmatrix: Set PWM frequency through MatrixSync at startup Co-Authored-By: Claude Opus 5.5 --- ledmatrix/src/main.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index f4a394a6..86a950c6 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -300,9 +300,8 @@ fn main() -> ! { .set_scaling(MAX_BRIGHTNESS) .expect("failed to set scaling"); - matrix.device.set_pwm_freq(state.pwm_freq.into()).unwrap(); - let mut display = MatrixSync::new(matrix); + display.set_pwm_freq(state.pwm_freq); display.flush_if_dirty(&state); let mut animation_timer = timer.get_counter().ticks(); From f66244fe75db5f3ce6471a75888288135b887308 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 01:58:50 +0800 Subject: [PATCH 08/48] ledmatrix: Update commented-out panic handler to use MatrixSync set_brightness was removed and fill_grid_pixels is private now. Co-Authored-By: Claude Opus 5.5 --- ledmatrix/src/main.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index 86a950c6..d6230f97 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -102,9 +102,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); +// state.brightness = 255; +// state.grid = display_panic(); +// display.force_flush(state); // // loop {} //} From 13edb8c9d700c93088c1c9921842c4bcb9ce9cda Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:10:30 +0800 Subject: [PATCH 09/48] ledmatrix: Add Stats command for measuring rendering throughput New command 0x21 returns performance counters as little-endian u32s: bytes received, commands parsed/rejected, frames committed, I2C flushes, total and max I2C flush time and max main loop time. Counters wrap, so the host should only compare two reads. The max values reset after each read. MatrixSync times the flushes itself, so every flush is counted, including sleep fades and force_flush. Co-Authored-By: Claude Opus 5.5 --- fl16-inputmodules/src/control.rs | 7 +++ fl16-inputmodules/src/matrix_sync.rs | 65 +++++++++++++++++++++++++++- ledmatrix/src/main.rs | 17 ++++++-- 3 files changed, 84 insertions(+), 5 deletions(-) diff --git a/fl16-inputmodules/src/control.rs b/fl16-inputmodules/src/control.rs index 2073a21d..2f829d9f 100644 --- a/fl16-inputmodules/src/control.rs +++ b/fl16-inputmodules/src/control.rs @@ -73,6 +73,7 @@ pub enum CommandVals { PwmFreq = 0x1E, DebugMode = 0x1F, Version = 0x20, + Stats = 0x21, } #[derive(num_derive::FromPrimitive)] @@ -213,6 +214,8 @@ pub enum Command { GetPwmFreq, SetDebugMode(bool), GetDebugMode, + /// Get performance counters + GetStats, _Unknown, } @@ -399,6 +402,7 @@ pub fn parse_module_command(count: usize, buf: &[u8]) -> Option { } else { Command::GetDebugMode }), + Some(CommandVals::Stats) => Some(Command::GetStats), _ => None, } } else { @@ -566,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) => { @@ -577,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 @@ -637,6 +643,7 @@ pub fn handle_command( response[0] = state.debug_mode as u8; Some(response) } + Command::GetStats => Some(display.stats.take_response()), _ => handle_generic_command(command), } } diff --git a/fl16-inputmodules/src/matrix_sync.rs b/fl16-inputmodules/src/matrix_sync.rs index 08ba0f95..0ff59e34 100644 --- a/fl16-inputmodules/src/matrix_sync.rs +++ b/fl16-inputmodules/src/matrix_sync.rs @@ -9,6 +9,7 @@ use rp2040_hal::{ FunctionI2C, PullUp, }, pac::I2C1, + Timer, }; pub type Foo = LedMatrix< @@ -24,23 +25,83 @@ pub type Foo = LedMatrix< /// 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, +} + +impl Stats { + /// Serialize as little-endian u32s and reset the max values + pub fn take_response(&mut self) -> [u8; 32] { + 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, + ]; + 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()); + } + self.flush_us_max = 0; + self.loop_us_max = 0; + response + } +} + pub struct MatrixSync { matrix: Foo, /// PWM values last sent to the LED controller. None if unknown sent: Option<[u8; PWM_BUF_LEN]>, + timer: Timer, + pub stats: Stats, } impl MatrixSync { - pub fn new(matrix: Foo) -> Self { - Self { matrix, sent: None } + pub fn new(matrix: Foo, timer: Timer) -> Self { + Self { + matrix, + sent: None, + timer, + stats: Stats::default(), + } } /// Fills the grid pixels but only sends the I2C commands if the PWM values changed pub fn flush_if_dirty(&mut self, state: &LedmatrixState) { let brightnesses = calc_brightnesses(state, &self.matrix); 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); } } diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index d6230f97..2c42f797 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -77,6 +77,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, @@ -102,7 +103,7 @@ const MAX_BRIGHTNESS: u8 = 50; // .setup(&mut delay) // .expect("failed to setup rgb controller"); // -// let mut display = MatrixSync::new(matrix); +// let mut display = MatrixSync::new(matrix, timer); // state.brightness = 255; // state.grid = display_panic(); // display.force_flush(state); @@ -301,7 +302,7 @@ fn main() -> ! { .set_scaling(MAX_BRIGHTNESS) .expect("failed to set scaling"); - let mut display = MatrixSync::new(matrix); + let mut display = MatrixSync::new(matrix, timer); display.set_pwm_freq(state.pwm_freq); display.flush_if_dirty(&state); @@ -331,6 +332,7 @@ fn main() -> ! { let mut last_host_sleep = sleep.is_low().unwrap(); loop { + let loop_start = timer.get_counter().ticks(); last_sleep_reason = sleep_reason; state.debug_mode = dip1.is_low().unwrap(); @@ -453,6 +455,8 @@ fn main() -> ! { // Do nothing } Ok(count) => { + 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 @@ -461,6 +465,7 @@ fn main() -> ! { 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, @@ -516,7 +521,10 @@ fn main() -> ! { display.force_flush(&state); } - (None, _) => {} + (None, _) => { + display.stats.cmds_rejected = + display.stats.cmds_rejected.wrapping_add(1); + } } } } @@ -577,6 +585,9 @@ fn main() -> ! { } game_timer = timer.get_counter().ticks(); } + + let loop_us = (timer.get_counter().ticks() - loop_start) as u32; + display.stats.loop_us_max = display.stats.loop_us_max.max(loop_us); } } From b852c2e8ea68ba6997575a790a294c196f14a14f Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:10:30 +0800 Subject: [PATCH 10/48] inputmodule-control: Add --benchmark for LED matrix throughput Streams changing greyscale frames for the given number of seconds and reports host send rate. With firmware that supports the Stats command, also reports bytes and commands received, frames committed, I2C flushes and timing, measured on the device. Wakes the module and waits for the fade-in before starting, because the firmware doesn't service USB while fading in. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 144 +++++++++++++++++++++++++ inputmodule-control/src/ledmatrix.rs | 4 + 2 files changed, 148 insertions(+) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index 8008cbb4..96250769 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -50,6 +50,7 @@ enum Command { PwmFreq = 0x1E, DebugMode = 0x1F, Version = 0x20, + Stats = 0x21, } enum GameControlArg { @@ -246,6 +247,9 @@ 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)); + } } // Commands that block and need manual looping if ledmatrix_args.blinking { @@ -530,6 +534,146 @@ 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, +} + +/// 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. +fn get_stats(port: &mut Box) -> Option { + simple_cmd_port(port, Command::Stats, &[]); + + let mut response = [0; 32]; + port.read_exact(&mut response).ok()?; + let val = |i: usize| u32::from_le_bytes(response[i * 4..i * 4 + 4].try_into().unwrap()); + Some(DeviceStats { + bytes_received: val(0), + cmds_parsed: val(1), + cmds_rejected: val(2), + frames_committed: val(3), + flushes: val(4), + flush_us_total: val(5), + flush_us_max: val(6), + loop_us_max: val(7), + }) +} + +/// Stream changing greyscale frames as fast as possible and report the throughput +fn benchmark_cmd(serialdev: &str, duration: Duration) { + // 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"); + + // Wake up and wait until the fade-in is done, so it doesn't count towards the benchmark + simple_cmd_port(&mut port, Command::Sleeping, &[0]); + simple_cmd_port(&mut port, Command::Version, &[]); + let mut response = [0; 32]; + port.read_exact(&mut response) + .expect("Device didn't respond to version request"); + + // 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; + let start = std::time::Instant::now(); + while start.elapsed() < duration { + // Bright row moving down with a fading tail, so that every frame is different + let head = frames as usize % HEIGHT; + 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; + } + send_col(&mut port, x as u8, &vals); + bytes += 3 + 1 + HEIGHT as u32; + } + commit_cols(&mut port); + bytes += 3; + cmds += WIDTH as u32 + 1; + 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 + ); + + let (Some(before), Some(after)) = (before, after) else { + return; + }; + let delta = |f: fn(&DeviceStats) -> u32| f(&after).wrapping_sub(f(&before)); + // The final stats request itself counts as one command of 3 bytes + let bytes_received = delta(|s| s.bytes_received).wrapping_sub(3); + let cmds_parsed = delta(|s| s.cmds_parsed).wrapping_sub(1); + 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); +} + ///Increase the brightness with each pixel. ///Only 0-255 available, so it can't fill all 306 LEDs fn all_brightnesses_cmd(serialdev: &str) { diff --git a/inputmodule-control/src/ledmatrix.rs b/inputmodule-control/src/ledmatrix.rs index 656ddee6..9e26ff8b 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -137,6 +137,10 @@ pub struct LedMatrixSubcommand { #[arg(long)] pub debug_mode: Option>, + /// Stream greyscale frames for this many seconds and report throughput + #[arg(long)] + pub benchmark: Option, + /// Crash the firmware (TESTING ONLY!) #[arg(long)] pub panic: bool, From 719830e834ff3f077accf43f2690e33136291ed7 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:10:40 +0800 Subject: [PATCH 11/48] ledmatrix: Only flush after a command if the output changed Resending the full grid after every command took 3.7ms of I2C each time, even for commands that don't change the output, like staging a greyscale column. A greyscale frame caused 10 flushes instead of one. The periodic refresh still resends the grid once per second, so the controller still recovers if it loses its state, just not right after the next command anymore. Greyscale benchmark: 10.2 -> 16.7 FPS, 10.1 -> 1.1 flushes per frame. Co-Authored-By: Claude Opus 5.5 --- ledmatrix/src/main.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index 2c42f797..0bc0c63d 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -519,7 +519,10 @@ fn main() -> ! { .unwrap(); // let _ = serial.write(text.as_bytes()); - display.force_flush(&state); + // 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 = From 996312d7e70a9142e0a0a5449e9638d73ac2ad8a Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:11:51 +0800 Subject: [PATCH 12/48] inputmodule-control: Add black and white mode to --benchmark --benchmark-mode bw sends one Draw command per frame, instead of the nine StageGreyCol and one DrawGreyColBuffer of the default grey mode. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 47 ++++++++++++++++++-------- inputmodule-control/src/ledmatrix.rs | 15 +++++++- 2 files changed, 47 insertions(+), 15 deletions(-) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index 96250769..c7153c07 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -11,7 +11,7 @@ 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, Game, GameOfLifeStartParam, Pattern}; const FWK_MAGIC: &[u8] = &[0x32, 0xAC]; pub const FRAMEWORK_VID: u16 = 0x32AC; @@ -248,7 +248,11 @@ pub fn serial_commands(args: &crate::ClapCli) { get_device_version(serialdev); } if let Some(secs) = ledmatrix_args.benchmark { - benchmark_cmd(serialdev, Duration::from_secs(secs)); + benchmark_cmd( + serialdev, + Duration::from_secs(secs), + ledmatrix_args.benchmark_mode, + ); } } // Commands that block and need manual looping @@ -568,7 +572,7 @@ fn get_stats(port: &mut Box) -> Option { } /// Stream changing greyscale frames as fast as possible and report the throughput -fn benchmark_cmd(serialdev: &str, duration: Duration) { +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)) @@ -597,20 +601,35 @@ fn benchmark_cmd(serialdev: &str, duration: Duration) { let mut bytes: u32 = 0; let start = std::time::Instant::now(); while start.elapsed() < duration { - // Bright row moving down with a fading tail, so that every frame is different + // Bright row moving down, so that every frame is different let head = frames as usize % HEIGHT; - 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; + 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; + } + send_col(&mut port, x as u8, &vals); + bytes += 3 + 1 + HEIGHT as u32; + } + commit_cols(&mut port); + 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); + } + simple_cmd_port(&mut port, Command::DisplayBwImage, &vals); + bytes += 3 + vals.len() as u32; + cmds += 1; } - send_col(&mut port, x as u8, &vals); - bytes += 3 + 1 + HEIGHT as u32; } - commit_cols(&mut port); - bytes += 3; - cmds += WIDTH as u32 + 1; frames += 1; } diff --git a/inputmodule-control/src/ledmatrix.rs b/inputmodule-control/src/ledmatrix.rs index 9e26ff8b..39c07519 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -24,6 +24,14 @@ 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, +} + #[derive(Copy, Clone, Debug, PartialEq, clap::ValueEnum)] pub enum GameOfLifeStartParam { CurrentMatrix = 0x00, @@ -137,10 +145,15 @@ pub struct LedMatrixSubcommand { #[arg(long)] pub debug_mode: Option>, - /// Stream greyscale frames for this many seconds and report throughput + /// 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, + /// Crash the firmware (TESTING ONLY!) #[arg(long)] pub panic: bool, From 9bed2ad5358f1ce769018d5847c794527fb2aebe Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:14:00 +0800 Subject: [PATCH 13/48] inputmodule-control: Measure host write time in --benchmark Time each write call and report avg, p50, p99 and max, plus the share of total time spent blocked in writes. Shows whether the host is waiting on the device/USB or spending time preparing frames. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index c7153c07..d1eb77a3 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -599,6 +599,8 @@ fn benchmark_cmd(serialdev: &str, duration: Duration, mode: BenchmarkMode) { 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 @@ -612,10 +614,14 @@ fn benchmark_cmd(serialdev: &str, duration: Duration, mode: BenchmarkMode) { 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; } @@ -625,7 +631,9 @@ fn benchmark_cmd(serialdev: &str, duration: Duration, mode: BenchmarkMode) { 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; } @@ -653,6 +661,18 @@ fn benchmark_cmd(serialdev: &str, duration: Duration, mode: BenchmarkMode) { bytes as f64 / elapsed / 1024.0 ); + write_times.sort(); + let write_total: Duration = write_times.iter().sum(); + 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().max(1) 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; }; From b164341df652792e9e5f65c074b9b7a4496b5f71 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:15:34 +0800 Subject: [PATCH 14/48] ledmatrix: Add stats page with main loop idle and busy time Stats command now takes an optional page argument. Page 0, the default, returns the same counters as before. Page 1 returns main loop iterations, iterations without USB data and the time spent in iterations with and without USB data. That shows whether the firmware is waiting for USB data or busy while the host is blocked writing. Co-Authored-By: Claude Opus 5.5 --- fl16-inputmodules/src/control.rs | 8 ++--- fl16-inputmodules/src/matrix_sync.rs | 54 ++++++++++++++++++++-------- ledmatrix/src/main.rs | 9 +++++ 3 files changed, 53 insertions(+), 18 deletions(-) diff --git a/fl16-inputmodules/src/control.rs b/fl16-inputmodules/src/control.rs index 2f829d9f..56bb54d9 100644 --- a/fl16-inputmodules/src/control.rs +++ b/fl16-inputmodules/src/control.rs @@ -214,8 +214,8 @@ pub enum Command { GetPwmFreq, SetDebugMode(bool), GetDebugMode, - /// Get performance counters - GetStats, + /// Get a page of performance counters + GetStats(u8), _Unknown, } @@ -402,7 +402,7 @@ pub fn parse_module_command(count: usize, buf: &[u8]) -> Option { } else { Command::GetDebugMode }), - Some(CommandVals::Stats) => Some(Command::GetStats), + Some(CommandVals::Stats) => Some(Command::GetStats(arg.unwrap_or(0))), _ => None, } } else { @@ -643,7 +643,7 @@ pub fn handle_command( response[0] = state.debug_mode as u8; Some(response) } - Command::GetStats => Some(display.stats.take_response()), + Command::GetStats(page) => Some(display.stats.take_response(*page)), _ => handle_generic_command(command), } } diff --git a/fl16-inputmodules/src/matrix_sync.rs b/fl16-inputmodules/src/matrix_sync.rs index 0ff59e34..ebbe3549 100644 --- a/fl16-inputmodules/src/matrix_sync.rs +++ b/fl16-inputmodules/src/matrix_sync.rs @@ -47,27 +47,53 @@ pub struct Stats { 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, } impl Stats { - /// Serialize as little-endian u32s and reset the max values - pub fn take_response(&mut self) -> [u8; 32] { - 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, - ]; + /// Serialize a page as little-endian u32s + /// + /// Page 0 resets the max values, page 1 doesn't have any. + 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 => [ + self.loops, + self.idle_loops, + self.idle_us_total, + self.busy_us_total, + 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()); } - self.flush_us_max = 0; - self.loop_us_max = 0; response } } diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index 0bc0c63d..8c850132 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -333,6 +333,7 @@ fn main() -> ! { 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(); @@ -455,6 +456,7 @@ 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); @@ -591,6 +593,13 @@ fn main() -> ! { let loop_us = (timer.get_counter().ticks() - loop_start) as u32; display.stats.loop_us_max = display.stats.loop_us_max.max(loop_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); + } } } From c1945b1d8fb1734a08d08424a7e58139f18cee23 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:16:45 +0800 Subject: [PATCH 15/48] inputmodule-control: Show device busy and idle time in --benchmark Read stats page 1 and report how many main loop iterations received USB data, how long they took on average, and how much of the time the firmware was idle waiting for data. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 71 ++++++++++++++++++++------ 1 file changed, 55 insertions(+), 16 deletions(-) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index d1eb77a3..dfc05564 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -549,25 +549,44 @@ struct DeviceStats { 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, } -/// 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. -fn get_stats(port: &mut Box) -> Option { - simple_cmd_port(port, Command::Stats, &[]); +/// 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 val = |i: usize| u32::from_le_bytes(response[i * 4..i * 4 + 4].try_into().unwrap()); + 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 two 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)?; Some(DeviceStats { - bytes_received: val(0), - cmds_parsed: val(1), - cmds_rejected: val(2), - frames_committed: val(3), - flushes: val(4), - flush_us_total: val(5), - flush_us_max: val(6), - loop_us_max: val(7), + 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], }) } @@ -677,9 +696,10 @@ fn benchmark_cmd(serialdev: &str, duration: Duration, mode: BenchmarkMode) { return; }; let delta = |f: fn(&DeviceStats) -> u32| f(&after).wrapping_sub(f(&before)); - // The final stats request itself counts as one command of 3 bytes - let bytes_received = delta(|s| s.bytes_received).wrapping_sub(3); - let cmds_parsed = delta(|s| s.cmds_parsed).wrapping_sub(1); + // The second 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(8); + let cmds_parsed = delta(|s| s.cmds_parsed).wrapping_sub(2); let cmds_rejected = delta(|s| s.cmds_rejected); let frames_committed = delta(|s| s.frames_committed); let flushes = delta(|s| s.flushes); @@ -711,6 +731,25 @@ fn benchmark_cmd(serialdev: &str, duration: Duration, mode: BenchmarkMode) { 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 + ); } ///Increase the brightness with each pixel. From f60689d5e9ecf4a09dcf6fdb5c9c65cc3bebd8b6 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:17:23 +0800 Subject: [PATCH 16/48] ledmatrix: Measure time spent calculating PWM values flush_if_dirty calculates the PWM values for the whole grid on every call, to compare them with what was sent. Add count, total and max time of that calculation to stats page 1. Co-Authored-By: Claude Opus 5.5 --- fl16-inputmodules/src/matrix_sync.rs | 38 ++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/fl16-inputmodules/src/matrix_sync.rs b/fl16-inputmodules/src/matrix_sync.rs index ebbe3549..fa5ad59b 100644 --- a/fl16-inputmodules/src/matrix_sync.rs +++ b/fl16-inputmodules/src/matrix_sync.rs @@ -55,12 +55,18 @@ pub struct Stats { 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, } impl Stats { /// Serialize a page as little-endian u32s /// - /// Page 0 resets the max values, page 1 doesn't have any. + /// Each page resets the max values it contains. pub fn take_response(&mut self, page: u8) -> [u8; 32] { let vals = match page { 0 => { @@ -78,16 +84,20 @@ impl Stats { self.loop_us_max = 0; vals } - 1 => [ - self.loops, - self.idle_loops, - self.idle_us_total, - self.busy_us_total, - 0, - 0, - 0, - 0, - ], + 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, + 0, + ]; + self.calc_us_max = 0; + vals + } _ => [0; 8], }; let mut response = [0; 32]; @@ -118,7 +128,13 @@ impl MatrixSync { /// Fills the grid pixels but only sends the I2C commands if the PWM values changed pub fn flush_if_dirty(&mut self, state: &LedmatrixState) { + let calc_start = self.timer.get_counter().ticks(); let brightnesses = calc_brightnesses(state, &self.matrix); + 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); + if self.sent.as_ref() != Some(&brightnesses) { let start = self.timer.get_counter().ticks(); self.matrix.device.fill_matrix(&brightnesses).unwrap(); From fe0dca9c8b9a4784799fe5c55c9adefef32457ec Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:18:19 +0800 Subject: [PATCH 17/48] inputmodule-control: Show PWM calculation time in --benchmark Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index dfc05564..663eda63 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -553,6 +553,9 @@ struct DeviceStats { idle_loops: u32, idle_us_total: u32, busy_us_total: u32, + calcs: u32, + calc_us_total: u32, + calc_us_max: u32, } /// Read one page of performance counters. None if the firmware doesn't support it. @@ -587,6 +590,9 @@ fn get_stats(port: &mut Box) -> Option { 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], }) } @@ -750,6 +756,17 @@ fn benchmark_cmd(serialdev: &str, duration: Duration, mode: BenchmarkMode) { 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 + ); } ///Increase the brightness with each pixel. From 3b6cdfa2ad9559ee47068685b814df7464c9b428 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:19:53 +0800 Subject: [PATCH 18/48] ledmatrix: Speed up PWM value calculation 64x calc_pixel builds its 306 entry lookup table on the stack on every call and was called for every pixel, so each calculation copied around 187KB. Look up each pixel's PWM buffer index once in MatrixSync::new instead. Also use u32 instead of u64 math. 255 * 255 fits easily and 64-bit division is slow on the Cortex-M0+. The results are the same. PWM calculation: 4700us -> 73us Greyscale benchmark: 16.8 -> 187 FPS Black and white benchmark: 101.7 -> 255 FPS Co-Authored-By: Claude Opus 5.5 --- fl16-inputmodules/src/matrix_sync.rs | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/fl16-inputmodules/src/matrix_sync.rs b/fl16-inputmodules/src/matrix_sync.rs index fa5ad59b..9d5ca9a7 100644 --- a/fl16-inputmodules/src/matrix_sync.rs +++ b/fl16-inputmodules/src/matrix_sync.rs @@ -112,15 +112,26 @@ pub struct MatrixSync { matrix: Foo, /// 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, 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, sent: None, + pwm_index, timer, stats: Stats::default(), } @@ -129,7 +140,7 @@ impl MatrixSync { /// Fills the grid pixels but only sends the I2C commands if the PWM values changed pub fn flush_if_dirty(&mut self, state: &LedmatrixState) { let calc_start = self.timer.get_counter().ticks(); - let brightnesses = calc_brightnesses(state, &self.matrix); + 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); @@ -160,14 +171,17 @@ impl MatrixSync { } /// Calculate PWM values for the entire grid, so they can be sent with just two I2C commands -fn calc_brightnesses(state: &LedmatrixState, matrix: &Foo) -> [u8; PWM_BUF_LEN] { +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 { - 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; + // 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 From 22f405e69acaad549f3940d9729858d886522003 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:24:11 +0800 Subject: [PATCH 19/48] inputmodule-control: Add plasma demo with --fps limit --demo plasma streams overlapping greyscale sine waves to all selected LED matrices, printing the achieved frame rate every second. The animation depends on the time, not the frame count, so --fps only changes how smooth it looks, not how fast it moves. That makes it easy to compare frame rates side by side, e.g. --fps 15 on one module and uncapped on the other. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 83 +++++++++++++++++++++++++- inputmodule-control/src/ledmatrix.rs | 15 +++++ 2 files changed, 97 insertions(+), 1 deletion(-) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index 663eda63..d915d00d 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -11,7 +11,7 @@ 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::{BenchmarkMode, Game, GameOfLifeStartParam, Pattern}; +use crate::ledmatrix::{BenchmarkMode, Demo, Game, GameOfLifeStartParam, Pattern}; const FWK_MAGIC: &[u8] = &[0x32, 0xAC]; pub const FRAMEWORK_VID: u16 = 0x32AC; @@ -275,6 +275,10 @@ pub fn serial_commands(args: &crate::ClapCli) { if ledmatrix_args.clock { clock_cmd(&serialdevs); } + + if let Some(demo) = ledmatrix_args.demo { + demo_cmd(&serialdevs, demo, ledmatrix_args.fps); + } } Some(crate::Commands::B1Display(b1display_args)) => { for serialdev in &serialdevs { @@ -903,6 +907,83 @@ fn display_gray_image_cmd(serialdev: &str, image_path: &str) { commit_cols(&mut port); } +type GreyGrid = [[u8; HEIGHT]; WIDTH]; + +/// 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) -> GreyGrid { + let mut grid = [[0; HEIGHT]; WIDTH]; + // Center of the circular wave moves around + let cx = 4.0 + (t * 0.5).sin() * 3.0; + 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 +} + +/// Run a greyscale demo forever, as fast as possible or limited to fps +fn demo_cmd(serialdevs: &[String], demo: Demo, fps: Option) { + // Long timeout, because the firmware doesn't service USB while fading in after waking up + let mut ports: Vec<_> = serialdevs + .iter() + .map(|serialdev| { + serialport::new(serialdev, 115_200) + .timeout(Duration::from_secs(10)) + .open() + .expect("Failed to open port") + }) + .collect(); + + let start = std::time::Instant::now(); + let mut frames: u64 = 0; + let mut report_start = start; + let mut report_frames: u64 = 0; + loop { + let t = start.elapsed().as_secs_f32(); + let grid = match demo { + Demo::Plasma => plasma_frame(t), + }; + for port in &mut ports { + for (x, col) in grid.iter().enumerate() { + send_col(port, x as u8, col); + } + commit_cols(port); + } + frames += 1; + report_frames += 1; + + if report_start.elapsed() >= Duration::from_secs(1) { + let rate = report_frames as f64 / report_start.elapsed().as_secs_f64(); + print!("\r{:.1} FPS ", rate); + let _ = std::io::Write::flush(&mut std::io::stdout()); + report_start = std::time::Instant::now(); + report_frames = 0; + } + + 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 { diff --git a/inputmodule-control/src/ledmatrix.rs b/inputmodule-control/src/ledmatrix.rs index 39c07519..1a6a2ef4 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -32,6 +32,12 @@ pub enum BenchmarkMode { Bw, } +#[derive(Copy, Clone, Debug, PartialEq, clap::ValueEnum)] +pub enum Demo { + /// Flowing greyscale sine waves + Plasma, +} + #[derive(Copy, Clone, Debug, PartialEq, clap::ValueEnum)] pub enum GameOfLifeStartParam { CurrentMatrix = 0x00, @@ -154,6 +160,15 @@ pub struct LedMatrixSubcommand { #[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, + + /// Limit --demo to this many frames per second. Uncapped by default + #[arg(long)] + pub fps: Option, + /// Crash the firmware (TESTING ONLY!) #[arg(long)] pub panic: bool, From b8b77b1f0b5f0904c94794e68b4ca4cc5fec1443 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:25:26 +0800 Subject: [PATCH 20/48] inputmodule-control: Add fire demo --demo fire shows flames rising from the bottom, like the PSX Doom fire effect. The simulation runs at a fixed 30 steps per second and frames blend between steps, so higher frame rates look smoother instead of burning faster. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 63 ++++++++++++++++++++++++++ inputmodule-control/src/ledmatrix.rs | 2 + 2 files changed, 65 insertions(+) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index d915d00d..c68d3699 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -936,6 +936,66 @@ fn plasma_frame(t: f32) -> GreyGrid { 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: [[f32; HEIGHT]; WIDTH], + next: [[f32; HEIGHT]; WIDTH], + steps: u64, + rng: ThreadRng, +} + +impl Fire { + fn new() -> Self { + Self { + prev: [[0.0; HEIGHT]; WIDTH], + next: [[0.0; HEIGHT]; WIDTH], + steps: 0, + rng: thread_rng(), + } + } + + fn step(&mut self) { + self.prev = self.next; + let heat = &mut self.next; + // 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 = [[0; HEIGHT]; WIDTH]; + for x in 0..WIDTH { + for y in 0..HEIGHT { + let heat = self.prev[x][y] + (self.next[x][y] - self.prev[x][y]) * blend; + grid[x][y] = gamma(heat); + } + } + grid + } +} + /// Run a greyscale demo forever, as fast as possible or limited to fps fn demo_cmd(serialdevs: &[String], demo: Demo, fps: Option) { // Long timeout, because the firmware doesn't service USB while fading in after waking up @@ -949,6 +1009,8 @@ fn demo_cmd(serialdevs: &[String], demo: Demo, fps: Option) { }) .collect(); + let mut fire = Fire::new(); + let start = std::time::Instant::now(); let mut frames: u64 = 0; let mut report_start = start; @@ -957,6 +1019,7 @@ fn demo_cmd(serialdevs: &[String], demo: Demo, fps: Option) { let t = start.elapsed().as_secs_f32(); let grid = match demo { Demo::Plasma => plasma_frame(t), + Demo::Fire => fire.frame(t), }; for port in &mut ports { for (x, col) in grid.iter().enumerate() { diff --git a/inputmodule-control/src/ledmatrix.rs b/inputmodule-control/src/ledmatrix.rs index 1a6a2ef4..1516a3ec 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -36,6 +36,8 @@ pub enum BenchmarkMode { pub enum Demo { /// Flowing greyscale sine waves Plasma, + /// Flames rising from the bottom + Fire, } #[derive(Copy, Clone, Debug, PartialEq, clap::ValueEnum)] From feb659272570735189dbc12da77502f5eb020ceb Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:28:36 +0800 Subject: [PATCH 21/48] inputmodule-control: Add smoothly scrolling text demo --demo text scrolls text up the LED matrix, set with --demo-text (default "FRAMEWORK"). Characters are stacked like with --string, but the text moves by fractions of a pixel, blending neighboring rows, so it glides instead of jumping a whole row at a time. The blend is linear, without gamma, so the total light stays the same while a row moves between two LEDs. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 59 +++++++++++++++++++++++++- inputmodule-control/src/ledmatrix.rs | 6 +++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index c68d3699..c14ec455 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -277,7 +277,12 @@ pub fn serial_commands(args: &crate::ClapCli) { } if let Some(demo) = ledmatrix_args.demo { - demo_cmd(&serialdevs, demo, ledmatrix_args.fps); + demo_cmd( + &serialdevs, + demo, + &ledmatrix_args.demo_text, + ledmatrix_args.fps, + ); } } Some(crate::Commands::B1Display(b1display_args)) => { @@ -996,8 +1001,56 @@ impl Fire { } } +/// 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 +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]>, +} + +impl ScrollingText { + fn new(text: &str) -> Self { + // Start with an empty screen, so the text scrolls in from the bottom and out at the top + let mut rows = vec![[0.0; WIDTH]; HEIGHT]; + // 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 } + } + + /// 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 = [[0; HEIGHT]; WIDTH]; + for y in 0..HEIGHT { + let pos = offset + 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[x][y] = (brightness * 255.0) as u8; + } + } + grid + } +} + /// Run a greyscale demo forever, as fast as possible or limited to fps -fn demo_cmd(serialdevs: &[String], demo: Demo, fps: Option) { +fn demo_cmd(serialdevs: &[String], demo: Demo, text: &str, fps: Option) { // Long timeout, because the firmware doesn't service USB while fading in after waking up let mut ports: Vec<_> = serialdevs .iter() @@ -1010,6 +1063,7 @@ fn demo_cmd(serialdevs: &[String], demo: Demo, fps: Option) { .collect(); let mut fire = Fire::new(); + let scrolling_text = ScrollingText::new(text); let start = std::time::Instant::now(); let mut frames: u64 = 0; @@ -1020,6 +1074,7 @@ fn demo_cmd(serialdevs: &[String], demo: Demo, fps: Option) { let grid = match demo { Demo::Plasma => plasma_frame(t), Demo::Fire => fire.frame(t), + Demo::Text => scrolling_text.frame(t), }; for port in &mut ports { for (x, col) in grid.iter().enumerate() { diff --git a/inputmodule-control/src/ledmatrix.rs b/inputmodule-control/src/ledmatrix.rs index 1516a3ec..1535a507 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -38,6 +38,8 @@ pub enum Demo { Plasma, /// Flames rising from the bottom Fire, + /// Text scrolling up smoothly, set with --demo-text + Text, } #[derive(Copy, Clone, Debug, PartialEq, clap::ValueEnum)] @@ -167,6 +169,10 @@ pub struct LedMatrixSubcommand { #[clap(value_enum)] pub demo: Option, + /// Text for --demo text + #[arg(long, default_value = "FRAMEWORK")] + pub demo_text: String, + /// Limit --demo to this many frames per second. Uncapped by default #[arg(long)] pub fps: Option, From a522db3ed245d5fb68f390744fc297360473e5cc Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:41:06 +0800 Subject: [PATCH 22/48] inputmodule-control: Extract frame streaming helpers from demo_cmd Opening ports, sending a greyscale frame and reporting the frame rate are needed for video playback too. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 68 ++++++++++++++++++-------- 1 file changed, 47 insertions(+), 21 deletions(-) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index c14ec455..d1be39d6 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -1049,10 +1049,10 @@ impl ScrollingText { } } -/// Run a greyscale demo forever, as fast as possible or limited to fps -fn demo_cmd(serialdevs: &[String], demo: Demo, text: &str, fps: Option) { +/// Open ports for streaming frames +fn open_stream_ports(serialdevs: &[String]) -> Vec> { // Long timeout, because the firmware doesn't service USB while fading in after waking up - let mut ports: Vec<_> = serialdevs + serialdevs .iter() .map(|serialdev| { serialport::new(serialdev, 115_200) @@ -1060,15 +1060,54 @@ fn demo_cmd(serialdevs: &[String], demo: Demo, text: &str, fps: Option) { .open() .expect("Failed to open port") }) - .collect(); + .collect() +} + +/// Send a greyscale frame to every port +fn send_grey_frame(ports: &mut [Box], grid: &GreyGrid) { + for port in ports { + for (x, col) in grid.iter().enumerate() { + send_col(port, x as u8, col); + } + commit_cols(port); + } +} + +/// Prints the achieved frame rate once per second +struct FpsReporter { + start: std::time::Instant, + frames: u64, +} + +impl FpsReporter { + fn new() -> Self { + Self { + start: std::time::Instant::now(), + frames: 0, + } + } + + fn frame_sent(&mut self) { + self.frames += 1; + if self.start.elapsed() >= Duration::from_secs(1) { + let rate = self.frames as f64 / self.start.elapsed().as_secs_f64(); + print!("\r{:.1} FPS ", rate); + let _ = std::io::Write::flush(&mut std::io::stdout()); + *self = Self::new(); + } + } +} + +/// Run a greyscale demo forever, as fast as possible or limited to fps +fn demo_cmd(serialdevs: &[String], demo: Demo, text: &str, fps: Option) { + let mut ports = open_stream_ports(serialdevs); let mut fire = Fire::new(); let scrolling_text = ScrollingText::new(text); let start = std::time::Instant::now(); let mut frames: u64 = 0; - let mut report_start = start; - let mut report_frames: u64 = 0; + let mut reporter = FpsReporter::new(); loop { let t = start.elapsed().as_secs_f32(); let grid = match demo { @@ -1076,22 +1115,9 @@ fn demo_cmd(serialdevs: &[String], demo: Demo, text: &str, fps: Option) { Demo::Fire => fire.frame(t), Demo::Text => scrolling_text.frame(t), }; - for port in &mut ports { - for (x, col) in grid.iter().enumerate() { - send_col(port, x as u8, col); - } - commit_cols(port); - } + send_grey_frame(&mut ports, &grid); frames += 1; - report_frames += 1; - - if report_start.elapsed() >= Duration::from_secs(1) { - let rate = report_frames as f64 / report_start.elapsed().as_secs_f64(); - print!("\r{:.1} FPS ", rate); - let _ = std::io::Write::flush(&mut std::io::stdout()); - report_start = std::time::Instant::now(); - report_frames = 0; - } + reporter.frame_sent(); if let Some(fps) = fps { let next_frame = start + Duration::from_secs_f64(frames as f64 / fps as f64); From c13c4068ae182c271ed05d46db4ea5758260556a Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:43:56 +0800 Subject: [PATCH 23/48] inputmodule-control: Add --video to play videos on the LED matrix Like --video of the Python tool: scale the video to the height of the matrix, crop the middle and show it in greyscale. ffmpeg, which must be in PATH, decodes and scales the frames and pipes them as raw greyscale. Unlike the Python version, frames are paced to the video's frame rate from ffprobe, instead of being sent as fast as the module accepts them. With --fps, ffmpeg resamples the video to that frame rate instead. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 83 ++++++++++++++++++++++++++ inputmodule-control/src/ledmatrix.rs | 7 ++- 2 files changed, 89 insertions(+), 1 deletion(-) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index d1be39d6..16d7042b 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -276,6 +276,10 @@ pub fn serial_commands(args: &crate::ClapCli) { clock_cmd(&serialdevs); } + if let Some(path) = &ledmatrix_args.video { + video_cmd(&serialdevs, path, ledmatrix_args.fps); + } + if let Some(demo) = ledmatrix_args.demo { demo_cmd( &serialdevs, @@ -1098,6 +1102,85 @@ impl FpsReporter { } } +/// 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) +} + +/// Play a video in greyscale at its own frame rate, or resampled to fps. +/// ffmpeg decodes and scales the frames. +fn video_cmd(serialdevs: &[String], path: &str, fps: Option) { + // 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 ffmpeg = std::process::Command::new("ffmpeg") + .args(["-loglevel", "error", "-nostdin"]) + .args(["-i", path, "-vf", &filter, "-f", "rawvideo", "-"]) + .stdout(std::process::Stdio::piped()) + .spawn(); + let mut ffmpeg = match ffmpeg { + Ok(ffmpeg) => ffmpeg, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => { + println!("ffmpeg not found. Please install it and make sure it's in PATH"); + return; + } + Err(err) => panic!("Failed to run ffmpeg: {err}"), + }; + let mut video = ffmpeg.stdout.take().unwrap(); + + 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 + }), + }; + + let mut ports = open_stream_ports(serialdevs); + let mut reporter = FpsReporter::new(); + // One byte per pixel, row by row + let mut pixels = [0; WIDTH * HEIGHT]; + let mut start = None; + let mut frames: u64 = 0; + while std::io::Read::read_exact(&mut video, &mut pixels).is_ok() { + // 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 = [[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); + } + } + send_grey_frame(&mut ports, &grid); + reporter.frame_sent(); + } + let _ = ffmpeg.wait(); + println!(); +} + /// Run a greyscale demo forever, as fast as possible or limited to fps fn demo_cmd(serialdevs: &[String], demo: Demo, text: &str, fps: Option) { let mut ports = open_stream_ports(serialdevs); diff --git a/inputmodule-control/src/ledmatrix.rs b/inputmodule-control/src/ledmatrix.rs index 1535a507..2959db94 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -173,7 +173,12 @@ pub struct LedMatrixSubcommand { #[arg(long, default_value = "FRAMEWORK")] pub demo_text: String, - /// Limit --demo to this many frames per second. Uncapped by default + /// Play a video file in greyscale. Requires ffmpeg in PATH + #[arg(long)] + pub video: Option, + + /// Limit --demo or --video to this many frames per second. + /// Uncapped for --demo and the video's frame rate for --video by default #[arg(long)] pub fps: Option, From 4d6a090e2e946eb55f09b1e661e874ee1b7d5ff4 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:49:14 +0800 Subject: [PATCH 24/48] inputmodule-control: Wake LED matrix before streaming frames While fading in after waking up, the firmware doesn't service USB, so the first frame of a demo or video stalled for about a second. Video playback then rushed to catch up, playing the beginning too fast. Wake up the matrix and wait for the fade-in when opening the ports, like the benchmark already did. Also start counting the frame rate at the first frame, so startup time doesn't show as a slow first second. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 48 ++++++++++++++++++-------- 1 file changed, 33 insertions(+), 15 deletions(-) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index 16d7042b..d91c8cb8 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -609,6 +609,18 @@ fn get_stats(port: &mut Box) -> Option { }) } +/// 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 @@ -617,12 +629,8 @@ fn benchmark_cmd(serialdev: &str, duration: Duration, mode: BenchmarkMode) { .open() .expect("Failed to open port"); - // Wake up and wait until the fade-in is done, so it doesn't count towards the benchmark - simple_cmd_port(&mut port, Command::Sleeping, &[0]); - simple_cmd_port(&mut port, Command::Version, &[]); - let mut response = [0; 32]; - port.read_exact(&mut response) - .expect("Device didn't respond to version request"); + // 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(); @@ -1053,16 +1061,18 @@ impl ScrollingText { } } -/// Open ports for streaming frames +/// Open ports for streaming frames and wake up the LED matrices fn open_stream_ports(serialdevs: &[String]) -> Vec> { - // Long timeout, because the firmware doesn't service USB while fading in after waking up serialdevs .iter() .map(|serialdev| { - serialport::new(serialdev, 115_200) + // 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") + .expect("Failed to open port"); + wake_and_wait(&mut port); + port }) .collect() } @@ -1079,25 +1089,33 @@ fn send_grey_frame(ports: &mut [Box], grid: &GreyGrid) { /// Prints the achieved frame rate once per second struct FpsReporter { - start: std::time::Instant, + /// When the first frame of the current second was sent + start: Option, + /// Frames sent since then frames: u64, } impl FpsReporter { fn new() -> Self { Self { - start: std::time::Instant::now(), + start: None, frames: 0, } } 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 self.start.elapsed() >= Duration::from_secs(1) { - let rate = self.frames as f64 / self.start.elapsed().as_secs_f64(); + if start.elapsed() >= Duration::from_secs(1) { + let rate = self.frames as f64 / start.elapsed().as_secs_f64(); print!("\r{:.1} FPS ", rate); let _ = std::io::Write::flush(&mut std::io::stdout()); - *self = Self::new(); + self.start = Some(std::time::Instant::now()); + self.frames = 0; } } } From d6dc24b64427303a7fb23a53920a6aa542fb6a1b Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 02:49:45 +0800 Subject: [PATCH 25/48] inputmodule-control: Add --camera to show the webcam on the LED matrix Like --camera of the Python tool. Uses ffmpeg with dshow on Windows, v4l2 on Linux and avfoundation on macOS. Uses the first camera by default, /dev/video0 on Linux and device 0 on macOS, or the given device name, path or index. Shares the ffmpeg streaming with --video, but sends frames as soon as they come in, since the camera already delivers them in real time. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 142 ++++++++++++++++++++----- inputmodule-control/src/ledmatrix.rs | 10 +- 2 files changed, 121 insertions(+), 31 deletions(-) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index d91c8cb8..bdc011a2 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -280,6 +280,10 @@ pub fn serial_commands(args: &crate::ClapCli) { video_cmd(&serialdevs, path, ledmatrix_args.fps); } + if let Some(device) = &ledmatrix_args.camera { + camera_cmd(&serialdevs, device.as_deref(), ledmatrix_args.fps); + } + if let Some(demo) = ledmatrix_args.demo { demo_cmd( &serialdevs, @@ -1135,9 +1139,102 @@ fn video_frame_rate(path: &str) -> Option { (rate.is_finite() && rate > 0.0).then_some(rate) } -/// Play a video in greyscale at its own frame rate, or resampled to fps. -/// ffmpeg decodes and scales the frames. +/// 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], 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, &["-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], 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, &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], 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 ports = open_stream_ports(serialdevs); + // 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!( @@ -1146,44 +1243,31 @@ fn video_cmd(serialdevs: &[String], path: &str, fps: Option) { if let Some(fps) = fps { filter = format!("fps={fps},{filter}"); } - let ffmpeg = std::process::Command::new("ffmpeg") + let mut ffmpeg = std::process::Command::new("ffmpeg") .args(["-loglevel", "error", "-nostdin"]) - .args(["-i", path, "-vf", &filter, "-f", "rawvideo", "-"]) + .args(input) + .args(["-vf", &filter, "-f", "rawvideo", "-"]) .stdout(std::process::Stdio::piped()) - .spawn(); - let mut ffmpeg = match ffmpeg { - Ok(ffmpeg) => ffmpeg, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => { - println!("ffmpeg not found. Please install it and make sure it's in PATH"); - return; - } - Err(err) => panic!("Failed to run ffmpeg: {err}"), - }; + .spawn() + .expect("Failed to run ffmpeg"); let mut video = ffmpeg.stdout.take().unwrap(); - 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 - }), - }; - - let mut ports = open_stream_ports(serialdevs); let mut reporter = FpsReporter::new(); // One byte per pixel, row by row let mut pixels = [0; WIDTH * HEIGHT]; let mut start = None; let mut frames: u64 = 0; while std::io::Read::read_exact(&mut video, &mut pixels).is_ok() { - // 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); + 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; } - frames += 1; let mut grid = [[0; HEIGHT]; WIDTH]; for (x, col) in grid.iter_mut().enumerate() { diff --git a/inputmodule-control/src/ledmatrix.rs b/inputmodule-control/src/ledmatrix.rs index 2959db94..81cf66a8 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -177,8 +177,14 @@ pub struct LedMatrixSubcommand { #[arg(long)] pub video: Option, - /// Limit --demo or --video to this many frames per second. - /// Uncapped for --demo and the video's frame rate for --video by default + /// 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>, + + /// Limit --demo, --video or --camera to this many frames per second. + /// Uncapped for --demo, the video's frame rate for --video + /// and the camera's frame rate for --camera by default #[arg(long)] pub fps: Option, From fecc312cb582c941fd551544168b4f731222a564 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 03:11:05 +0800 Subject: [PATCH 26/48] ledmatrix: Add CPU wait time to stats page 1 Use the last free slot of stats page 1 for the time the CPU spent asleep waiting for an event. Nothing waits yet, so it's always zero until the main loop stops busy polling. Co-Authored-By: Claude Opus 5.5 --- fl16-inputmodules/src/matrix_sync.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/fl16-inputmodules/src/matrix_sync.rs b/fl16-inputmodules/src/matrix_sync.rs index 9d5ca9a7..9630c61d 100644 --- a/fl16-inputmodules/src/matrix_sync.rs +++ b/fl16-inputmodules/src/matrix_sync.rs @@ -61,6 +61,8 @@ pub struct Stats { 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, } impl Stats { @@ -93,7 +95,7 @@ impl Stats { self.calcs, self.calc_us_total, self.calc_us_max, - 0, + self.wait_us_total, ]; self.calc_us_max = 0; vals From 867c6613ee4d8239e575b01f194aa3a6264e28c5 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 03:11:06 +0800 Subject: [PATCH 27/48] inputmodule-control: Show CPU asleep time in --benchmark Read the wait time from stats page 1 and report it as a share of the device time. Old firmware reports zero in that slot. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index bdc011a2..dc2fd88f 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -573,6 +573,7 @@ struct DeviceStats { calcs: u32, calc_us_total: u32, calc_us_max: u32, + wait_us_total: u32, } /// Read one page of performance counters. None if the firmware doesn't support it. @@ -610,6 +611,7 @@ fn get_stats(port: &mut Box) -> Option { calcs: page1[4], calc_us_total: page1[5], calc_us_max: page1[6], + wait_us_total: page1[7], }) } @@ -792,6 +794,12 @@ fn benchmark_cmd(serialdev: &str, duration: Duration, mode: BenchmarkMode) { 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 + ); } ///Increase the brightness with each pixel. From a65815111ea7c62ccbfa5ca78bcdc217f1b8b27a Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 03:11:36 +0800 Subject: [PATCH 28/48] inputmodule-control: Add idle mode to --benchmark Sends nothing for the duration and then reports the device stats, to measure how the firmware behaves when it's not in use, like how much of the time the CPU is asleep. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 24 +++++++++++++++--------- inputmodule-control/src/ledmatrix.rs | 2 ++ 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index dc2fd88f..5e3e1cde 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -689,6 +689,10 @@ fn benchmark_cmd(serialdev: &str, duration: Duration, mode: BenchmarkMode) { bytes += 3 + vals.len() as u32; cmds += 1; } + BenchmarkMode::Idle => { + thread::sleep(duration); + break; + } } frames += 1; } @@ -715,15 +719,17 @@ fn benchmark_cmd(serialdev: &str, duration: Duration, mode: BenchmarkMode) { write_times.sort(); let write_total: Duration = write_times.iter().sum(); - 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().max(1) as u128, - percentile(50), - percentile(99), - percentile(100), - write_total.as_secs_f64() / elapsed * 100.0 - ); + 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; diff --git a/inputmodule-control/src/ledmatrix.rs b/inputmodule-control/src/ledmatrix.rs index 81cf66a8..d2586e20 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -30,6 +30,8 @@ pub enum BenchmarkMode { 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)] From f01202bb1565138641c443c4516fae7f8e410a55 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 03:15:16 +0800 Subject: [PATCH 29/48] ledmatrix: Sleep the CPU between main loop iterations Instead of busy polling, wait with WFE until the next timer deadline (animation frame, display refresh, game step or sleep timeout), at most 10ms so the SLEEP# pin and DIP switch are still checked often enough. SEVONPEND makes pending interrupts wake the CPU even though none are enabled in the NVIC, so no interrupt handlers are needed. USB activity and a timer alarm for the deadline wake it up. Both interrupts are level triggered, so clearing them before WFE can't lose an event. Idle benchmark: CPU asleep 0% -> 99%, 252k -> 127 loops per second. Greyscale benchmark: 187 -> 185.6 FPS, black and white 255 -> 254 FPS. Co-Authored-By: Claude Opus 5.5 --- ledmatrix/src/main.rs | 53 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index 8c850132..b058c2eb 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -4,6 +4,7 @@ #![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}; @@ -39,6 +40,11 @@ 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 10ms at a time, so the SLEEP# pin and DIP switch are still checked often enough +const MAX_WAIT_US: u64 = 10_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; @@ -130,11 +136,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; @@ -194,7 +201,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( @@ -591,6 +606,40 @@ fn main() -> ! { 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(animation_timer + state.animation_period) + .min(refresh_timer + DISPLAY_REFRESH_PERIOD); + } + if !state.debug_mode { + deadline = deadline.min(sleep_timer + SLEEP_TIMEOUT); + } + let wait = deadline.saturating_sub(now); + 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); + // 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) + { + cortex_m::asm::wfe(); + } + let 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; display.stats.loop_us_max = display.stats.loop_us_max.max(loop_us); display.stats.loops = display.stats.loops.wrapping_add(1); From bf88a694f7848ec91ab0811cc111e98dc30527aa Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 03:17:22 +0800 Subject: [PATCH 30/48] ledmatrix: Only wake up for animation frames while animating Without an animation, the display only changes through commands and games, so the 32 FPS animation tick just recalculated the same PWM values. Skip it and don't wake up for it. Games now flush right after each step instead of waiting for the next animation tick. The startup animation never cleared upcoming_frames when it was over, so it would have kept the tick running forever. Idle benchmark: 127 -> 100 wakeups and 33 -> 3 PWM calculations per second. Co-Authored-By: Claude Opus 5.5 --- ledmatrix/src/main.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index b058c2eb..978e952e 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -415,14 +415,18 @@ fn main() -> ! { ); // 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; } } @@ -603,6 +607,9 @@ fn main() -> ! { } None => {} } + if matches!(state.sleeping, SleepState::Awake) { + display.flush_if_dirty(&state); + } game_timer = timer.get_counter().ticks(); } @@ -611,9 +618,10 @@ fn main() -> ! { 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(animation_timer + state.animation_period) - .min(refresh_timer + DISPLAY_REFRESH_PERIOD); + 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); From 4e91e063000a75442658c402ea20bbd48364eef4 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 03:18:30 +0800 Subject: [PATCH 31/48] ledmatrix: Wake up on SLEEP# pin changes instead of polling it Enable edge interrupts on the SLEEP# pin, so the CPU wakes up as soon as the host goes to sleep or wakes up. Then the main loop only needs to wake up periodically for the DIP switch, so sleep up to 100ms at a time instead of 10ms. The edge flags are cleared right before reading the pin, so a change after reading it still wakes the CPU. Idle benchmark: 100 -> 10 wakeups per second. Greyscale 189.6 FPS, black and white 255.5 FPS, unchanged. Co-Authored-By: Claude Opus 5.5 --- ledmatrix/src/main.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index 978e952e..6b48747d 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -40,8 +40,9 @@ 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 10ms at a time, so the SLEEP# pin and DIP switch are still checked often enough -const MAX_WAIT_US: u64 = 10_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; @@ -338,6 +339,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; @@ -353,6 +359,9 @@ fn main() -> ! { 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; @@ -634,6 +643,7 @@ fn main() -> ! { // 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(); @@ -641,6 +651,7 @@ fn main() -> ! { // 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(); } From 337ff359af329018f83a5e61ada984c496f3bd6a Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 03:18:59 +0800 Subject: [PATCH 32/48] ledmatrix: Don't count sleeping towards the longest main loop Since the main loop sleeps, loop_us_max was always close to the longest wait, hiding how long the actual work took. Subtract the wait. Co-Authored-By: Claude Opus 5.5 --- ledmatrix/src/main.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index 6b48747d..baa40f6d 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -636,6 +636,7 @@ fn main() -> ! { 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(); @@ -655,12 +656,13 @@ fn main() -> ! { { cortex_m::asm::wfe(); } - let wait_us = (timer.get_counter().ticks() - now) as u32; + 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; - display.stats.loop_us_max = display.stats.loop_us_max.max(loop_us); + // 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); From ba1e8ec69621df9dcd922883ecd03247d2fa0d04 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 03:21:05 +0800 Subject: [PATCH 33/48] ledmatrix: Let MatrixSync control the LED controller's SDB pin Move the LED enable pin into MatrixSync, so it can turn the controller on and off by itself. No change in behavior yet. Co-Authored-By: Claude Opus 5.5 --- fl16-inputmodules/src/matrix_sync.rs | 21 ++++++++++++++++--- ledmatrix/src/main.rs | 30 +++++++--------------------- 2 files changed, 25 insertions(+), 26 deletions(-) diff --git a/fl16-inputmodules/src/matrix_sync.rs b/fl16-inputmodules/src/matrix_sync.rs index 9630c61d..748f0e65 100644 --- a/fl16-inputmodules/src/matrix_sync.rs +++ b/fl16-inputmodules/src/matrix_sync.rs @@ -2,11 +2,12 @@ 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}, - FunctionI2C, PullUp, + bank0::{Gpio26, Gpio27, Gpio29}, + FunctionI2C, FunctionSioOutput, Pin, PullDown, PullUp, }, pac::I2C1, Timer, @@ -22,6 +23,9 @@ pub type Foo = LedMatrix< >, >; +/// 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; @@ -112,6 +116,7 @@ impl Stats { pub struct MatrixSync { matrix: Foo, + led_enable: LedEnable, /// 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. @@ -122,7 +127,7 @@ pub struct MatrixSync { } impl MatrixSync { - pub fn new(matrix: Foo, timer: Timer) -> Self { + 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() { @@ -132,6 +137,7 @@ impl MatrixSync { } Self { matrix, + led_enable, sent: None, pwm_index, timer, @@ -167,6 +173,15 @@ impl MatrixSync { self.flush_if_dirty(state); } + /// Turn the LED controller on or off + pub fn set_powered(&mut self, powered: bool) { + if powered { + self.led_enable.set_high().unwrap(); + } else { + self.led_enable.set_low().unwrap(); + } + } + pub fn set_pwm_freq(&mut self, freq: PwmFreqArg) { self.matrix.device.set_pwm_freq(freq.into()).unwrap(); } diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index baa40f6d..558dba39 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -9,10 +9,7 @@ use cortex_m::peripheral::NVIC; 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 _; @@ -110,7 +107,7 @@ const MAX_BRIGHTNESS: u8 = 50; // .setup(&mut delay) // .expect("failed to setup rgb controller"); // -// let mut display = MatrixSync::new(matrix, timer); +// let mut display = MatrixSync::new(matrix, led_enable, timer); // state.brightness = 255; // state.grid = display_panic(); // display.force_flush(state); @@ -318,7 +315,7 @@ fn main() -> ! { .set_scaling(MAX_BRIGHTNESS) .expect("failed to set scaling"); - let mut display = MatrixSync::new(matrix, timer); + let mut display = MatrixSync::new(matrix, led_enable, timer); display.set_pwm_freq(state.pwm_freq); display.flush_if_dirty(&state); @@ -415,13 +412,7 @@ fn main() -> ! { sleep_timer = timer.get_counter().ticks(); } - handle_sleep( - sleep_reason, - &mut state, - &mut display, - &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, @@ -518,13 +509,7 @@ fn main() -> ! { SleepState::Sleeping((grid.clone(), new_brightness)); } } - handle_sleep( - sleep_reason, - &mut state, - &mut display, - &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; @@ -721,7 +706,6 @@ fn handle_sleep( state: &mut LedmatrixState, display: &mut MatrixSync, delay: &mut Delay, - led_enable: &mut gpio::Pin, ) { match (state.sleeping.clone(), sleep_reason) { // Awake and staying awake @@ -747,7 +731,7 @@ fn handle_sleep( display.flush_if_dirty(state); } else { // Turn LED controller off to save power - led_enable.set_low().unwrap(); + display.set_powered(false); } // TODO: Set up SLEEP# pin as interrupt and wfi @@ -769,7 +753,7 @@ fn handle_sleep( // Power LED controller back on. Even in debug mode, because it // might have been turned off before debug mode was enabled. - led_enable.set_high().unwrap(); + display.set_powered(true); // Must be after powering on, the controller may not have accepted writes while off display.force_flush(state); From cb783354136e7e0c8b02a02428de1cb05e5a92ba Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 03:23:41 +0800 Subject: [PATCH 34/48] ledmatrix: Power the LED controller off while no LED is lit Previously it was only turned off when going to sleep, so a blank screen or brightness 0 kept it powered until the sleep timeout. Now MatrixSync pulls SDB low whenever all PWM values are zero and powers it back on, resending the whole frame, as soon as an LED is lit again. While off, nothing is sent over I2C, including the periodic refresh. Setting the PWM frequency powers it on first, in case it doesn't accept writes while off. Add stats page 2 with how often the controller was powered on and how long it was off. Idle benchmark: blank grid or brightness 0 -> controller off 100% of the time, 0 I2C flushes. Lit -> on 100%. Greyscale 193.4 FPS, black and white 255.9 FPS, unchanged. Co-Authored-By: Claude Opus 5.5 --- fl16-inputmodules/src/control.rs | 2 +- fl16-inputmodules/src/matrix_sync.rs | 71 ++++++++++++++++++++++++++-- ledmatrix/src/main.rs | 7 ++- 3 files changed, 72 insertions(+), 8 deletions(-) diff --git a/fl16-inputmodules/src/control.rs b/fl16-inputmodules/src/control.rs index 56bb54d9..540ed773 100644 --- a/fl16-inputmodules/src/control.rs +++ b/fl16-inputmodules/src/control.rs @@ -643,7 +643,7 @@ pub fn handle_command( response[0] = state.debug_mode as u8; Some(response) } - Command::GetStats(page) => Some(display.stats.take_response(*page)), + Command::GetStats(page) => Some(display.take_stats(*page)), _ => handle_generic_command(command), } } diff --git a/fl16-inputmodules/src/matrix_sync.rs b/fl16-inputmodules/src/matrix_sync.rs index 748f0e65..42992818 100644 --- a/fl16-inputmodules/src/matrix_sync.rs +++ b/fl16-inputmodules/src/matrix_sync.rs @@ -67,6 +67,10 @@ pub struct Stats { 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 { @@ -104,6 +108,16 @@ impl Stats { 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]; @@ -117,6 +131,12 @@ impl Stats { 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. @@ -138,6 +158,10 @@ impl MatrixSync { 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, @@ -145,7 +169,8 @@ impl MatrixSync { } } - /// Fills the grid pixels but only sends the I2C commands if the PWM values changed + /// 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); @@ -154,6 +179,12 @@ impl MatrixSync { 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(); @@ -173,16 +204,50 @@ impl MatrixSync { self.flush_if_dirty(state); } - /// Turn the LED controller on or off - pub fn set_powered(&mut self, powered: bool) { + /// 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(); } } diff --git a/ledmatrix/src/main.rs b/ledmatrix/src/main.rs index 558dba39..75df4abe 100644 --- a/ledmatrix/src/main.rs +++ b/ledmatrix/src/main.rs @@ -731,7 +731,7 @@ fn handle_sleep( display.flush_if_dirty(state); } else { // Turn LED controller off to save power - display.set_powered(false); + display.set_enabled(false); } // TODO: Set up SLEEP# pin as interrupt and wfi @@ -751,10 +751,9 @@ fn handle_sleep( state.sleeping = SleepState::Awake; state.grid = old_grid; - // Power LED controller back on. Even in debug mode, because it + // 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_powered(true); - // Must be after powering on, the controller may not have accepted writes while off + display.set_enabled(true); display.force_flush(state); // Slowly increase brightness From 6436bcee061ae8654ae02af8607bc414838ebe52 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 10 Nov 2026 03:23:41 +0800 Subject: [PATCH 35/48] inputmodule-control: Show LED controller power stats in --benchmark Read stats page 2 and report how long the LED controller was off and how often it was powered on. Reading the extra page sends one more command, so subtract three instead of two requests from the counters. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index 5e3e1cde..04b4766d 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -574,6 +574,8 @@ struct DeviceStats { 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. @@ -591,10 +593,11 @@ fn get_stats_page(port: &mut Box, page: u8) -> Option<[u32; 8]> /// 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 two commands of 4 bytes each. +/// 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], @@ -612,6 +615,8 @@ fn get_stats(port: &mut Box) -> Option { 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], }) } @@ -735,10 +740,10 @@ fn benchmark_cmd(serialdev: &str, duration: Duration, mode: BenchmarkMode) { return; }; let delta = |f: fn(&DeviceStats) -> u32| f(&after).wrapping_sub(f(&before)); - // The second 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(8); - let cmds_parsed = delta(|s| s.cmds_parsed).wrapping_sub(2); + // 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); @@ -806,6 +811,13 @@ fn benchmark_cmd(serialdev: &str, duration: Duration, mode: BenchmarkMode) { "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. From ff4ffc760156d6fd3a59a8efbbaf1242d3a1016b Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 11 Nov 2026 00:51:58 +0800 Subject: [PATCH 36/48] inputmodule-control: Add falling-sand hourglass demo --demo hourglass shows an hourglass timer whose sand runs out after --demo-minutes. Each LED is split into 4x4 sand cells and lit by the share of them holding sand, so grains and slopes look much smoother than 9 pixels wide. A gate at the neck lets sand through just fast enough to empty the top chamber on time. When it's empty, the sand blinks, the glass flips over and the next timer starts. Several minutes cycle, like --demo-minutes 25 5 for Pomodoro. Runs at 60 FPS by default, the simulation rate, so a long timer doesn't stream as fast as possible. The new Vec argument trips clippy's large_enum_variant on Commands. It's parsed once at startup, so allow it. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 313 ++++++++++++++++++++++++- inputmodule-control/src/ledmatrix.rs | 7 + inputmodule-control/src/main.rs | 2 + 3 files changed, 319 insertions(+), 3 deletions(-) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index 04b4766d..b54c80e4 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -289,6 +289,7 @@ pub fn serial_commands(args: &crate::ClapCli) { &serialdevs, demo, &ledmatrix_args.demo_text, + &ledmatrix_args.demo_minutes, ledmatrix_args.fps, ); } @@ -1091,6 +1092,263 @@ impl ScrollingText { } } +/// 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_W: usize = WIDTH * SAND_SUB; +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.55; +/// 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 = [[bool; SAND_H]; SAND_W]; + +/// 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) -> 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; + let half_width = half.min(1 + to_neck).min(8 + 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: [[bool; HEIGHT]; WIDTH], + /// 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]) -> Self { + let mut glass = [[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); + } + } + + let mut edge = [[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().count() / 2; + let mut sand = [[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, + 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; + 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 = 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 = 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 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 = [[0; HEIGHT]; WIDTH]; + for x in 0..WIDTH { + 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 + } +} + /// Open ports for streaming frames and wake up the LED matrices fn open_stream_ports(serialdevs: &[String]) -> Vec> { serialdevs @@ -1123,6 +1381,8 @@ struct FpsReporter { start: Option, /// Frames sent since then frames: u64, + /// Shown after the frame rate + status: String, } impl FpsReporter { @@ -1130,6 +1390,7 @@ impl FpsReporter { Self { start: None, frames: 0, + status: String::new(), } } @@ -1142,7 +1403,7 @@ impl FpsReporter { 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); + 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; @@ -1309,12 +1570,18 @@ fn ffmpeg_stream(serialdevs: &[String], input: &[&str], fps: Option, frame_ println!(); } -/// Run a greyscale demo forever, as fast as possible or limited to fps -fn demo_cmd(serialdevs: &[String], demo: Demo, text: &str, fps: Option) { +/// 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], demo: Demo, text: &str, minutes: &[f32], fps: Option) { let mut ports = open_stream_ports(serialdevs); let mut fire = Fire::new(); let scrolling_text = ScrollingText::new(text); + let mut hourglass = Hourglass::new(minutes); + 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; @@ -1325,6 +1592,11 @@ fn demo_cmd(serialdevs: &[String], demo: Demo, text: &str, fps: Option) { Demo::Plasma => plasma_frame(t), Demo::Fire => fire.frame(t), Demo::Text => scrolling_text.frame(t), + Demo::Hourglass => { + let grid = hourglass.frame(t); + reporter.status = hourglass.status(t); + grid + } }; send_grey_frame(&mut ports, &grid); frames += 1; @@ -1856,3 +2128,38 @@ 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() { + for minutes in [0.5, 2.0] { + let mut hourglass = Hourglass::new(&[minutes, 0.25]); + 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 ran out after {:.1}s", minutes, 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 d2586e20..0c02f86d 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -42,6 +42,8 @@ pub enum Demo { 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)] @@ -175,6 +177,11 @@ pub struct LedMatrixSubcommand { #[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, diff --git a/inputmodule-control/src/main.rs b/inputmodule-control/src/main.rs index 8348ad74..47f2ed3b 100644 --- a/inputmodule-control/src/main.rs +++ b/inputmodule-control/src/main.rs @@ -14,6 +14,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), From 24d59c727d6b3c9280e8dcb18c8063ed6ab1c856 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 11 Nov 2026 01:02:10 +0800 Subject: [PATCH 37/48] inputmodule-control: Add brick breaker game --bricks plays a brick breaker game on the host and streams it to the LED matrix. Ball, paddle and bricks aren't rounded to whole LEDs, each LED lights up by how much of it they cover, so the ball glides at any angle. Uncapped frame rate by default, the physics run at a fixed 480 steps per second. Steer with the mouse across the terminal for sub-pixel positioning, or with the arrow keys. Keys can be held in terminals that report key releases (kitty protocol, Windows), elsewhere every press or key repeat moves by one LED. Uses crossterm for raw terminal input. Every level adds a row of bricks and from level 2 the top rows take two hits. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 177 ++++++- inputmodule-control/Cargo.toml | 1 + inputmodule-control/src/bricks.rs | 629 +++++++++++++++++++++++++ inputmodule-control/src/inputmodule.rs | 14 +- inputmodule-control/src/ledmatrix.rs | 8 +- inputmodule-control/src/main.rs | 1 + 6 files changed, 818 insertions(+), 12 deletions(-) create mode 100644 inputmodule-control/src/bricks.rs diff --git a/Cargo.lock b/Cargo.lock index 9a7bd7b6..efb17d5d 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" @@ -1065,6 +1142,7 @@ version = "0.2.0" dependencies = [ "chrono", "clap", + "crossterm", "image", "rand 0.8.5", "serialport", @@ -1203,9 +1281,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 +1315,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 +1403,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 +1675,7 @@ checksum = "94c8c7923936b28d546dfd14d4472eaf34c99b14e1c973a32b3e6d4eb04298c9" dependencies = [ "libc", "rand 0.6.5", - "rustc_version", + "rustc_version 0.2.3", "smallvec 0.6.14", "winapi", ] @@ -2059,7 +2161,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 +2187,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 +2236,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 +2303,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 +2603,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/inputmodule-control/Cargo.toml b/inputmodule-control/Cargo.toml index 27be7699..41576eab 100644 --- a/inputmodule-control/Cargo.toml +++ b/inputmodule-control/Cargo.toml @@ -18,6 +18,7 @@ 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" [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..b386fb71 --- /dev/null +++ b/inputmodule-control/src/bricks.rs @@ -0,0 +1,629 @@ +//! Brick breaker game, played on the host and streamed to the LED matrix. +//! +//! Positions are in LEDs, but not rounded to whole LEDs. Each LED lights up by how +//! much of it the ball, paddle or bricks cover, so they glide smoothly instead of +//! jumping from LED to LED. The higher the frame rate, the smoother it looks. + +use std::collections::VecDeque; +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::prelude::*; + +use crate::inputmodule::{open_stream_ports, send_grey_frame, GreyGrid, HEIGHT, WIDTH}; + +const FIELD_W: f32 = WIDTH as f32; +const FIELD_H: f32 = HEIGHT as f32; + +/// 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, +} + +/// What the player wants, collected from terminal events +#[derive(Default)] +struct Input { + /// Where the paddle should go, from the mouse or arrow key presses + target: Option, + /// Arrow keys currently held, only known if the terminal reports key releases + held_left: bool, + held_right: bool, + launch: bool, + quit: bool, +} + +struct Game { + rng: ThreadRng, + 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() -> Self { + let mut game = Self { + rng: thread_rng(), + state: State::Serving { since: 0.0 }, + level: 1, + score: 0, + balls: BALLS, + bricks: vec![], + paddle_x: FIELD_W / 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); + self.bricks = (0..rows) + .flat_map(|row| { + (0..WIDTH / BRICK_WIDTH).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 move_paddle(&mut self, input: &mut Input, dt: f32) { + let held = input.held_right as i32 - input.held_left as i32; + if held != 0 { + self.paddle_x += held as f32 * PADDLE_KEY_SPEED * dt; + input.target = None; + } else if let Some(target) = input.target { + let max_step = PADDLE_MAX_SPEED * dt; + self.paddle_x += (target - self.paddle_x).clamp(-max_step, max_step); + } + let half = PADDLE_WIDTH / 2.0; + self.paddle_x = self.paddle_x.clamp(half, FIELD_W - half); + } + + fn update(&mut self, input: &mut Input, now: f32, dt: f32) { + self.move_paddle(input, dt); + match self.state { + State::Serving { since } => { + self.ball_x = self.paddle_x; + self.ball_y = PADDLE_Y - BALL_RADIUS; + if input.launch || 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.launch { + self.restart(now); + } + } + } + input.launch = false; + } + + 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 > FIELD_W { + self.ball_x = FIELD_W - 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 }; + } + } + + fn render(&self, now: f32) -> GreyGrid { + let mut light = [[0.0f32; HEIGHT]; WIDTH]; + + 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_ball(&mut light, x, y, brightness); + } + } + add_ball(&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[WIDTH - 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), (FIELD_W, y + 2.0), 0.8); + } + + let dim = if self.state == State::GameOver { + 0.25 + } else { + 1.0 + }; + let mut grid = [[0; HEIGHT]; WIDTH]; + for x in 0..WIDTH { + for y in 0..HEIGHT { + // Linear instead of gamma, so the total light stays the same while moving + grid[x][y] = (light[x][y].min(1.0) * dim * 255.0) as u8; + } + } + grid + } + + 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 + ) + } +} + +/// Light up the LEDs by how much of them the rectangle covers +fn add_rect( + light: &mut [[f32; HEIGHT]; WIDTH], + (x0, y0): (f32, f32), + (x1, y1): (f32, f32), + brightness: f32, +) { + let cols = (x0.floor().max(0.0) as usize)..(x1.ceil().min(FIELD_W) 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; + } + } +} + +fn add_ball(light: &mut [[f32; HEIGHT]; WIDTH], x: f32, y: f32, brightness: f32) { + let r = BALL_RADIUS; + add_rect(light, (x - r, y - r), (x + r, y + r), brightness); +} + +/// 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 +fn read_input(input: &mut Input, key_releases: bool, paddle_x: f32) -> std::io::Result<()> { + while event::poll(Duration::ZERO)? { + match event::read()? { + Event::Key(key) => { + let pressed = key.kind != KeyEventKind::Release; + 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(paddle_x); + input.target = Some(from + dir); + } + } else if pressed { + match key.code { + KeyCode::Char(' ') | KeyCode::Up | KeyCode::Enter => input.launch = 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 LED matrix + let (cols, _) = terminal::size()?; + let x = (mouse.column as f32 + 0.5) / cols.max(1) as f32 * FIELD_W; + match mouse.kind { + MouseEventKind::Moved | MouseEventKind::Drag(_) => input.target = Some(x), + MouseEventKind::Down(MouseButton::Left) => input.launch = true, + _ => {} + } + } + _ => {} + } + } + Ok(()) +} + +/// Play until the player quits, as fast as possible or limited to fps +pub fn bricks_cmd(serialdevs: &[String], fps: Option) { + let mut ports = open_stream_ports(serialdevs); + println!("Steer with the arrow keys, or move the mouse across this terminal."); + println!("Space or a click launches the ball. Q or Esc quits."); + + let term = RawTerminal::new().expect("Failed to set up the terminal"); + let mut input = Input::default(); + let mut game = Game::new(); + + 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.paddle_x).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); + send_grey_frame(&mut ports, &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 + send_grey_frame(&mut ports, &[[0; HEIGHT]; WIDTH]); + drop(term); + println!("{}", game.status(measured_fps)); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Ball that the paddle always catches clears the level and never gets stuck + #[test] + fn autoplay_clears_level() { + let mut game = Game::new(); + let mut input = Input::default(); + let dt = 1.0 / 120.0; + let mut now = 0.0; + while game.level == 1 { + input.target = Some(game.ball_x + 0.4); + input.launch = 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); + } + + #[test] + fn rect_covers_partial_leds() { + let mut light = [[0.0f32; HEIGHT]; WIDTH]; + add_ball(&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 b54c80e4..0826642f 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -63,8 +63,8 @@ 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); @@ -284,6 +284,10 @@ pub fn serial_commands(args: &crate::ClapCli) { camera_cmd(&serialdevs, device.as_deref(), ledmatrix_args.fps); } + if ledmatrix_args.bricks { + crate::bricks::bricks_cmd(&serialdevs, ledmatrix_args.fps); + } + if let Some(demo) = ledmatrix_args.demo { demo_cmd( &serialdevs, @@ -955,7 +959,7 @@ fn display_gray_image_cmd(serialdev: &str, image_path: &str) { commit_cols(&mut port); } -type GreyGrid = [[u8; HEIGHT]; WIDTH]; +pub type GreyGrid = [[u8; HEIGHT]; WIDTH]; /// Make dim values dimmer, so the LEDs show more contrast fn gamma(brightness: f32) -> u8 { @@ -1350,7 +1354,7 @@ impl Hourglass { } /// Open ports for streaming frames and wake up the LED matrices -fn open_stream_ports(serialdevs: &[String]) -> Vec> { +pub fn open_stream_ports(serialdevs: &[String]) -> Vec> { serialdevs .iter() .map(|serialdev| { @@ -1366,7 +1370,7 @@ fn open_stream_ports(serialdevs: &[String]) -> Vec> { } /// Send a greyscale frame to every port -fn send_grey_frame(ports: &mut [Box], grid: &GreyGrid) { +pub fn send_grey_frame(ports: &mut [Box], grid: &GreyGrid) { for port in ports { for (x, col) in grid.iter().enumerate() { send_col(port, x as u8, col); diff --git a/inputmodule-control/src/ledmatrix.rs b/inputmodule-control/src/ledmatrix.rs index 0c02f86d..5d114683 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -191,8 +191,12 @@ pub struct LedMatrixSubcommand { #[arg(long)] pub camera: Option>, - /// Limit --demo, --video or --camera to this many frames per second. - /// Uncapped for --demo, the video's frame rate for --video + /// Play a brick breaker game, with the arrow keys or the mouse in the terminal + #[arg(long)] + pub bricks: bool, + + /// Limit --demo, --bricks, --video or --camera to this many frames per second. + /// Uncapped for --demo and --bricks, the video's frame rate for --video /// and the camera's frame rate for --camera by default #[arg(long)] pub fps: Option, diff --git a/inputmodule-control/src/main.rs b/inputmodule-control/src/main.rs index 47f2ed3b..3fa9b70a 100644 --- a/inputmodule-control/src/main.rs +++ b/inputmodule-control/src/main.rs @@ -1,6 +1,7 @@ #![allow(clippy::needless_range_loop)] #![allow(clippy::single_match)] mod b1display; +mod bricks; mod c1minimal; mod font; mod inputmodule; From 699ebf4571a73c3c0b0941615fd5f155fd93423a Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 11 Nov 2026 01:05:27 +0800 Subject: [PATCH 38/48] inputmodule-control: Move shared host game code out of bricks Drawing by area, terminal input and the frame loop go to hostgame.rs, behind a small HostGame trait, so more games can use them. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/bricks.rs | 335 ++++++---------------------- inputmodule-control/src/hostgame.rs | 248 ++++++++++++++++++++ inputmodule-control/src/main.rs | 1 + 3 files changed, 318 insertions(+), 266 deletions(-) create mode 100644 inputmodule-control/src/hostgame.rs diff --git a/inputmodule-control/src/bricks.rs b/inputmodule-control/src/bricks.rs index b386fb71..668a8ad3 100644 --- a/inputmodule-control/src/bricks.rs +++ b/inputmodule-control/src/bricks.rs @@ -1,25 +1,13 @@ -//! Brick breaker game, played on the host and streamed to the LED matrix. -//! -//! Positions are in LEDs, but not rounded to whole LEDs. Each LED lights up by how -//! much of it the ball, paddle or bricks cover, so they glide smoothly instead of -//! jumping from LED to LED. The higher the frame rate, the smoother it looks. +//! Brick breaker game, played on the host and streamed to the LED matrix use std::collections::VecDeque; -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::prelude::*; -use crate::inputmodule::{open_stream_ports, send_grey_frame, GreyGrid, HEIGHT, WIDTH}; - -const FIELD_W: f32 = WIDTH as f32; -const FIELD_H: f32 = HEIGHT as f32; +use crate::hostgame::{ + add_rect, add_square, play, to_grid, HostGame, Input, Light, FIELD_H, FIELD_W, +}; +use crate::inputmodule::{GreyGrid, HEIGHT, WIDTH}; /// Physics steps per second, independent of the frame rate. /// Small enough steps that even the fastest ball can't skip through a brick. @@ -100,18 +88,6 @@ enum State { GameOver, } -/// What the player wants, collected from terminal events -#[derive(Default)] -struct Input { - /// Where the paddle should go, from the mouse or arrow key presses - target: Option, - /// Arrow keys currently held, only known if the terminal reports key releases - held_left: bool, - held_right: bool, - launch: bool, - quit: bool, -} - struct Game { rng: ThreadRng, state: State, @@ -190,64 +166,6 @@ impl Game { self.serve(now); } - fn move_paddle(&mut self, input: &mut Input, dt: f32) { - let held = input.held_right as i32 - input.held_left as i32; - if held != 0 { - self.paddle_x += held as f32 * PADDLE_KEY_SPEED * dt; - input.target = None; - } else if let Some(target) = input.target { - let max_step = PADDLE_MAX_SPEED * dt; - self.paddle_x += (target - self.paddle_x).clamp(-max_step, max_step); - } - let half = PADDLE_WIDTH / 2.0; - self.paddle_x = self.paddle_x.clamp(half, FIELD_W - half); - } - - fn update(&mut self, input: &mut Input, now: f32, dt: f32) { - self.move_paddle(input, dt); - match self.state { - State::Serving { since } => { - self.ball_x = self.paddle_x; - self.ball_y = PADDLE_Y - BALL_RADIUS; - if input.launch || 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.launch { - self.restart(now); - } - } - } - input.launch = false; - } - fn step_ball(&mut self, dt: f32, now: f32) { self.ball_x += self.vel_x * dt; self.ball_y += self.vel_y * dt; @@ -334,9 +252,62 @@ impl Game { 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, FIELD_W - 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 = [[0.0f32; HEIGHT]; WIDTH]; + let mut light: Light = [[0.0; HEIGHT]; WIDTH]; for brick in &self.bricks { let since_hit = brick.hit_at.map_or(f32::MAX, |t| now - t); @@ -382,10 +353,10 @@ impl Game { for &(ago, brightness) in &TRAIL { if let Some(&(_, x, y)) = self.trail.iter().rev().find(|&&(t, _, _)| now - t >= ago) { - add_ball(&mut light, x, y, brightness); + add_square(&mut light, x, y, brightness); } } - add_ball(&mut light, self.ball_x, self.ball_y, 1.0); + add_square(&mut light, self.ball_x, self.ball_y, 1.0); } // Spare balls as dim dots in the bottom right corner @@ -408,14 +379,7 @@ impl Game { } else { 1.0 }; - let mut grid = [[0; HEIGHT]; WIDTH]; - for x in 0..WIDTH { - for y in 0..HEIGHT { - // Linear instead of gamma, so the total light stays the same while moving - grid[x][y] = (light[x][y].min(1.0) * dim * 255.0) as u8; - } - } - grid + to_grid(&light, dim) } fn status(&self, fps: f64) -> String { @@ -433,165 +397,14 @@ impl Game { } } -/// Light up the LEDs by how much of them the rectangle covers -fn add_rect( - light: &mut [[f32; HEIGHT]; WIDTH], - (x0, y0): (f32, f32), - (x1, y1): (f32, f32), - brightness: f32, -) { - let cols = (x0.floor().max(0.0) as usize)..(x1.ceil().min(FIELD_W) 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; - } - } -} - -fn add_ball(light: &mut [[f32; HEIGHT]; WIDTH], x: f32, y: f32, brightness: f32) { - let r = BALL_RADIUS; - add_rect(light, (x - r, y - r), (x + r, y + r), brightness); -} - -/// 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 -fn read_input(input: &mut Input, key_releases: bool, paddle_x: f32) -> std::io::Result<()> { - while event::poll(Duration::ZERO)? { - match event::read()? { - Event::Key(key) => { - let pressed = key.kind != KeyEventKind::Release; - 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(paddle_x); - input.target = Some(from + dir); - } - } else if pressed { - match key.code { - KeyCode::Char(' ') | KeyCode::Up | KeyCode::Enter => input.launch = 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 LED matrix - let (cols, _) = terminal::size()?; - let x = (mouse.column as f32 + 0.5) / cols.max(1) as f32 * FIELD_W; - match mouse.kind { - MouseEventKind::Moved | MouseEventKind::Drag(_) => input.target = Some(x), - MouseEventKind::Down(MouseButton::Left) => input.launch = true, - _ => {} - } - } - _ => {} - } - } - Ok(()) -} - /// Play until the player quits, as fast as possible or limited to fps pub fn bricks_cmd(serialdevs: &[String], fps: Option) { - let mut ports = open_stream_ports(serialdevs); - println!("Steer with the arrow keys, or move the mouse across this terminal."); - println!("Space or a click launches the ball. Q or Esc quits."); - - let term = RawTerminal::new().expect("Failed to set up the terminal"); - let mut input = Input::default(); - let mut game = Game::new(); - - 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.paddle_x).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); - send_grey_frame(&mut ports, &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 - send_grey_frame(&mut ports, &[[0; HEIGHT]; WIDTH]); - drop(term); - println!("{}", game.status(measured_fps)); + play( + serialdevs, + fps, + "Space or a click launches the ball.", + &mut Game::new(), + ); } #[cfg(test)] @@ -607,7 +420,7 @@ mod tests { let mut now = 0.0; while game.level == 1 { input.target = Some(game.ball_x + 0.4); - input.launch = true; + input.action = true; now += dt; game.update(&mut input, now, dt); game.render(now); @@ -616,14 +429,4 @@ mod tests { } println!("Cleared level 1 in {:.1}s, score {}", now, game.score); } - - #[test] - fn rect_covers_partial_leds() { - let mut light = [[0.0f32; HEIGHT]; WIDTH]; - add_ball(&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/hostgame.rs b/inputmodule-control/src/hostgame.rs new file mode 100644 index 00000000..56c99c02 --- /dev/null +++ b/inputmodule-control/src/hostgame.rs @@ -0,0 +1,248 @@ +//! 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 crate::inputmodule::{open_stream_ports, send_grey_frame, GreyGrid, HEIGHT, WIDTH}; + +pub const FIELD_W: f32 = WIDTH as f32; +pub const FIELD_H: f32 = HEIGHT as f32; + +/// Brightness of each LED, 1.0 is fully on. Adds up where shapes overlap. +pub type Light = [[f32; 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(FIELD_W) 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); +} + +/// Convert to a frame for the LED matrix, scaling everything by dim +pub fn to_grid(light: &Light, dim: f32) -> GreyGrid { + let mut grid = [[0; HEIGHT]; WIDTH]; + for x in 0..WIDTH { + for y in 0..HEIGHT { + // Linear instead of gamma, so the total light stays the same while moving + grid[x][y] = (light[x][y].clamp(0.0, 1.0) * dim * 255.0) as u8; + } + } + grid +} + +/// 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, + 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 +fn read_input(input: &mut Input, key_releases: bool, player_x: f32) -> std::io::Result<()> { + while event::poll(Duration::ZERO)? { + match event::read()? { + Event::Key(key) => { + let pressed = key.kind != KeyEventKind::Release; + 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 LED matrix + let (cols, _) = terminal::size()?; + let x = (mouse.column as f32 + 0.5) / cols.max(1) as f32 * FIELD_W; + 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 +pub fn play(serialdevs: &[String], fps: Option, help: &str, game: &mut impl HostGame) { + let mut ports = open_stream_ports(serialdevs); + println!("Steer with the arrow keys, or move the mouse across this terminal."); + 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()).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; + send_grey_frame(&mut ports, &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 + send_grey_frame(&mut ports, &[[0; HEIGHT]; WIDTH]); + drop(term); + println!("{}", game.status(measured_fps)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn square_covers_partial_leds() { + let mut light = [[0.0f32; HEIGHT]; 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/main.rs b/inputmodule-control/src/main.rs index 3fa9b70a..c5bc20e4 100644 --- a/inputmodule-control/src/main.rs +++ b/inputmodule-control/src/main.rs @@ -4,6 +4,7 @@ mod b1display; mod bricks; mod c1minimal; mod font; +mod hostgame; mod inputmodule; mod ledmatrix; From 69277578a41aaff186c8b38931ab5dad48d2a46b Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 11 Nov 2026 01:07:01 +0800 Subject: [PATCH 39/48] inputmodule-control: Add cave descent game --cave falls down an endless winding cave, steered with the mouse or arrow keys like --bricks. The cave scrolls by fractions of an LED and its walls are drawn by area, so it flows smoothly at high frame rates. It gets faster and narrower the deeper it goes, but never curves steeper than the player can follow with the arrow keys at the current speed. Gems along the way are worth extra points. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/cave.rs | 413 +++++++++++++++++++++++++ inputmodule-control/src/inputmodule.rs | 4 + inputmodule-control/src/ledmatrix.rs | 8 +- inputmodule-control/src/main.rs | 1 + 4 files changed, 424 insertions(+), 2 deletions(-) create mode 100644 inputmodule-control/src/cave.rs diff --git a/inputmodule-control/src/cave.rs b/inputmodule-control/src/cave.rs new file mode 100644 index 00000000..9297bb1e --- /dev/null +++ b/inputmodule-control/src/cave.rs @@ -0,0 +1,413 @@ +//! 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, play, to_grid, HostGame, Input, Light, FIELD_W}; +use crate::inputmodule::{GreyGrid, HEIGHT, WIDTH}; + +/// 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; +const SPARKS: usize = 14; + +struct Segment { + depth: f32, + center: f32, + half_width: f32, +} + +struct Gem { + depth: f32, + x: f32, + taken_at: Option, +} + +/// Flies away from where the player crashed +struct Spark { + vel_x: f32, + vel_y: f32, +} + +#[derive(Clone, Copy, PartialEq)] +enum State { + /// Waiting for the player to start + Ready, + Falling, + Crashed { + since: f32, + }, +} + +struct Game { + rng: ThreadRng, + 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, + sparks: Vec, + /// Recent player positions with the time, for the trail. Newest last. + trail: VecDeque<(f32, f32)>, +} + +impl Game { + fn new() -> Self { + let mut game = Self { + rng: thread_rng(), + state: State::Ready, + depth: 0.0, + speed: START_SPEED, + player_x: FIELD_W / 2.0, + segments: VecDeque::new(), + gems: VecDeque::new(), + gems_taken: 0, + best: 0, + sparks: vec![], + 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 = FIELD_W / 2.0; + self.segments.clear(); + self.gems.clear(); + self.gems_taken = 0; + self.trail.clear(); + self.segments.push_back(Segment { + depth: -SEGMENT, + center: FIELD_W / 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 { + FIELD_W / 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, FIELD_W - 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.sparks = (0..SPARKS) + .map(|i| { + let angle = i as f32 / SPARKS as f32 * 2.0 * PI + self.rng.gen_range(0.0..0.4); + let speed = self.rng.gen_range(3.0..10.0); + Spark { + vel_x: speed * angle.cos(), + vel_y: speed * angle.sin(), + } + }) + .collect(); + } + } +} + +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, FIELD_W - 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 = [[0.0; HEIGHT]; WIDTH]; + + // 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 } => { + let age = (now - since).min(CRASH_SECS); + let fade = 1.0 - age / CRASH_SECS; + for spark in &self.sparks { + let x = self.player_x + spark.vel_x * age; + let y = PLAYER_Y + spark.vel_y * age; + add_square(&mut light, x, y, 0.8 * fade); + } + } + _ => { + // 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], fps: Option) { + play( + serialdevs, + fps, + "Space or a click starts.", + &mut Game::new(), + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Following the middle of the cave gets through, even at full speed and width + #[test] + fn autoplay_survives() { + let mut game = Game::new(); + 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 <= FIELD_W + 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/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index 0826642f..cc200ebd 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -288,6 +288,10 @@ pub fn serial_commands(args: &crate::ClapCli) { crate::bricks::bricks_cmd(&serialdevs, ledmatrix_args.fps); } + if ledmatrix_args.cave { + crate::cave::cave_cmd(&serialdevs, ledmatrix_args.fps); + } + if let Some(demo) = ledmatrix_args.demo { demo_cmd( &serialdevs, diff --git a/inputmodule-control/src/ledmatrix.rs b/inputmodule-control/src/ledmatrix.rs index 5d114683..35c14402 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -195,8 +195,12 @@ pub struct LedMatrixSubcommand { #[arg(long)] pub bricks: bool, - /// Limit --demo, --bricks, --video or --camera to this many frames per second. - /// Uncapped for --demo and --bricks, the video's frame rate for --video + /// Play a cave descent game, with the arrow keys or the mouse in the terminal + #[arg(long)] + pub cave: bool, + + /// Limit --demo, --bricks, --cave, --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, diff --git a/inputmodule-control/src/main.rs b/inputmodule-control/src/main.rs index c5bc20e4..077735dc 100644 --- a/inputmodule-control/src/main.rs +++ b/inputmodule-control/src/main.rs @@ -3,6 +3,7 @@ mod b1display; mod bricks; mod c1minimal; +mod cave; mod font; mod hostgame; mod inputmodule; From d027253c773ce9c4599922f96daff6ddb2a8565e Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 11 Nov 2026 01:12:27 +0800 Subject: [PATCH 40/48] inputmodule-control: Share crash sparks between host games Move the sparks from the cave game into hostgame.rs as Burst. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/cave.rs | 35 +++++++------------------- inputmodule-control/src/hostgame.rs | 39 +++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 26 deletions(-) diff --git a/inputmodule-control/src/cave.rs b/inputmodule-control/src/cave.rs index 9297bb1e..3e445b72 100644 --- a/inputmodule-control/src/cave.rs +++ b/inputmodule-control/src/cave.rs @@ -6,7 +6,9 @@ use std::f32::consts::PI; use rand::prelude::*; -use crate::hostgame::{add_rect, add_square, play, to_grid, HostGame, Input, Light, FIELD_W}; +use crate::hostgame::{ + add_rect, add_square, play, to_grid, Burst, HostGame, Input, Light, FIELD_W, +}; use crate::inputmodule::{GreyGrid, HEIGHT, WIDTH}; /// Physics steps per second, independent of the frame rate @@ -54,7 +56,6 @@ const GEM_SIZE: f32 = 0.7; const GEM_FADE_SECS: f32 = 0.25; const CRASH_SECS: f32 = 1.0; -const SPARKS: usize = 14; struct Segment { depth: f32, @@ -68,12 +69,6 @@ struct Gem { taken_at: Option, } -/// Flies away from where the player crashed -struct Spark { - vel_x: f32, - vel_y: f32, -} - #[derive(Clone, Copy, PartialEq)] enum State { /// Waiting for the player to start @@ -96,7 +91,8 @@ struct Game { gems: VecDeque, gems_taken: u32, best: u32, - sparks: Vec, + /// Where the player crashed + burst: Option, /// Recent player positions with the time, for the trail. Newest last. trail: VecDeque<(f32, f32)>, } @@ -113,7 +109,7 @@ impl Game { gems: VecDeque::new(), gems_taken: 0, best: 0, - sparks: vec![], + burst: None, trail: VecDeque::new(), }; game.restart(); @@ -221,16 +217,7 @@ impl Game { if self.crashed() { self.state = State::Crashed { since: now }; self.best = self.best.max(self.score()); - self.sparks = (0..SPARKS) - .map(|i| { - let angle = i as f32 / SPARKS as f32 * 2.0 * PI + self.rng.gen_range(0.0..0.4); - let speed = self.rng.gen_range(3.0..10.0); - Spark { - vel_x: speed * angle.cos(), - vel_y: speed * angle.sin(), - } - }) - .collect(); + self.burst = Some(Burst::new(&mut self.rng, self.player_x, PLAYER_Y)); } } } @@ -314,12 +301,8 @@ impl HostGame for Game { match self.state { State::Crashed { since } => { - let age = (now - since).min(CRASH_SECS); - let fade = 1.0 - age / CRASH_SECS; - for spark in &self.sparks { - let x = self.player_x + spark.vel_x * age; - let y = PLAYER_Y + spark.vel_y * age; - add_square(&mut light, x, y, 0.8 * fade); + if let Some(burst) = &self.burst { + burst.draw(&mut light, now - since, CRASH_SECS); } } _ => { diff --git a/inputmodule-control/src/hostgame.rs b/inputmodule-control/src/hostgame.rs index 56c99c02..7ebe74f9 100644 --- a/inputmodule-control/src/hostgame.rs +++ b/inputmodule-control/src/hostgame.rs @@ -14,6 +14,7 @@ use crossterm::event::{ PushKeyboardEnhancementFlags, }; use crossterm::{cursor, execute, terminal}; +use rand::Rng; use crate::inputmodule::{open_stream_ports, send_grey_frame, GreyGrid, HEIGHT, WIDTH}; @@ -41,6 +42,44 @@ 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 +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 { let mut grid = [[0; HEIGHT]; WIDTH]; From aebac2554cbd12aa4ca0b44c59f10f5fd2f4e5b6 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 11 Nov 2026 01:18:06 +0800 Subject: [PATCH 41/48] inputmodule-control: Add one-button flying game --flap: flap with space, up or a click to stay in the air and fly through the gaps in the walls that slide in from the right. Gravity pulls along the tall side of the matrix, so every flap is a long arc, and walls and player move by fractions of an LED. Every wall passed makes it a bit faster and the gaps a bit smaller. The next gap is never higher than the player can climb in time, or much lower. A test plays with a player that looks one second ahead, to make sure the hardest walls can still be passed. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/flap.rs | 404 +++++++++++++++++++++++++ inputmodule-control/src/hostgame.rs | 1 + inputmodule-control/src/inputmodule.rs | 4 + inputmodule-control/src/ledmatrix.rs | 6 +- inputmodule-control/src/main.rs | 1 + 5 files changed, 415 insertions(+), 1 deletion(-) create mode 100644 inputmodule-control/src/flap.rs diff --git a/inputmodule-control/src/flap.rs b/inputmodule-control/src/flap.rs new file mode 100644 index 00000000..a7972830 --- /dev/null +++ b/inputmodule-control/src/flap.rs @@ -0,0 +1,404 @@ +//! 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, play, to_grid, Burst, HostGame, Input, Light, FIELD_W, +}; +use crate::inputmodule::{GreyGrid, HEIGHT, WIDTH}; + +/// 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, + 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() -> Self { + let mut game = Self { + rng: thread_rng(), + 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 < FIELD_W + WALL_SPACING) + { + let (x, center) = match self.walls.back() { + // The first wall comes in after a moment + None => (FIELD_W + 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 = [[0.0; HEIGHT]; WIDTH]; + + // Dashed ground, scrolling along with the walls + let offset = self.scrolled % 2.0; + for i in 0..=WIDTH / 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], fps: Option) { + play( + serialdevs, + fps, + "Space, up or a click flaps.", + &mut Game::new(), + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 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() { + let mut game = Game::new(); + let mut input = Input::default(); + let dt = 1.0 / 60.0; + let lookahead = 1.0; + let mut now = 0.0; + while now < 150.0 { + // Flap only if not flapping would crash + input.action = game.state == State::Ready + || (survives(game.clone(), false, now, dt, lookahead) < lookahead + && survives(game.clone(), true, now, dt, lookahead) + > survives(game.clone(), false, now, dt, lookahead)); + 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 index 7ebe74f9..e8b0206d 100644 --- a/inputmodule-control/src/hostgame.rs +++ b/inputmodule-control/src/hostgame.rs @@ -43,6 +43,7 @@ pub fn add_square(light: &mut Light, x: f32, y: f32, brightness: f32) { } /// Sparks flying apart from a point, like when the player crashes +#[derive(Clone)] pub struct Burst { x: f32, y: f32, diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index cc200ebd..766a5757 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -292,6 +292,10 @@ pub fn serial_commands(args: &crate::ClapCli) { crate::cave::cave_cmd(&serialdevs, ledmatrix_args.fps); } + if ledmatrix_args.flap { + crate::flap::flap_cmd(&serialdevs, ledmatrix_args.fps); + } + if let Some(demo) = ledmatrix_args.demo { demo_cmd( &serialdevs, diff --git a/inputmodule-control/src/ledmatrix.rs b/inputmodule-control/src/ledmatrix.rs index 35c14402..b57515eb 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -199,7 +199,11 @@ pub struct LedMatrixSubcommand { #[arg(long)] pub cave: bool, - /// Limit --demo, --bricks, --cave, --video or --camera to this many frames per second. + /// Play a one-button flying game, flap with space, up or a click + #[arg(long)] + pub flap: 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)] diff --git a/inputmodule-control/src/main.rs b/inputmodule-control/src/main.rs index 077735dc..a47f87c8 100644 --- a/inputmodule-control/src/main.rs +++ b/inputmodule-control/src/main.rs @@ -4,6 +4,7 @@ mod b1display; mod bricks; mod c1minimal; mod cave; +mod flap; mod font; mod hostgame; mod inputmodule; From b042cd04ca26b44dfff45cdcfb2aacd3b951485d Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Thu, 12 Nov 2026 14:06:53 +0800 Subject: [PATCH 42/48] ledmatrix: Bump firmware version to 0.2.1 Makes newly flashed modules distinguishable from ones still on 0.2.0. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 4 ++-- fl16-inputmodules/Cargo.toml | 2 +- ledmatrix/Cargo.toml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index efb17d5d..fdb4e196 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -861,7 +861,7 @@ checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db" [[package]] name = "fl16-inputmodules" -version = "0.2.0" +version = "0.2.1" dependencies = [ "cortex-m", "cortex-m-rt", @@ -1261,7 +1261,7 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "ledmatrix" -version = "0.2.0" +version = "0.2.1" dependencies = [ "cortex-m", "cortex-m-rt", 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/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 = [] From 68f88860434a39ae2d9b512268eb35f82fe3d7be Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Thu, 12 Nov 2026 14:17:17 +0800 Subject: [PATCH 43/48] inputmodule-control: Add --extend to stream across several LED matrices --extend shows --demo, the games, --video and --camera on all LED matrices side by side, as one wide screen, instead of the same on each. Frames are as wide as the screen, and each LED matrix gets its part. Frames go to all LED matrices at the same time, so more of them don't make the frame rate drop. They're placed left to right in the order of --serial-dev, which can now be given several times, or sorted by port name without it. Scrolling text continues from one LED matrix to the next like columns in a newspaper, so letters aren't split between them. The hourglass now fills its chamber by the cells inside the glass, not the whole bounding box, so the wider glass doesn't overflow. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/bricks.rs | 64 ++--- inputmodule-control/src/cave.rs | 92 +++---- inputmodule-control/src/flap.rs | 89 ++++--- inputmodule-control/src/hostgame.rs | 64 +++-- inputmodule-control/src/inputmodule.rs | 321 ++++++++++++++++--------- inputmodule-control/src/ledmatrix.rs | 6 + inputmodule-control/src/main.rs | 5 +- 7 files changed, 393 insertions(+), 248 deletions(-) diff --git a/inputmodule-control/src/bricks.rs b/inputmodule-control/src/bricks.rs index 668a8ad3..e8530ea4 100644 --- a/inputmodule-control/src/bricks.rs +++ b/inputmodule-control/src/bricks.rs @@ -4,10 +4,8 @@ use std::collections::VecDeque; use rand::prelude::*; -use crate::hostgame::{ - add_rect, add_square, play, to_grid, HostGame, Input, Light, FIELD_H, FIELD_W, -}; -use crate::inputmodule::{GreyGrid, HEIGHT, WIDTH}; +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. @@ -90,6 +88,8 @@ enum State { struct Game { rng: ThreadRng, + /// Screen width in LEDs, one or more LED matrices side by side + width: f32, state: State, level: u32, score: u32, @@ -108,15 +108,16 @@ struct Game { } impl Game { - fn new() -> Self { + 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: FIELD_W / 2.0, + paddle_x: width as f32 / 2.0, ball_x: 0.0, ball_y: 0.0, vel_x: 0.0, @@ -132,9 +133,10 @@ impl Game { 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..WIDTH / BRICK_WIDTH).map(move |col| Brick { + (0..cols).map(move |col| Brick { x: col * BRICK_WIDTH, y: BRICK_TOP + row, hits: if row < tough_rows { 2 } else { 1 }, @@ -184,8 +186,8 @@ impl Game { self.ball_x = BALL_RADIUS; self.vel_x = self.vel_x.abs(); } - if self.ball_x + BALL_RADIUS > FIELD_W { - self.ball_x = FIELD_W - BALL_RADIUS; + 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 { @@ -263,7 +265,7 @@ impl HostGame for Game { let half = PADDLE_WIDTH / 2.0; self.paddle_x = input .steer(self.paddle_x, dt, PADDLE_KEY_SPEED, PADDLE_MAX_SPEED) - .clamp(half, FIELD_W - half); + .clamp(half, self.width - half); match self.state { State::Serving { since } => { self.ball_x = self.paddle_x; @@ -307,7 +309,7 @@ impl HostGame for Game { } fn render(&self, now: f32) -> GreyGrid { - let mut light: Light = [[0.0; HEIGHT]; WIDTH]; + 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); @@ -365,13 +367,13 @@ impl HostGame for Game { _ => self.balls, }; for i in 0..spare as usize { - light[WIDTH - 1 - 2 * i][HEIGHT - 1] += 0.15; + 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), (FIELD_W, y + 2.0), 0.8); + add_rect(&mut light, (0.0, y), (self.width, y + 2.0), 0.8); } let dim = if self.state == State::GameOver { @@ -398,35 +400,41 @@ impl HostGame for Game { } /// Play until the player quits, as fast as possible or limited to fps -pub fn bricks_cmd(serialdevs: &[String], fps: Option) { +pub fn bricks_cmd(serialdevs: &[String], extend: bool, fps: Option) { play( serialdevs, + extend, fps, "Space or a click launches the ball.", - &mut Game::new(), + 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() { - let mut game = Game::new(); - let mut input = Input::default(); - let dt = 1.0 / 120.0; - let mut now = 0.0; - while game.level == 1 { - input.target = Some(game.ball_x + 0.4); - 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"); + // 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); } - 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 index 3e445b72..f6e3d5ba 100644 --- a/inputmodule-control/src/cave.rs +++ b/inputmodule-control/src/cave.rs @@ -6,10 +6,8 @@ use std::f32::consts::PI; use rand::prelude::*; -use crate::hostgame::{ - add_rect, add_square, play, to_grid, Burst, HostGame, Input, Light, FIELD_W, -}; -use crate::inputmodule::{GreyGrid, HEIGHT, WIDTH}; +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; @@ -81,6 +79,8 @@ enum State { 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, @@ -98,13 +98,14 @@ struct Game { } impl Game { - fn new() -> Self { + 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: FIELD_W / 2.0, + player_x: width as f32 / 2.0, segments: VecDeque::new(), gems: VecDeque::new(), gems_taken: 0, @@ -120,14 +121,14 @@ impl Game { self.state = State::Ready; self.depth = 0.0; self.speed = START_SPEED; - self.player_x = FIELD_W / 2.0; + 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: FIELD_W / 2.0, + center: self.width / 2.0, half_width: START_HALF_WIDTH, }); self.extend_cave(); @@ -146,14 +147,14 @@ impl Game { 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 { - FIELD_W / 2.0 + 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, FIELD_W - half_width) + shifted.clamp(half_width, self.width - half_width) }; if depth >= STRAIGHT_START && self.rng.gen_bool(GEM_CHANCE) { let room = half_width - GEM_SIZE; @@ -237,7 +238,7 @@ impl HostGame for Game { self.player_x = input .steer(self.player_x, dt, PLAYER_KEY_SPEED, PLAYER_MAX_SPEED) - .clamp(0.5, FIELD_W - 0.5); + .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(); @@ -260,7 +261,7 @@ impl HostGame for Game { } fn render(&self, now: f32) -> GreyGrid { - let mut light: Light = [[0.0; HEIGHT]; WIDTH]; + 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); @@ -343,54 +344,59 @@ impl HostGame for Game { } /// Play until the player quits, as fast as possible or limited to fps -pub fn cave_cmd(serialdevs: &[String], fps: Option) { +pub fn cave_cmd(serialdevs: &[String], extend: bool, fps: Option) { play( serialdevs, + extend, fps, "Space or a click starts.", - &mut Game::new(), + 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() { - let mut game = Game::new(); - 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 <= FIELD_W + 0.01, - "Cave leaves the screen" - ); + // 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!( - right - left >= 2.0 * MIN_HALF_WIDTH - 0.01, - "Cave too narrow" + !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); } - 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 index a7972830..1ef18d22 100644 --- a/inputmodule-control/src/flap.rs +++ b/inputmodule-control/src/flap.rs @@ -6,10 +6,8 @@ use std::collections::VecDeque; use rand::prelude::*; -use crate::hostgame::{ - add_rect, add_square, play, to_grid, Burst, HostGame, Input, Light, FIELD_W, -}; -use crate::inputmodule::{GreyGrid, HEIGHT, WIDTH}; +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; @@ -74,6 +72,8 @@ enum State { #[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, @@ -91,9 +91,10 @@ struct Game { } impl Game { - fn new() -> Self { + 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, @@ -128,11 +129,11 @@ impl Game { while self .walls .back() - .is_none_or(|w| w.x < FIELD_W + WALL_SPACING) + .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 => (FIELD_W + 2.0, GROUND / 2.0), + 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. @@ -242,11 +243,11 @@ impl HostGame for Game { } fn render(&self, now: f32) -> GreyGrid { - let mut light: Light = [[0.0; HEIGHT]; WIDTH]; + 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..=WIDTH / 2 + 1 { + for i in 0..=self.width as usize / 2 + 1 { let x = i as f32 * 2.0 - offset; add_rect( &mut light, @@ -323,18 +324,20 @@ impl HostGame for Game { } /// Play until the player quits, as fast as possible or limited to fps -pub fn flap_cmd(serialdevs: &[String], fps: Option) { +pub fn flap_cmd(serialdevs: &[String], extend: bool, fps: Option) { play( serialdevs, + extend, fps, "Space, up or a click flaps.", - &mut Game::new(), + 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 @@ -371,34 +374,42 @@ mod tests { /// the smallest gaps, so the hardest walls are still fair #[test] fn autoplay_survives() { - let mut game = Game::new(); - let mut input = Input::default(); - let dt = 1.0 / 60.0; - let lookahead = 1.0; - let mut now = 0.0; - while now < 150.0 { - // Flap only if not flapping would crash - input.action = game.state == State::Ready - || (survives(game.clone(), false, now, dt, lookahead) < lookahead - && survives(game.clone(), true, now, dt, lookahead) - > survives(game.clone(), false, now, dt, lookahead)); - 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::>() - ); + // 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); } - 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 index e8b0206d..1e606bc6 100644 --- a/inputmodule-control/src/hostgame.rs +++ b/inputmodule-control/src/hostgame.rs @@ -16,17 +16,22 @@ use crossterm::event::{ use crossterm::{cursor, execute, terminal}; use rand::Rng; -use crate::inputmodule::{open_stream_ports, send_grey_frame, GreyGrid, HEIGHT, WIDTH}; +use crate::inputmodule::{GreyGrid, Matrices, HEIGHT}; -pub const FIELD_W: f32 = WIDTH as f32; pub const FIELD_H: f32 = HEIGHT as f32; /// Brightness of each LED, 1.0 is fully on. Adds up where shapes overlap. -pub type Light = [[f32; HEIGHT]; WIDTH]; +/// 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(FIELD_W) as usize); + 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); @@ -83,14 +88,13 @@ impl Burst { /// Convert to a frame for the LED matrix, scaling everything by dim pub fn to_grid(light: &Light, dim: f32) -> GreyGrid { - let mut grid = [[0; HEIGHT]; WIDTH]; - for x in 0..WIDTH { - for y in 0..HEIGHT { + light + .iter() + .map(|col| { // Linear instead of gamma, so the total light stays the same while moving - grid[x][y] = (light[x][y].clamp(0.0, 1.0) * dim * 255.0) as u8; - } - } - grid + col.map(|l| (l.clamp(0.0, 1.0) * dim * 255.0) as u8) + }) + .collect() } /// What the player wants, collected from terminal events @@ -170,8 +174,13 @@ impl Drop for RawTerminal { } } -/// Apply all pending terminal events to the input -fn read_input(input: &mut Input, key_releases: bool, player_x: f32) -> std::io::Result<()> { +/// 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) => { @@ -205,9 +214,9 @@ fn read_input(input: &mut Input, key_releases: bool, player_x: f32) -> std::io:: } } Event::Mouse(mouse) => { - // The width of the terminal maps to the width of the LED matrix + // 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 * FIELD_W; + 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, @@ -220,9 +229,19 @@ fn read_input(input: &mut Input, key_releases: bool, player_x: f32) -> std::io:: Ok(()) } -/// Play until the player quits, as fast as possible or limited to fps -pub fn play(serialdevs: &[String], fps: Option, help: &str, game: &mut impl HostGame) { - let mut ports = open_stream_ports(serialdevs); +/// Play until the player quits, as fast as possible or limited to fps. +/// 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!("Steer with the arrow keys, or move the mouse across this terminal."); println!("{} Q or Esc quits.", help); @@ -236,7 +255,8 @@ pub fn play(serialdevs: &[String], fps: Option, help: &str, game: &mut impl let mut fps_since = start; let mut measured_fps = 0.0; loop { - read_input(&mut input, term.key_releases, game.player_x()).expect("Failed to read input"); + read_input(&mut input, term.key_releases, game.player_x(), width as f32) + .expect("Failed to read input"); if input.quit { break; } @@ -246,7 +266,7 @@ pub fn play(serialdevs: &[String], fps: Option, help: &str, game: &mut impl last = now; game.update(&mut input, now, dt); input.action = false; - send_grey_frame(&mut ports, &game.render(now)); + matrices.send(&game.render(now)); frames += 1; fps_frames += 1; @@ -267,7 +287,7 @@ pub fn play(serialdevs: &[String], fps: Option, help: &str, game: &mut impl } // Leave the matrix dark instead of on the last frame - send_grey_frame(&mut ports, &[[0; HEIGHT]; WIDTH]); + matrices.clear(); drop(term); println!("{}", game.status(measured_fps)); } @@ -278,7 +298,7 @@ mod tests { #[test] fn square_covers_partial_leds() { - let mut light = [[0.0f32; HEIGHT]; WIDTH]; + 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); diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index 766a5757..0642e452 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -70,16 +70,17 @@ 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 { @@ -255,6 +256,16 @@ pub fn serial_commands(args: &crate::ClapCli) { ); } } + + // Streaming to all LED matrices side by side. Without --serial-dev, they're + // found in no particular order, so at least make it the same every time. + let extend = ledmatrix_args.extend; + let mut serialdevs = serialdevs; + if extend && args.serial_dev.is_empty() { + // COM9 before COM10 + serialdevs.sort_by_key(|dev| (dev.len(), dev.clone())); + } + // Commands that block and need manual looping if ledmatrix_args.blinking { blinking_cmd(&serialdevs); @@ -277,28 +288,29 @@ pub fn serial_commands(args: &crate::ClapCli) { } if let Some(path) = &ledmatrix_args.video { - video_cmd(&serialdevs, path, ledmatrix_args.fps); + video_cmd(&serialdevs, extend, path, ledmatrix_args.fps); } if let Some(device) = &ledmatrix_args.camera { - camera_cmd(&serialdevs, device.as_deref(), ledmatrix_args.fps); + camera_cmd(&serialdevs, extend, device.as_deref(), ledmatrix_args.fps); } if ledmatrix_args.bricks { - crate::bricks::bricks_cmd(&serialdevs, ledmatrix_args.fps); + crate::bricks::bricks_cmd(&serialdevs, extend, ledmatrix_args.fps); } if ledmatrix_args.cave { - crate::cave::cave_cmd(&serialdevs, ledmatrix_args.fps); + crate::cave::cave_cmd(&serialdevs, extend, ledmatrix_args.fps); } if ledmatrix_args.flap { - crate::flap::flap_cmd(&serialdevs, ledmatrix_args.fps); + crate::flap::flap_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, @@ -967,7 +979,9 @@ fn display_gray_image_cmd(serialdev: &str, image_path: &str) { commit_cols(&mut port); } -pub type GreyGrid = [[u8; HEIGHT]; WIDTH]; +/// 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 { @@ -976,10 +990,11 @@ fn gamma(brightness: f32) -> u8 { } /// Overlapping sine waves, depends only on the time, not on the frame rate -fn plasma_frame(t: f32) -> GreyGrid { - let mut grid = [[0; HEIGHT]; WIDTH]; +fn plasma_frame(t: f32, width: usize) -> GreyGrid { + let mut grid = vec![[0; HEIGHT]; width]; // Center of the circular wave moves around - let cx = 4.0 + (t * 0.5).sin() * 3.0; + 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() { @@ -1002,25 +1017,26 @@ 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: [[f32; HEIGHT]; WIDTH], - next: [[f32; HEIGHT]; WIDTH], + prev: Vec<[f32; HEIGHT]>, + next: Vec<[f32; HEIGHT]>, steps: u64, rng: ThreadRng, } impl Fire { - fn new() -> Self { + fn new(width: usize) -> Self { Self { - prev: [[0.0; HEIGHT]; WIDTH], - next: [[0.0; HEIGHT]; WIDTH], + prev: vec![[0.0; HEIGHT]; width], + next: vec![[0.0; HEIGHT]; width], steps: 0, rng: thread_rng(), } } fn step(&mut self) { - self.prev = self.next; + 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); @@ -1028,9 +1044,9 @@ impl Fire { // 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 { + 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 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); } @@ -1045,11 +1061,11 @@ impl Fire { self.step(); } let blend = pos - (self.steps - 2) as f32; - let mut grid = [[0; HEIGHT]; WIDTH]; - for x in 0..WIDTH { - for y in 0..HEIGHT { + 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; - grid[x][y] = gamma(heat); + *val = gamma(heat); } } grid @@ -1059,16 +1075,21 @@ impl Fire { /// 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 +/// 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) -> Self { - // Start with an empty screen, so the text scrolls in from the bottom and out at the top - let mut rows = vec![[0.0; WIDTH]; HEIGHT]; + 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); @@ -1081,23 +1102,25 @@ impl ScrollingText { } rows.push([0.0; WIDTH]); } - Self { rows } + 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 = [[0; HEIGHT]; WIDTH]; - for y in 0..HEIGHT { - let pos = offset + 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[x][y] = (brightness * 255.0) as u8; + 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 @@ -1106,34 +1129,35 @@ impl ScrollingText { /// 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_W: usize = WIDTH * SAND_SUB; 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.55; +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 = [[bool; SAND_H]; SAND_W]; +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) -> bool { +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; - let half_width = half.min(1 + to_neck).min(8 + to_end); + 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) } @@ -1143,7 +1167,7 @@ fn inside_glass(x: usize, y: usize) -> bool { struct Hourglass { glass: SandGrid, /// LEDs that the edge of the glass goes through, to show its outline - edge: [[bool; HEIGHT]; WIDTH], + edge: Vec<[bool; HEIGHT]>, /// Sand after the previous and the next simulation step prev: SandGrid, next: SandGrid, @@ -1163,15 +1187,16 @@ struct Hourglass { } impl Hourglass { - fn new(minutes: &[f32]) -> Self { - let mut glass = [[false; SAND_H]; SAND_W]; + 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); + *cell = inside_glass(x, y, sand_w); } } - let mut edge = [[false; HEIGHT]; WIDTH]; + 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) @@ -1182,15 +1207,15 @@ impl Hourglass { } // Fill the top chamber from the neck upwards, whole rows at a time - let chamber: usize = glass.iter().flatten().count() / 2; - let mut sand = [[false; SAND_H]; SAND_W]; + 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(); + 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 { + for x in 0..sand_w { sand[x][y] = glass[x][y]; } grains += row; @@ -1200,7 +1225,7 @@ impl Hourglass { Self { glass, edge, - prev: sand, + prev: sand.clone(), next: sand, steps: 0, rng: thread_rng(), @@ -1215,14 +1240,15 @@ impl Hourglass { /// Turn upside down and start the next timer fn flip(&mut self, now: f32) { - let old = self.next; - for x in 0..SAND_W { + 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]; + self.next[x][y] = old[sand_w - 1 - x][SAND_H - 1 - y]; } } // Don't blend between before and after flipping - self.prev = self.next; + self.prev.clone_from(&self.next); self.top = self .next .iter() @@ -1236,7 +1262,7 @@ impl Hourglass { } fn step(&mut self) { - self.prev = self.next; + self.prev.clone_from(&self.next); let dt = 1.0 / SAND_STEPS_PER_SEC; let now = self.steps as f32 * dt; self.steps += 1; @@ -1253,6 +1279,7 @@ impl Hourglass { 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; @@ -1267,20 +1294,20 @@ impl Hourglass { // 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 { + 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 }; + 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)) + (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)) + (Some(x + 1).filter(|&x| x < sand_w), x.checked_sub(1)) }; [first, second] .into_iter() @@ -1337,8 +1364,8 @@ impl Hourglass { }; let cells = (SAND_SUB * SAND_SUB) as f32; - let mut grid = [[0; HEIGHT]; WIDTH]; - for x in 0..WIDTH { + 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) @@ -1361,29 +1388,76 @@ impl Hourglass { } } -/// Open ports for streaming frames and wake up the LED matrices -pub fn open_stream_ports(serialdevs: &[String]) -> Vec> { - 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() -} - -/// Send a greyscale frame to every port -pub fn send_grey_frame(ports: &mut [Box], grid: &GreyGrid) { - for port in ports { - for (x, col) in grid.iter().enumerate() { - send_col(port, x as u8, col); +/// 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); } - 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()]); } } @@ -1451,7 +1525,7 @@ fn ffmpeg_available() -> bool { } /// Play a video in greyscale at its own frame rate, or resampled to fps -fn video_cmd(serialdevs: &[String], path: &str, fps: Option) { +fn video_cmd(serialdevs: &[String], extend: bool, path: &str, fps: Option) { if !ffmpeg_available() { return; } @@ -1462,7 +1536,7 @@ fn video_cmd(serialdevs: &[String], path: &str, fps: Option) { 30.0 }), }; - ffmpeg_stream(serialdevs, &["-i", path], fps, Some(frame_rate)); + ffmpeg_stream(serialdevs, extend, &["-i", path], fps, Some(frame_rate)); } /// Name of the first DirectShow video device, like "Laptop Webcam Module (2nd Gen)" @@ -1489,7 +1563,7 @@ fn first_dshow_camera() -> Option { /// 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], device: Option<&str>, fps: Option) { +fn camera_cmd(serialdevs: &[String], extend: bool, device: Option<&str>, fps: Option) { if !ffmpeg_available() { return; } @@ -1524,20 +1598,27 @@ fn camera_cmd(serialdevs: &[String], device: Option<&str>, fps: Option) { let input: Vec<&str> = input.iter().map(String::as_str).collect(); // Frames come in live, no need to pace them - ffmpeg_stream(serialdevs, &input, fps, None); + 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], input: &[&str], fps: Option, frame_rate: Option) { +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 ports = open_stream_ports(serialdevs); + 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" + "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}"); @@ -1553,7 +1634,7 @@ fn ffmpeg_stream(serialdevs: &[String], input: &[&str], fps: Option, frame_ let mut reporter = FpsReporter::new(); // One byte per pixel, row by row - let mut pixels = [0; WIDTH * HEIGHT]; + 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() { @@ -1568,14 +1649,14 @@ fn ffmpeg_stream(serialdevs: &[String], input: &[&str], fps: Option, frame_ frames += 1; } - let mut grid = [[0; HEIGHT]; WIDTH]; + 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); + *val = gamma(pixels[x + y * width] as f32 / 255.0); } } - send_grey_frame(&mut ports, &grid); + matrices.send(&grid); reporter.frame_sent(); } let _ = ffmpeg.wait(); @@ -1584,12 +1665,20 @@ fn ffmpeg_stream(serialdevs: &[String], input: &[&str], fps: Option, frame_ /// 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], demo: Demo, text: &str, minutes: &[f32], fps: Option) { - let mut ports = open_stream_ports(serialdevs); - - let mut fire = Fire::new(); - let scrolling_text = ScrollingText::new(text); - let mut hourglass = Hourglass::new(minutes); +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, @@ -1601,7 +1690,7 @@ fn demo_cmd(serialdevs: &[String], demo: Demo, text: &str, minutes: &[f32], fps: loop { let t = start.elapsed().as_secs_f32(); let grid = match demo { - Demo::Plasma => plasma_frame(t), + Demo::Plasma => plasma_frame(t, width), Demo::Fire => fire.frame(t), Demo::Text => scrolling_text.frame(t), Demo::Hourglass => { @@ -1610,7 +1699,7 @@ fn demo_cmd(serialdevs: &[String], demo: Demo, text: &str, minutes: &[f32], fps: grid } }; - send_grey_frame(&mut ports, &grid); + matrices.send(&grid); frames += 1; reporter.frame_sent(); @@ -2151,8 +2240,9 @@ mod tests { #[test] fn hourglass_runs_out_on_time() { - for minutes in [0.5, 2.0] { - let mut hourglass = Hourglass::new(&[minutes, 0.25]); + // 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); @@ -2163,7 +2253,10 @@ mod tests { assert!(t < minutes * 60.0 + 10.0, "Sand didn't run out"); } let ran_out = hourglass.empty_since.unwrap(); - println!("{} min ran out after {:.1}s", minutes, ran_out); + 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); diff --git a/inputmodule-control/src/ledmatrix.rs b/inputmodule-control/src/ledmatrix.rs index b57515eb..b9f47c15 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -203,6 +203,12 @@ pub struct LedMatrixSubcommand { #[arg(long)] pub flap: 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 diff --git a/inputmodule-control/src/main.rs b/inputmodule-control/src/main.rs index a47f87c8..b776a11a 100644 --- a/inputmodule-control/src/main.rs +++ b/inputmodule-control/src/main.rs @@ -52,9 +52,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)] From 779fe8e79bd3da81d0a4a7c27d7783a63355b028 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Thu, 12 Nov 2026 14:26:30 +0800 Subject: [PATCH 44/48] inputmodule-control: Order --extend by input deck slot COM port numbers depend on enumeration order and not every LED matrix reports a serial number, so sorting by COM name puts them in a random order. The USB port of each Framework 16 input deck slot is fixed, so look up the location path of each serial device and order the LED matrices left to right by their slot. --list now also shows the USB location and slot of each device. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + inputmodule-control/Cargo.toml | 9 ++ inputmodule-control/src/inputmodule.rs | 19 ++- inputmodule-control/src/main.rs | 1 + inputmodule-control/src/usbport.rs | 183 +++++++++++++++++++++++++ 5 files changed, 210 insertions(+), 3 deletions(-) create mode 100644 inputmodule-control/src/usbport.rs diff --git a/Cargo.lock b/Cargo.lock index fdb4e196..ca02a66f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1148,6 +1148,7 @@ dependencies = [ "serialport", "static_vcruntime", "vis-core", + "windows-sys 0.52.0", ] [[package]] diff --git a/inputmodule-control/Cargo.toml b/inputmodule-control/Cargo.toml index 41576eab..6c419ad7 100644 --- a/inputmodule-control/Cargo.toml +++ b/inputmodule-control/Cargo.toml @@ -19,6 +19,15 @@ rand = "0.8.5" # 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/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index 0642e452..99d9e422 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -126,6 +126,12 @@ pub fn find_serialdevs(args: &crate::ClapCli, wait_for_device: bool) -> (Vec { //println!("{}", p.port_name); @@ -258,12 +264,19 @@ pub fn serial_commands(args: &crate::ClapCli) { } // Streaming to all LED matrices side by side. Without --serial-dev, they're - // found in no particular order, so at least make it the same every time. + // 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() { - // COM9 before COM10 - serialdevs.sort_by_key(|dev| (dev.len(), dev.clone())); + // 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 diff --git a/inputmodule-control/src/main.rs b/inputmodule-control/src/main.rs index b776a11a..fd1b4f26 100644 --- a/inputmodule-control/src/main.rs +++ b/inputmodule-control/src/main.rs @@ -9,6 +9,7 @@ mod font; mod hostgame; mod inputmodule; mod ledmatrix; +mod usbport; use clap::{Parser, Subcommand}; use inputmodule::find_serialdevs; 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); + } +} From 937d939c51d7df1d0644bc009db79c09b3c3d357 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Thu, 12 Nov 2026 14:43:17 +0800 Subject: [PATCH 45/48] fl16-inputmodules: Format matrix_sync stats with rustfmt Co-Authored-By: Claude Opus 5.5 --- fl16-inputmodules/src/matrix_sync.rs | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/fl16-inputmodules/src/matrix_sync.rs b/fl16-inputmodules/src/matrix_sync.rs index 42992818..56aa5f61 100644 --- a/fl16-inputmodules/src/matrix_sync.rs +++ b/fl16-inputmodules/src/matrix_sync.rs @@ -108,16 +108,7 @@ impl Stats { self.calc_us_max = 0; vals } - 2 => [ - self.led_power_ons, - self.led_off_us_total, - 0, - 0, - 0, - 0, - 0, - 0, - ], + 2 => [self.led_power_ons, self.led_off_us_total, 0, 0, 0, 0, 0, 0], _ => [0; 8], }; let mut response = [0; 32]; From b5f6c191d67e29829b99f151cb73996a51d4f13c Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Thu, 12 Nov 2026 14:43:17 +0800 Subject: [PATCH 46/48] inputmodule-control: Show firmware version in --list --list now asks each LED matrix, B1 LCD and C1 minimal module for its firmware version. Other devices are skipped, they don't speak the protocol. If a module doesn't answer, the error is shown instead of aborting. The version query waits up to 500ms, because the first response after opening the port sometimes takes longer than the usual 20ms timeout. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 47 ++++++++++++++++++++------ 1 file changed, 36 insertions(+), 11 deletions(-) diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index 99d9e422..76fea23d 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -17,6 +17,7 @@ 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; @@ -87,7 +88,7 @@ fn match_serialdevs( 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 { @@ -132,6 +133,16 @@ 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); @@ -408,27 +419,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) { From 6bcb42dc8e06eef2de8f18b65cd6c55e6f6d0fa7 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Thu, 12 Nov 2026 15:09:28 +0800 Subject: [PATCH 47/48] inputmodule-control: Let host games see every key press Input now also has every key pressed since the last update, including key repeats, for games that need more than steering and one action. The hint to steer with the arrow keys or the mouse is now part of each game's help, since not every game steers. --flap no longer shows it. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/bricks.rs | 3 ++- inputmodule-control/src/cave.rs | 3 ++- inputmodule-control/src/hostgame.rs | 9 +++++++-- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/inputmodule-control/src/bricks.rs b/inputmodule-control/src/bricks.rs index e8530ea4..5d681b01 100644 --- a/inputmodule-control/src/bricks.rs +++ b/inputmodule-control/src/bricks.rs @@ -405,7 +405,8 @@ pub fn bricks_cmd(serialdevs: &[String], extend: bool, fps: Option) { serialdevs, extend, fps, - "Space or a click launches the ball.", + "Steer with the arrow keys, or move the mouse across this terminal. +Space or a click launches the ball.", Game::new, ); } diff --git a/inputmodule-control/src/cave.rs b/inputmodule-control/src/cave.rs index f6e3d5ba..f270189d 100644 --- a/inputmodule-control/src/cave.rs +++ b/inputmodule-control/src/cave.rs @@ -349,7 +349,8 @@ pub fn cave_cmd(serialdevs: &[String], extend: bool, fps: Option) { serialdevs, extend, fps, - "Space or a click starts.", + "Steer with the arrow keys, or move the mouse across this terminal. +Space or a click starts.", Game::new, ); } diff --git a/inputmodule-control/src/hostgame.rs b/inputmodule-control/src/hostgame.rs index 1e606bc6..29401ec2 100644 --- a/inputmodule-control/src/hostgame.rs +++ b/inputmodule-control/src/hostgame.rs @@ -107,6 +107,8 @@ pub struct Input { 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, } @@ -185,6 +187,9 @@ fn read_input( 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 { @@ -230,7 +235,7 @@ fn read_input( } /// Play until the player quits, as fast as possible or limited to fps. -/// new_game makes the game for a screen that many LEDs wide. +/// 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], @@ -242,7 +247,6 @@ pub fn play( let mut matrices = Matrices::open(serialdevs, extend); let width = matrices.width(); let mut game = new_game(width); - println!("Steer with the arrow keys, or move the mouse across this terminal."); println!("{} Q or Esc quits.", help); let term = RawTerminal::new().expect("Failed to set up the terminal"); @@ -266,6 +270,7 @@ pub fn play( last = now; game.update(&mut input, now, dt); input.action = false; + input.presses.clear(); matrices.send(&game.render(now)); frames += 1; From 7cfbe809099e4c428350cc34aa677f8313a50d49 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Thu, 12 Nov 2026 15:09:28 +0800 Subject: [PATCH 48/48] inputmodule-control: Add Ledris, a falling block puzzle --ledris: move and turn the falling blocks of four 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 between rows and a dim copy shows where it will land. Full rows flash and fade out before the rest drops down. With --extend the well is as wide as all LED matrices together. Left and right move, up or X turns, Z turns the other way, down drops faster and space drops all the way. Blocks come in shuffled sets of all seven, and can still be moved for a moment after they land. A test plays with a player that tries every place for each block, to make sure full rows are found, scored and removed. Co-Authored-By: Claude Opus 5.5 --- inputmodule-control/src/inputmodule.rs | 4 + inputmodule-control/src/ledmatrix.rs | 4 + inputmodule-control/src/ledris.rs | 698 +++++++++++++++++++++++++ inputmodule-control/src/main.rs | 1 + 4 files changed, 707 insertions(+) create mode 100644 inputmodule-control/src/ledris.rs diff --git a/inputmodule-control/src/inputmodule.rs b/inputmodule-control/src/inputmodule.rs index 76fea23d..bab63a65 100644 --- a/inputmodule-control/src/inputmodule.rs +++ b/inputmodule-control/src/inputmodule.rs @@ -331,6 +331,10 @@ pub fn serial_commands(args: &crate::ClapCli) { 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, diff --git a/inputmodule-control/src/ledmatrix.rs b/inputmodule-control/src/ledmatrix.rs index b9f47c15..0f2a5ddc 100644 --- a/inputmodule-control/src/ledmatrix.rs +++ b/inputmodule-control/src/ledmatrix.rs @@ -203,6 +203,10 @@ pub struct LedMatrixSubcommand { #[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 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 fd1b4f26..96fe9aac 100644 --- a/inputmodule-control/src/main.rs +++ b/inputmodule-control/src/main.rs @@ -9,6 +9,7 @@ mod font; mod hostgame; mod inputmodule; mod ledmatrix; +mod ledris; mod usbport; use clap::{Parser, Subcommand};