Files
pbio/examples/starter.rs
T
2026-07-05 15:12:23 +02:00

75 lines
2.7 KiB
Rust

//! pbio starter — Ausgangspunkt für eigene CPU-Render-Projekte.
//!
//! Ausführen: cargo run --example starter --release
//!
//! Zeigt: Game-Loop-Struktur, non-blocking Event-Polling, Tastatur (Esc beendet),
//! Maus, direktes Schreiben auf den RGB565-Framebuffer.
use std::time::Duration;
use pbio::{rgb565, Event, Key, MouseButton, Platform, PlatformConfig};
fn main() {
let mut p = Platform::new(PlatformConfig {
title: "pbio starter".into(),
window_size: (1240, 960),
framebuffer_size: (620, 480),
aspect_ratio: Some(620.0/480.0),
..Default::default()
});
let mut mouse = (0.0_f32, 0.0_f32);
let mut paint = false;
let mut frame = 0u32;
while !p.should_close() {
// 0-Timeout: nicht-blockierend pollen, damit der Loop unabhängig
// von Eingaben pro Frame durchläuft. None würde bis zum nächsten
// Event schlafen — gut für statische UIs, schlecht für Animation.
p.poll_events(Some(Duration::from_millis(0)));
// poll_event() gibt &mut self nach jedem Call wieder frei → Aktionen
// auf p (request_close, set_mouse_capture …) sind direkt im Loop
// erlaubt. drain_events() existiert weiter für den Fall, dass
// nur gelesen wird.
while let Some(ev) = p.poll_event() {
match ev {
Event::Key { key: Key::Escape, pressed: true, .. } => p.request_close(),
Event::MouseMove { x, y } => mouse = (x, y),
Event::MouseBtn { button: MouseButton::Left, pressed } => paint = pressed,
_ => {}
}
}
let (w, h) = p.framebuffer_size();
let fb = p.framebuffer_mut();
// Diagonal wanderndes Farbverlauf-Band, direkt als RGB565-Truecolor.
let t = (frame / 2) as u8;
for y in 0..h {
for x in 0..w {
let r = (x as u8).wrapping_add(t);
let g = (y as u8).wrapping_add(t);
let b = (x as u8).wrapping_add(y as u8);
fb[(y * w + x) as usize] = rgb565(r, g, b);
}
}
// Cursor: 3x3-Quadrat, rot; beim Klick gelb.
let (mx, my) = (mouse.0 as i32, mouse.1 as i32);
let cursor_px = if paint { rgb565(255, 255, 0) } else { rgb565(255, 0, 0) };
for dy in -1..=1 {
for dx in -1..=1 {
let x = mx + dx;
let y = my + dy;
if (0..w as i32).contains(&x) && (0..h as i32).contains(&y) {
fb[(y as u32 * w + x as u32) as usize] = cursor_px;
}
}
}
p.present();
frame = frame.wrapping_add(1);
}
}