M0: compilable skeleton — Kigi 0.1.0 fork surgery
Hard fork of xai-org/grok-build (Apache-2.0) re-targeted as Kigi, an
unofficial Kimi Code CLI community build.
Rename & identity
- 72 xai-*/xai-grok-* crates -> kigi-* (explicit: xai-grok-pager-bin ->
kigi-bin [binary `kigi`], xai-grok-pager -> kigi-tui; rest mechanical);
ptyctl, ptyctl-cli, third_party/ unchanged; proto package
xai.grok.tools.v1 -> kigi.tools.v1
- Config home ~/.kigi (KIGI_SHARE_DIR override), env prefix GROK_* ->
KIGI_*, `kigi --version` carries the unofficial-community-build notice
- clap identity, help text, startup banner, prompt templates rebranded
(templates re-encrypted)
Deletions (PRD removal list #5/#6/#7/#9/#10)
- voice input (xai-grok-voice) and all TUI wiring
- telemetry: Mixpanel client, external OTel stream, Sentry, OTLP layers,
trace/GCS/S3 upload queues (kigi-file-utils halved), workspace upload
module & dc_log, heap-profile uploader, auth-diagnostics uploader,
session-analytics halves of feedback; local zero-egress observability
preserved in new kigi-log crate (unified log, --debug firehose,
subsystem file logs, opt-in instrumentation)
- announcements (crate, remote-settings fields, TUI surfaces)
- plugin marketplace (crate, sources/browse/CTA/extensions-modal tab);
direct plugin install/uninstall/update via kigi-agent git_install kept
- relay/gateway/assets endpoints and features (agent relay, headless
relay transport, gateway bridge, LeaderEnvUrls); leader IPC socket now
~/.kigi/leader.sock + KIGI_LEADER_SOCKET, no ws-url derivation
- functional types rehomed instead of deleted: PermissionMode ->
kigi-config-types, McpInitStrategy -> kigi-mcp, PrCreationSource ->
session signals, TerminalDiagnostics -> kigi-pager-render, agent_id ->
shell util
Endpoints
- kigi-env rewritten: single production KigiEndpoints {coding_api_base_url
https://api.kimi.com/coding/v1 (KIGI_CODE_BASE_URL), oauth_host
https://auth.kimi.com (KIGI_OAUTH_HOST), update_base_url (GitHub
Releases API), upgrade_page_url}; GrokBuildEnvironment enum deleted
Toolchain & workspace hygiene
- Rust 1.97.0 pinned; edition 2024; full cargo update; git2 hoisted to
workspace at 0.21 (Option->Result API migration), quick-xml 0.41
- Root Cargo.toml hand-maintained (PRD §8.1): version 0.1.0 inherited by
all members, members sorted, unused deps pruned
- cargo-deny advisories gate (deny.toml with documented transitive
exceptions); CI workflow (check/clippy/fmt/deny/test, macOS+Linux)
- cross-crate test seams re-gated behind `test-support` cargo feature;
insta snapshot baselines renamed to the kigi_tui prefix
- clippy --workspace --all-targets: zero warnings; fmt clean
Fixes surfaced by the port
- updater probe/installer divergence (bin/kigi vs bin/grok symlink set)
- idle model-metadata refresh dead under KIGI_CODE_BASE_URL override
(new is_effective_coding_endpoint_url, loopback+override aware)
- macOS symlinked-TMPDIR fixture canonicalization (foreign_sessions,
fast-worktree); RSS measurement tests serialized via serial_test
Docs & legal (Apache §4)
- NOTICE added (upstream attribution + change statement); THIRD-PARTY
notices sustained; kigi-tools ported-code notices extended; README,
CONTRIBUTING, SECURITY, AGENTS.md rewritten
Out of scope for M0 (tracked): Kimi auth/inference (M1), search/fetch,
command parity, config import (M2), Computer Hub excision & final
brand-token sweep (M2), distribution & self-update rewrite (M3).
This commit is contained in:
commit
d6c20fc13f
2612 files changed
+1353757
No files matched your search
@@ -0,0 +1,711 @@
|
||||
//! Procedural art assets for the `/gboom` easter egg.
|
||||
//!
|
||||
//! Everything is generated in code — no binary assets, no copyrighted
|
||||
//! material. Wall textures are synthesized from hash noise, sprites are
|
||||
//! hand-drawn char-map pixel art, and text uses a tiny 5x7 pixel font.
|
||||
|
||||
/// RGB color.
|
||||
pub(super) type Rgb = [u8; 3];
|
||||
|
||||
/// Wall texture side length (square).
|
||||
pub(super) const TEX_SIZE: usize = 64;
|
||||
|
||||
/// The signature crimson red, shared by the title screen, end screens,
|
||||
/// and the overlay chrome so they always match.
|
||||
pub(crate) const GBOOM_RED: Rgb = [235, 40, 32];
|
||||
|
||||
/// Imp eye color. The renderer exempts exactly this color from distance
|
||||
/// fog so eyes glow in the dark; keep the sprite art and renderer in sync
|
||||
/// through this constant.
|
||||
pub(super) const EYE_GLOW: Rgb = [255, 216, 0];
|
||||
|
||||
/// Minimal xorshift64* PRNG.
|
||||
///
|
||||
/// The game needs determinism-friendly, allocation-free randomness for
|
||||
/// damage rolls and the fire effect — not `rand`-crate quality. Seeded
|
||||
/// per consumer so simulation and visuals stay independent streams.
|
||||
pub(super) struct XorShift64(u64);
|
||||
|
||||
impl XorShift64 {
|
||||
pub fn new(seed: u64) -> Self {
|
||||
Self(seed.max(1)) // xorshift state must be non-zero
|
||||
}
|
||||
|
||||
pub fn next_u32(&mut self) -> u32 {
|
||||
self.0 ^= self.0 >> 12;
|
||||
self.0 ^= self.0 << 25;
|
||||
self.0 ^= self.0 >> 27;
|
||||
(self.0.wrapping_mul(0x2545F4914F6CDD1D) >> 33) as u32
|
||||
}
|
||||
|
||||
/// Uniform float in `[0.0, 1.0)`.
|
||||
pub fn next_f32(&mut self) -> f32 {
|
||||
(self.next_u32() >> 8) as f32 / (1u32 << 24) as f32
|
||||
}
|
||||
}
|
||||
|
||||
/// Deterministic 2D integer hash → `[0.0, 1.0)`. Used for texture noise.
|
||||
fn hash01(x: u32, y: u32, seed: u32) -> f32 {
|
||||
let mut h = x
|
||||
.wrapping_mul(0x9E37_79B9)
|
||||
.wrapping_add(y.wrapping_mul(0x85EB_CA6B))
|
||||
.wrapping_add(seed.wrapping_mul(0xC2B2_AE35));
|
||||
h ^= h >> 16;
|
||||
h = h.wrapping_mul(0x7FEB_352D);
|
||||
h ^= h >> 15;
|
||||
h = h.wrapping_mul(0x846C_A68B);
|
||||
h ^= h >> 16;
|
||||
(h & 0xFFFF) as f32 / 65536.0
|
||||
}
|
||||
|
||||
fn scale(c: Rgb, f: f32) -> Rgb {
|
||||
[
|
||||
(c[0] as f32 * f).clamp(0.0, 255.0) as u8,
|
||||
(c[1] as f32 * f).clamp(0.0, 255.0) as u8,
|
||||
(c[2] as f32 * f).clamp(0.0, 255.0) as u8,
|
||||
]
|
||||
}
|
||||
|
||||
/// A generated wall texture: `TEX_SIZE * TEX_SIZE` RGB pixels, row-major.
|
||||
pub(super) struct Texture {
|
||||
pub pixels: Vec<Rgb>,
|
||||
}
|
||||
|
||||
impl Texture {
|
||||
#[inline]
|
||||
pub fn sample(&self, x: usize, y: usize) -> Rgb {
|
||||
self.pixels[(y & (TEX_SIZE - 1)) * TEX_SIZE + (x & (TEX_SIZE - 1))]
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate the wall texture set, indexed by map cell value - 1.
|
||||
pub(super) fn build_textures() -> Vec<Texture> {
|
||||
vec![brick(), stone(), tech(), hellstone()]
|
||||
}
|
||||
|
||||
/// Classic red-brown brick: 16x8 bricks, offset every other row, mortar gaps.
|
||||
fn brick() -> Texture {
|
||||
let base: Rgb = [148, 64, 44];
|
||||
let mortar: Rgb = [78, 60, 54];
|
||||
let mut pixels = Vec::with_capacity(TEX_SIZE * TEX_SIZE);
|
||||
for y in 0..TEX_SIZE {
|
||||
for x in 0..TEX_SIZE {
|
||||
let row = y / 8;
|
||||
let off = if row % 2 == 0 { 0 } else { 8 };
|
||||
let in_mortar = y % 8 == 0 || (x + off) % 16 == 0;
|
||||
let c = if in_mortar {
|
||||
mortar
|
||||
} else {
|
||||
// Per-brick tone variation + per-pixel grain.
|
||||
let brick_id = (row as u32) * 31 + (((x + off) / 16) as u32);
|
||||
let tone = 0.82 + 0.30 * hash01(brick_id, 7, 1);
|
||||
let grain = 0.92 + 0.16 * hash01(x as u32, y as u32, 2);
|
||||
scale(base, tone * grain)
|
||||
};
|
||||
pixels.push(c);
|
||||
}
|
||||
}
|
||||
Texture { pixels }
|
||||
}
|
||||
|
||||
/// Large gray stone blocks with grout lines and noise.
|
||||
fn stone() -> Texture {
|
||||
let base: Rgb = [118, 118, 126];
|
||||
let grout: Rgb = [58, 58, 64];
|
||||
let mut pixels = Vec::with_capacity(TEX_SIZE * TEX_SIZE);
|
||||
for y in 0..TEX_SIZE {
|
||||
for x in 0..TEX_SIZE {
|
||||
let row = y / 16;
|
||||
let off = if row % 2 == 0 { 0 } else { 16 };
|
||||
let in_grout = y % 16 == 0 || (x + off) % 32 == 0;
|
||||
let c = if in_grout {
|
||||
grout
|
||||
} else {
|
||||
let block_id = (row as u32) * 17 + (((x + off) / 32) as u32);
|
||||
let tone = 0.80 + 0.28 * hash01(block_id, 3, 3);
|
||||
let grain = 0.90 + 0.20 * hash01(x as u32, y as u32, 4);
|
||||
scale(base, tone * grain)
|
||||
};
|
||||
pixels.push(c);
|
||||
}
|
||||
}
|
||||
Texture { pixels }
|
||||
}
|
||||
|
||||
/// Dark sci-fi metal panels with horizontal seams and green light strips.
|
||||
fn tech() -> Texture {
|
||||
let base: Rgb = [74, 82, 92];
|
||||
let seam: Rgb = [38, 42, 48];
|
||||
let light: Rgb = [110, 240, 130];
|
||||
let mut pixels = Vec::with_capacity(TEX_SIZE * TEX_SIZE);
|
||||
for y in 0..TEX_SIZE {
|
||||
for x in 0..TEX_SIZE {
|
||||
let in_seam = y % 16 == 0 || y % 16 == 15 || x % 32 == 0;
|
||||
// Blinking-looking light dots along the middle of each panel.
|
||||
let is_light =
|
||||
y % 16 == 8 && x % 8 == 4 && hash01((x / 8) as u32, (y / 16) as u32, 5) > 0.35;
|
||||
let c = if is_light {
|
||||
light
|
||||
} else if in_seam {
|
||||
seam
|
||||
} else {
|
||||
let grain = 0.88 + 0.22 * hash01(x as u32, y as u32, 6);
|
||||
scale(base, grain)
|
||||
};
|
||||
pixels.push(c);
|
||||
}
|
||||
}
|
||||
Texture { pixels }
|
||||
}
|
||||
|
||||
/// Floor: large worn stone tiles with grime patches, kept dark so the
|
||||
/// fog gradient toward the horizon reads naturally.
|
||||
pub(super) fn build_floor_texture() -> Texture {
|
||||
let base: Rgb = [96, 86, 74];
|
||||
let grout: Rgb = [44, 40, 36];
|
||||
let mut pixels = Vec::with_capacity(TEX_SIZE * TEX_SIZE);
|
||||
for y in 0..TEX_SIZE {
|
||||
for x in 0..TEX_SIZE {
|
||||
let in_grout = y % 32 == 0 || x % 32 == 0;
|
||||
let c = if in_grout {
|
||||
grout
|
||||
} else {
|
||||
let tile_id = (y / 32) as u32 * 5 + (x / 32) as u32;
|
||||
let tone = 0.78 + 0.30 * hash01(tile_id, 11, 9);
|
||||
// Grime: coarse blotches darken patches of the tile.
|
||||
let grime = if hash01((x / 6) as u32, (y / 6) as u32, 10) > 0.72 {
|
||||
0.78
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let grain = 0.90 + 0.20 * hash01(x as u32, y as u32, 11);
|
||||
scale(base, tone * grime * grain)
|
||||
};
|
||||
pixels.push(c);
|
||||
}
|
||||
}
|
||||
Texture { pixels }
|
||||
}
|
||||
|
||||
/// Ceiling: dark metal panels with sparse emissive light squares. The
|
||||
/// lights stay bright through fog shading simply by starting near white.
|
||||
pub(super) fn build_ceiling_texture() -> Texture {
|
||||
let base: Rgb = [52, 56, 66];
|
||||
let seam: Rgb = [30, 32, 38];
|
||||
let lamp: Rgb = [232, 226, 198];
|
||||
let mut pixels = Vec::with_capacity(TEX_SIZE * TEX_SIZE);
|
||||
for y in 0..TEX_SIZE {
|
||||
for x in 0..TEX_SIZE {
|
||||
let in_seam = y % 16 == 0 || x % 16 == 0;
|
||||
// One panel in ~6 carries a recessed lamp in its center.
|
||||
let panel = ((x / 16) as u32, (y / 16) as u32);
|
||||
let has_lamp = hash01(panel.0, panel.1, 12) > 0.84;
|
||||
let in_lamp = has_lamp && (4..12).contains(&(x % 16)) && (4..12).contains(&(y % 16));
|
||||
let c = if in_lamp {
|
||||
lamp
|
||||
} else if in_seam {
|
||||
seam
|
||||
} else {
|
||||
let grain = 0.88 + 0.20 * hash01(x as u32, y as u32, 13);
|
||||
scale(base, grain)
|
||||
};
|
||||
pixels.push(c);
|
||||
}
|
||||
}
|
||||
Texture { pixels }
|
||||
}
|
||||
|
||||
/// Dark red marbled "hell" stone for accent walls.
|
||||
fn hellstone() -> Texture {
|
||||
let base: Rgb = [120, 30, 28];
|
||||
let vein: Rgb = [200, 80, 50];
|
||||
let mut pixels = Vec::with_capacity(TEX_SIZE * TEX_SIZE);
|
||||
for y in 0..TEX_SIZE {
|
||||
for x in 0..TEX_SIZE {
|
||||
let fx = x as f32 / TEX_SIZE as f32;
|
||||
let fy = y as f32 / TEX_SIZE as f32;
|
||||
// Cheap marble: layered sine waves distorted by noise.
|
||||
let n = hash01((x / 4) as u32, (y / 4) as u32, 7);
|
||||
let v = ((fx * 9.0 + fy * 4.0 + n * 3.0).sin() * 0.5 + 0.5).powi(3);
|
||||
let grain = 0.85 + 0.25 * hash01(x as u32, y as u32, 8);
|
||||
let c = [
|
||||
(base[0] as f32 * (1.0 - v) + vein[0] as f32 * v) * grain,
|
||||
(base[1] as f32 * (1.0 - v) + vein[1] as f32 * v) * grain,
|
||||
(base[2] as f32 * (1.0 - v) + vein[2] as f32 * v) * grain,
|
||||
];
|
||||
pixels.push([c[0] as u8, c[1] as u8, c[2] as u8]);
|
||||
}
|
||||
}
|
||||
Texture { pixels }
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Sprite art (char-map pixel art)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// Map a sprite art character to a color. `.` is transparent.
|
||||
fn sprite_color(ch: u8) -> Option<Rgb> {
|
||||
match ch {
|
||||
b'.' => None,
|
||||
b'B' => Some([146, 90, 50]), // imp body, brown
|
||||
b'b' => Some([104, 62, 34]), // imp body, shaded
|
||||
b'H' => Some([222, 214, 188]), // horn / bone
|
||||
b'E' => Some(EYE_GLOW), // glowing eye (fog-exempt in renderer)
|
||||
b'M' => Some([34, 20, 16]), // mouth / dark recess
|
||||
b'T' => Some([236, 232, 220]), // teeth
|
||||
b'C' => Some([214, 196, 160]), // claw
|
||||
b'R' => Some([186, 28, 24]), // blood
|
||||
b'r' => Some([120, 16, 14]), // blood, dark
|
||||
b'G' => Some([96, 104, 112]), // gunmetal
|
||||
b'g' => Some([52, 58, 66]), // gunmetal, dark
|
||||
b'W' => Some([224, 228, 232]), // highlight
|
||||
b'S' => Some([212, 160, 116]), // skin
|
||||
b's' => Some([164, 116, 80]), // skin, shaded
|
||||
b'F' => Some([255, 244, 160]), // muzzle flash core
|
||||
b'f' => Some([255, 168, 48]), // muzzle flash fringe
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A char-map sprite: rows of equal length, `.` = transparent.
|
||||
pub(super) struct Sprite {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
pixels: Vec<Option<Rgb>>,
|
||||
}
|
||||
|
||||
impl Sprite {
|
||||
fn from_art(art: &[&str]) -> Self {
|
||||
let h = art.len();
|
||||
let w = art.first().map_or(0, |r| r.len());
|
||||
let mut pixels = Vec::with_capacity(w * h);
|
||||
for row in art {
|
||||
debug_assert_eq!(row.len(), w, "sprite rows must be equal length");
|
||||
for &ch in row.as_bytes() {
|
||||
pixels.push(sprite_color(ch));
|
||||
}
|
||||
}
|
||||
Self { w, h, pixels }
|
||||
}
|
||||
|
||||
/// Sample with normalized coordinates in `[0, 1)`.
|
||||
#[inline]
|
||||
pub fn sample(&self, u: f32, v: f32) -> Option<Rgb> {
|
||||
let x = ((u * self.w as f32) as usize).min(self.w - 1);
|
||||
let y = ((v * self.h as f32) as usize).min(self.h - 1);
|
||||
self.pixels[y * self.w + x]
|
||||
}
|
||||
}
|
||||
|
||||
/// Imp frame set, indexed by [`super::game::ImpVisual`].
|
||||
pub(super) struct ImpSprites {
|
||||
pub walk_a: Sprite,
|
||||
pub walk_b: Sprite,
|
||||
pub attack: Sprite,
|
||||
pub pain: Sprite,
|
||||
pub die_a: Sprite,
|
||||
pub die_b: Sprite,
|
||||
pub corpse: Sprite,
|
||||
}
|
||||
|
||||
pub(super) fn build_imp_sprites() -> ImpSprites {
|
||||
// 16x20 horned demon. Two walk frames differ in leg/arm pose.
|
||||
let walk_a = Sprite::from_art(&[
|
||||
"..H..........H..",
|
||||
"..HH........HH..",
|
||||
"...bBBBBBBBBb...",
|
||||
"...BBBBBBBBBB...",
|
||||
"..BBEEBBBBEEBB..",
|
||||
"..BBEEBBBBEEBB..",
|
||||
"...BBBBBBBBBB...",
|
||||
"...BbMTMTMTbB...",
|
||||
"....bBBBBBBb....",
|
||||
"..bBBBBBBBBBBb..",
|
||||
".CBBb.BBBB.bBBC.",
|
||||
".CBB..BBBB..BBC.",
|
||||
".CC...BBBB...CC.",
|
||||
"......bBBb......",
|
||||
".....BB..BB.....",
|
||||
"....BB....BB....",
|
||||
"....BB.....BB...",
|
||||
"...bB.......Bb..",
|
||||
"...BB.......BB..",
|
||||
"..CC.........CC.",
|
||||
]);
|
||||
let walk_b = Sprite::from_art(&[
|
||||
"..H..........H..",
|
||||
"..HH........HH..",
|
||||
"...bBBBBBBBBb...",
|
||||
"...BBBBBBBBBB...",
|
||||
"..BBEEBBBBEEBB..",
|
||||
"..BBEEBBBBEEBB..",
|
||||
"...BBBBBBBBBB...",
|
||||
"...BbMTMTMTbB...",
|
||||
"....bBBBBBBb....",
|
||||
"..bBBBBBBBBBBb..",
|
||||
".CBBb.BBBB.bBBC.",
|
||||
".CBB..BBBB..BBC.",
|
||||
".CC...BBBB...CC.",
|
||||
"......bBBb......",
|
||||
".....BB..BB.....",
|
||||
"....BB.....BB...",
|
||||
"...BB.......BB..",
|
||||
"...Bb.......bB..",
|
||||
"...BB........BB.",
|
||||
"..CC..........CC",
|
||||
]);
|
||||
// Arms raised overhead, mouth wide.
|
||||
let attack = Sprite::from_art(&[
|
||||
".CC.H......H.CC.",
|
||||
".CBBHH....HHBBC.",
|
||||
".CBBbBBBBBBbBBC.",
|
||||
"..BBBBBBBBBBBB..",
|
||||
"..BBEEBBBBEEBB..",
|
||||
"..bBEEBBBBEEBb..",
|
||||
"...BBBBBBBBBB...",
|
||||
"...BbMMMMMMbB...",
|
||||
"...BbMTMTMTbB...",
|
||||
"....bBBBBBBb....",
|
||||
"...BBBBBBBBBB...",
|
||||
"...BBBBBBBBBB...",
|
||||
"....BBBBBBBB....",
|
||||
"......bBBb......",
|
||||
".....BB..BB.....",
|
||||
"....BB....BB....",
|
||||
"....BB....BB....",
|
||||
"...bB......Bb...",
|
||||
"...BB......BB...",
|
||||
"..CC........CC..",
|
||||
]);
|
||||
// Flinching: head tilted, eyes shut, blood.
|
||||
let pain = Sprite::from_art(&[
|
||||
"....H......H....",
|
||||
"...HH.....HH....",
|
||||
"..bBBBBBBBBb....",
|
||||
".RBBBBBBBBBB....",
|
||||
".RBBMMBBBMMBB...",
|
||||
"..rBBBBBBBBBR...",
|
||||
"...BBBBBBBBBB...",
|
||||
"...BbMMMMMMbB...",
|
||||
"....bBBBBBBbR...",
|
||||
"..bBBBBBBBBBBb..",
|
||||
".CBBb.BBBB.bBBC.",
|
||||
".CBB..BBBB..BBC.",
|
||||
".CC...BBBB...CC.",
|
||||
"......bBBb......",
|
||||
".....BB..BB.....",
|
||||
"....BB....BB....",
|
||||
"....BB....BB....",
|
||||
"...bB......Bb...",
|
||||
"...BB......BB...",
|
||||
"..CC........CC..",
|
||||
]);
|
||||
// Collapsing forward.
|
||||
let die_a = Sprite::from_art(&[
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"...H........H...",
|
||||
"...HHBBBBBBHH...",
|
||||
"..bBBBBBBBBBBb..",
|
||||
"..RBMMBBBBMMBR..",
|
||||
"..rBBBBBBBBBBr..",
|
||||
"...BbMMMMMMbB...",
|
||||
"..RbBBBBBBBBbR..",
|
||||
".CBBBBBBBBBBBBC.",
|
||||
".CBb.BBBBBB.bBC.",
|
||||
".CC..BBBBBB..CC.",
|
||||
"....bBBBBBBb....",
|
||||
"...RBB....BBR...",
|
||||
"...BB......BB...",
|
||||
"..rB........Br..",
|
||||
"..BB........BB..",
|
||||
".RCC........CCR.",
|
||||
"................",
|
||||
]);
|
||||
let die_b = Sprite::from_art(&[
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"....H......H....",
|
||||
"...HHBBBBBHH....",
|
||||
"..RbBBBBBBBbR...",
|
||||
"..rBMMBBBMMBr...",
|
||||
"..RBBBBBBBBBR...",
|
||||
".RbBBBBBBBBBbR..",
|
||||
".CBBBBBBBBBBBC..",
|
||||
".CBbRBBBBBBRbC..",
|
||||
"..RR.BBBBB.RR...",
|
||||
"...RbBBBBBbR....",
|
||||
"..RRBBBBBBRR....",
|
||||
".rRRRbBBbRRRr...",
|
||||
"................",
|
||||
]);
|
||||
// Flat smear on the floor.
|
||||
let corpse = Sprite::from_art(&[
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"................",
|
||||
"....rr..r.......",
|
||||
"..rRRrrRRr.r....",
|
||||
".rRbBBBBbRRrr...",
|
||||
"rRRBbHbBBbRRRr..",
|
||||
".rrRRbBBbRRrr...",
|
||||
"..r.rRRRRr.r....",
|
||||
"................",
|
||||
]);
|
||||
ImpSprites {
|
||||
walk_a,
|
||||
walk_b,
|
||||
attack,
|
||||
pain,
|
||||
die_a,
|
||||
die_b,
|
||||
corpse,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gun frame set (drawn bottom-center, view-model style).
|
||||
pub(super) struct GunSprites {
|
||||
pub idle: Sprite,
|
||||
pub fire: Sprite,
|
||||
}
|
||||
|
||||
pub(super) fn build_gun_sprites() -> GunSprites {
|
||||
// 24x18 pistol held in a gloved hand, slightly right of center.
|
||||
let idle = Sprite::from_art(&[
|
||||
"........................",
|
||||
"..........WGG...........",
|
||||
".........GGGGG..........",
|
||||
".........gGGGGg.........",
|
||||
".........gGGGGg.........",
|
||||
".........gGGGGg.........",
|
||||
"........gGGGGGGg........",
|
||||
"........gGGGGGGg........",
|
||||
".......gGGGGGGGGg.......",
|
||||
".......sSGGGGGGSs.......",
|
||||
"......sSSSGGGGSSSs......",
|
||||
".....sSSSSSGGSSSSSs.....",
|
||||
"....sSSSSSSSSSSSSSSs....",
|
||||
"....sSSSSSSSSSSSSSs.....",
|
||||
"...sSSSSSSSSSSSSSSs.....",
|
||||
"...sSSSSSSSSSSSSSs......",
|
||||
"..sSSSSSSSSSSSSSSs......",
|
||||
"..sSSSSSSSSSSSSSs.......",
|
||||
]);
|
||||
let fire = Sprite::from_art(&[
|
||||
".........fFFf...........",
|
||||
"........fFFFFf..........",
|
||||
".......fFFFFFFf.........",
|
||||
"........fFFFFf..........",
|
||||
".........FGGF...........",
|
||||
".........gGGGGg.........",
|
||||
"........gGGGGGGg........",
|
||||
"........gGGGGGGg........",
|
||||
".......gGGGGGGGGg.......",
|
||||
".......sSGGGGGGSs.......",
|
||||
"......sSSSGGGGSSSs......",
|
||||
".....sSSSSSGGSSSSSs.....",
|
||||
"....sSSSSSSSSSSSSSSs....",
|
||||
"....sSSSSSSSSSSSSSs.....",
|
||||
"...sSSSSSSSSSSSSSSs.....",
|
||||
"...sSSSSSSSSSSSSSs......",
|
||||
"..sSSSSSSSSSSSSSSs......",
|
||||
"..sSSSSSSSSSSSSSs.......",
|
||||
]);
|
||||
GunSprites { idle, fire }
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 5x7 pixel font (uppercase + the few symbols the game needs)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// Return the 5x7 glyph rows for a character, MSB-left in the low 5 bits.
|
||||
/// Unknown characters render as blank.
|
||||
pub(super) fn glyph5x7(ch: char) -> [u8; 7] {
|
||||
match ch.to_ascii_uppercase() {
|
||||
'A' => [
|
||||
0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
|
||||
],
|
||||
'B' => [
|
||||
0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110,
|
||||
],
|
||||
'C' => [
|
||||
0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110,
|
||||
],
|
||||
'D' => [
|
||||
0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110,
|
||||
],
|
||||
'E' => [
|
||||
0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111,
|
||||
],
|
||||
'G' => [
|
||||
0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01111,
|
||||
],
|
||||
'H' => [
|
||||
0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
|
||||
],
|
||||
'I' => [
|
||||
0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b11111,
|
||||
],
|
||||
'K' => [
|
||||
0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001,
|
||||
],
|
||||
'L' => [
|
||||
0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111,
|
||||
],
|
||||
'M' => [
|
||||
0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001,
|
||||
],
|
||||
'N' => [
|
||||
0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001,
|
||||
],
|
||||
'O' => [
|
||||
0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
|
||||
],
|
||||
'P' => [
|
||||
0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000,
|
||||
],
|
||||
'R' => [
|
||||
0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001,
|
||||
],
|
||||
'S' => [
|
||||
0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110,
|
||||
],
|
||||
'T' => [
|
||||
0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100,
|
||||
],
|
||||
'U' => [
|
||||
0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
|
||||
],
|
||||
'V' => [
|
||||
0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100,
|
||||
],
|
||||
'Y' => [
|
||||
0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100,
|
||||
],
|
||||
'!' => [
|
||||
0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00000, 0b00100,
|
||||
],
|
||||
'-' => [
|
||||
0b00000, 0b00000, 0b00000, 0b01110, 0b00000, 0b00000, 0b00000,
|
||||
],
|
||||
_ => [0; 7],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn textures_have_expected_size() {
|
||||
for tex in build_textures() {
|
||||
assert_eq!(tex.pixels.len(), TEX_SIZE * TEX_SIZE);
|
||||
}
|
||||
assert_eq!(build_floor_texture().pixels.len(), TEX_SIZE * TEX_SIZE);
|
||||
assert_eq!(build_ceiling_texture().pixels.len(), TEX_SIZE * TEX_SIZE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xorshift_is_nondegenerate() {
|
||||
// Zero seed must not collapse to the all-zero fixed point.
|
||||
let mut rng = XorShift64::new(0);
|
||||
assert!((0..4).map(|_| rng.next_u32()).any(|v| v != 0));
|
||||
// Floats stay in [0, 1).
|
||||
let mut rng = XorShift64::new(42);
|
||||
for _ in 0..1000 {
|
||||
let f = rng.next_f32();
|
||||
assert!((0.0..1.0).contains(&f));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_sprite_palette_char_is_used_in_art() {
|
||||
// Keep the palette free of dead entries: every mapped char's color
|
||||
// must appear in at least one sprite. Palette colors are distinct,
|
||||
// so matching on color is equivalent to matching on char.
|
||||
let mut used: std::collections::HashSet<Rgb> = std::collections::HashSet::new();
|
||||
let imps = build_imp_sprites();
|
||||
let guns = build_gun_sprites();
|
||||
for sprite in [
|
||||
&imps.walk_a,
|
||||
&imps.walk_b,
|
||||
&imps.attack,
|
||||
&imps.pain,
|
||||
&imps.die_a,
|
||||
&imps.die_b,
|
||||
&imps.corpse,
|
||||
&guns.idle,
|
||||
&guns.fire,
|
||||
] {
|
||||
used.extend(sprite.pixels.iter().flatten());
|
||||
}
|
||||
for ch in b"BbHEMTCRrGgWSsFf" {
|
||||
let color = sprite_color(*ch).expect("palette char must map to a color");
|
||||
assert!(
|
||||
used.contains(&color),
|
||||
"palette char {:?} is mapped but unused in art",
|
||||
*ch as char
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sprites_have_consistent_rows() {
|
||||
// Construction debug-asserts equal row lengths; touch every frame.
|
||||
let imps = build_imp_sprites();
|
||||
for s in [
|
||||
&imps.walk_a,
|
||||
&imps.walk_b,
|
||||
&imps.attack,
|
||||
&imps.pain,
|
||||
&imps.die_a,
|
||||
&imps.die_b,
|
||||
&imps.corpse,
|
||||
] {
|
||||
assert_eq!(s.w, 16);
|
||||
assert_eq!(s.h, 20);
|
||||
// Sampling corners must not panic.
|
||||
let _ = s.sample(0.0, 0.0);
|
||||
let _ = s.sample(0.999, 0.999);
|
||||
}
|
||||
let guns = build_gun_sprites();
|
||||
assert_eq!(guns.idle.w, 24);
|
||||
assert_eq!(guns.fire.w, 24);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_covers_required_strings() {
|
||||
// Every character used by in-game screens must have a glyph.
|
||||
for text in [
|
||||
"GBOOM",
|
||||
"KNEE-DEEP IN THE TOKENS",
|
||||
"PRESS ANY KEY",
|
||||
"YOU DIED",
|
||||
"VICTORY!",
|
||||
] {
|
||||
for ch in text.chars().filter(|c| *c != ' ') {
|
||||
assert_ne!(
|
||||
glyph5x7(ch),
|
||||
[0; 7],
|
||||
"missing glyph for {ch:?} used in {text:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,728 @@
|
||||
//! Software renderer for the `/gboom` easter egg.
|
||||
//!
|
||||
//! Grid raycaster (Lodev-style DDA): textured walls, floor, and ceiling
|
||||
//! with distance fog, billboard sprites with a 1D depth buffer, a
|
||||
//! view-model gun, and full-frame effects (muzzle light, damage flash,
|
||||
//! vignette). Also renders the title/end screens (animated fire + text).
|
||||
//!
|
||||
//! Everything draws into a plain RGB8 framebuffer the caller PNG-encodes
|
||||
//! for the kitty graphics protocol.
|
||||
|
||||
use super::assets::{self, GunSprites, ImpSprites, Rgb, TEX_SIZE, Texture, XorShift64};
|
||||
use super::game::{Game, ImpVisual};
|
||||
|
||||
/// Distance fog factor: shade = 1 / (1 + dist * FOG).
|
||||
const FOG: f32 = 0.16;
|
||||
/// Sprite height in world units (walls are 1.0 tall).
|
||||
const IMP_WORLD_HEIGHT: f32 = 0.72;
|
||||
/// Camera half-FOV tangent (0.66 ≈ the classic 66° FOV).
|
||||
const PLANE_LEN: f32 = 0.66;
|
||||
/// Corner-vignette strength (0 = none); subtle, ~0.8 at the extreme corners.
|
||||
const VIGNETTE: f32 = 0.11;
|
||||
|
||||
/// RGB framebuffer with reusable scratch buffers.
|
||||
pub(super) struct FrameBuffer {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
pub pixels: Vec<u8>, // RGB8, row-major
|
||||
zbuf: Vec<f32>, // per-column wall depth
|
||||
/// Per-column wall strip bounds `[top, bottom)` in screen rows, written
|
||||
/// by `draw_walls` and read by `draw_floor_ceiling` to skip the pixels
|
||||
/// walls already cover (avoids texturing them twice).
|
||||
wall_top: Vec<i32>,
|
||||
wall_bottom: Vec<i32>,
|
||||
/// Scratch for painter's-order sprite sorting, reused across frames.
|
||||
sprite_order: Vec<(usize, f32)>,
|
||||
/// Separable vignette factors, rebuilt on dimension change.
|
||||
vig_x: Vec<f32>,
|
||||
vig_y: Vec<f32>,
|
||||
}
|
||||
|
||||
impl FrameBuffer {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
w: 0,
|
||||
h: 0,
|
||||
pixels: Vec::new(),
|
||||
zbuf: Vec::new(),
|
||||
wall_top: Vec::new(),
|
||||
wall_bottom: Vec::new(),
|
||||
sprite_order: Vec::new(),
|
||||
vig_x: Vec::new(),
|
||||
vig_y: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resize(&mut self, w: usize, h: usize) {
|
||||
if self.w == w && self.h == h {
|
||||
return;
|
||||
}
|
||||
self.w = w;
|
||||
self.h = h;
|
||||
self.pixels.resize(w * h * 3, 0);
|
||||
self.zbuf.resize(w, f32::MAX);
|
||||
self.wall_top.resize(w, 0);
|
||||
self.wall_bottom.resize(w, 0);
|
||||
let axis = |i: usize, n: usize| {
|
||||
let t = if n <= 1 {
|
||||
0.0
|
||||
} else {
|
||||
2.0 * i as f32 / (n - 1) as f32 - 1.0
|
||||
};
|
||||
1.0 - VIGNETTE * t * t
|
||||
};
|
||||
self.vig_x = (0..w).map(|x| axis(x, w)).collect();
|
||||
self.vig_y = (0..h).map(|y| axis(y, h)).collect();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn put(&mut self, x: usize, y: usize, c: Rgb) {
|
||||
let i = (y * self.w + x) * 3;
|
||||
self.pixels[i] = c[0];
|
||||
self.pixels[i + 1] = c[1];
|
||||
self.pixels[i + 2] = c[2];
|
||||
}
|
||||
|
||||
/// Multiply the pixel at `(x, y)` by `f` (used for sprite shadows).
|
||||
#[inline]
|
||||
fn darken(&mut self, x: usize, y: usize, f: f32) {
|
||||
let i = (y * self.w + x) * 3;
|
||||
self.pixels[i] = (self.pixels[i] as f32 * f) as u8;
|
||||
self.pixels[i + 1] = (self.pixels[i + 1] as f32 * f) as u8;
|
||||
self.pixels[i + 2] = (self.pixels[i + 2] as f32 * f) as u8;
|
||||
}
|
||||
|
||||
/// Darken the frame toward the corners. Applied to the world (before
|
||||
/// the view-model gun, which stays crisp).
|
||||
fn apply_vignette(&mut self) {
|
||||
for y in 0..self.h {
|
||||
let vy = self.vig_y[y];
|
||||
let row = &mut self.pixels[y * self.w * 3..(y + 1) * self.w * 3];
|
||||
for (x, px) in row.chunks_exact_mut(3).enumerate() {
|
||||
let f = self.vig_x[x] * vy;
|
||||
px[0] = (px[0] as f32 * f) as u8;
|
||||
px[1] = (px[1] as f32 * f) as u8;
|
||||
px[2] = (px[2] as f32 * f) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn shade(c: Rgb, f: f32) -> Rgb {
|
||||
[
|
||||
(c[0] as f32 * f).min(255.0) as u8,
|
||||
(c[1] as f32 * f).min(255.0) as u8,
|
||||
(c[2] as f32 * f).min(255.0) as u8,
|
||||
]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn lerp_color(a: Rgb, b: Rgb, t: f32) -> Rgb {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
[
|
||||
(a[0] as f32 + (b[0] as f32 - a[0] as f32) * t) as u8,
|
||||
(a[1] as f32 + (b[1] as f32 - a[1] as f32) * t) as u8,
|
||||
(a[2] as f32 + (b[2] as f32 - a[2] as f32) * t) as u8,
|
||||
]
|
||||
}
|
||||
|
||||
/// All immutable render resources, built once per game.
|
||||
pub(super) struct Renderer {
|
||||
textures: Vec<Texture>,
|
||||
floor: Texture,
|
||||
ceiling: Texture,
|
||||
imps: ImpSprites,
|
||||
guns: GunSprites,
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
textures: assets::build_textures(),
|
||||
floor: assets::build_floor_texture(),
|
||||
ceiling: assets::build_ceiling_texture(),
|
||||
imps: assets::build_imp_sprites(),
|
||||
guns: assets::build_gun_sprites(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Render one gameplay frame into `fb`.
|
||||
pub fn render_game(&self, fb: &mut FrameBuffer, game: &Game) {
|
||||
let (w, h) = (fb.w, fb.h);
|
||||
if w == 0 || h == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
// Muzzle flash briefly lights the whole scene.
|
||||
let light_boost = if game.player.muzzle > 0.0 { 1.35 } else { 1.0 };
|
||||
|
||||
// Walls first: they record per-column strip bounds + depth, letting
|
||||
// the floor/ceiling pass skip the pixels they cover (no double-write).
|
||||
self.draw_walls(fb, game, light_boost);
|
||||
self.draw_floor_ceiling(fb, game, light_boost);
|
||||
self.draw_imps(fb, game, light_boost);
|
||||
// World-only vignette: the view-model gun stays crisp on top.
|
||||
fb.apply_vignette();
|
||||
self.draw_gun(fb, game);
|
||||
|
||||
// Damage flash: flat blend of the whole frame toward red, decaying
|
||||
// with `damage_flash`. Reads clearly even at low resolutions.
|
||||
if game.player.damage_flash > 0.0 {
|
||||
let t = (game.player.damage_flash * 0.45).min(0.45);
|
||||
for px in fb.pixels.chunks_exact_mut(3) {
|
||||
px[0] = (px[0] as f32 + (220.0 - px[0] as f32) * t) as u8;
|
||||
px[1] = (px[1] as f32 * (1.0 - t * 0.8)) as u8;
|
||||
px[2] = (px[2] as f32 * (1.0 - t * 0.8)) as u8;
|
||||
}
|
||||
}
|
||||
// Low-health vignette pulse.
|
||||
if game.player.hp <= 25 && !game.dead() {
|
||||
let pulse = 0.10 + 0.06 * (game.time * 5.0).sin();
|
||||
for px in fb.pixels.chunks_exact_mut(3) {
|
||||
px[0] = (px[0] as f32 + (160.0 - px[0] as f32) * pulse) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Perspective-correct textured floor and ceiling (Lodev scanline
|
||||
/// casting): each screen row below/above the horizon maps to one
|
||||
/// world-space distance, so texels are sampled by stepping world
|
||||
/// coordinates across the row. Distance fog matches the wall pass,
|
||||
/// making the whole scene recede uniformly into darkness.
|
||||
///
|
||||
/// Runs after `draw_walls` and skips pixels inside each column's wall
|
||||
/// strip — the world coords still step every pixel (to stay aligned),
|
||||
/// but the texture sample/shade/write are elided where a wall covers.
|
||||
fn draw_floor_ceiling(&self, fb: &mut FrameBuffer, game: &Game, light: f32) {
|
||||
let (w, h) = (fb.w, fb.h);
|
||||
let p = &game.player;
|
||||
let (dir_x, dir_y) = p.dir();
|
||||
let (plane_x, plane_y) = (-dir_y * PLANE_LEN, dir_x * PLANE_LEN);
|
||||
|
||||
// Leftmost and rightmost camera rays of the view frustum.
|
||||
let (ray0_x, ray0_y) = (dir_x - plane_x, dir_y - plane_y);
|
||||
let (ray1_x, ray1_y) = (dir_x + plane_x, dir_y + plane_y);
|
||||
let cam_z = 0.5 * h as f32;
|
||||
|
||||
for y in h / 2..h {
|
||||
// Rows at the horizon map to (near-)infinite distance.
|
||||
let row = (y - h / 2).max(1) as f32;
|
||||
let row_dist = cam_z / row;
|
||||
let fog = (1.0 / (1.0 + row_dist * FOG)) * light;
|
||||
|
||||
let step_x = row_dist * (ray1_x - ray0_x) / w as f32;
|
||||
let step_y = row_dist * (ray1_y - ray0_y) / w as f32;
|
||||
let mut world_x = p.x + row_dist * ray0_x;
|
||||
let mut world_y = p.y + row_dist * ray0_y;
|
||||
|
||||
// The ceiling row at the same distance mirrors across the
|
||||
// horizon (camera eye is at half wall height).
|
||||
let ceil_y = h - 1 - y;
|
||||
let (yi, ceil_yi) = (y as i32, ceil_y as i32);
|
||||
for x in 0..w {
|
||||
let (wx, wy) = (world_x, world_y);
|
||||
world_x += step_x;
|
||||
world_y += step_y;
|
||||
|
||||
// Skip pixels the wall strip already filled this column. The
|
||||
// texel coords are computed lazily, so the central wall band
|
||||
// (where both are covered) costs only the world-coord step.
|
||||
let floor_vis = yi >= fb.wall_bottom[x];
|
||||
let ceil_vis = ceil_yi < fb.wall_top[x];
|
||||
if !(floor_vis || ceil_vis) {
|
||||
continue;
|
||||
}
|
||||
let tx = (wx.rem_euclid(1.0) * TEX_SIZE as f32) as usize;
|
||||
let ty = (wy.rem_euclid(1.0) * TEX_SIZE as f32) as usize;
|
||||
if floor_vis {
|
||||
fb.put(x, y, shade(self.floor.sample(tx, ty), fog));
|
||||
}
|
||||
if ceil_vis {
|
||||
fb.put(x, ceil_y, shade(self.ceiling.sample(tx, ty), fog));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_walls(&self, fb: &mut FrameBuffer, game: &Game, light: f32) {
|
||||
let (w, h) = (fb.w, fb.h);
|
||||
let p = &game.player;
|
||||
let (dir_x, dir_y) = p.dir();
|
||||
let (plane_x, plane_y) = (-dir_y * PLANE_LEN, dir_x * PLANE_LEN);
|
||||
|
||||
for x in 0..w {
|
||||
let camera_x = 2.0 * x as f32 / w as f32 - 1.0;
|
||||
let rd_x = dir_x + plane_x * camera_x;
|
||||
let rd_y = dir_y + plane_y * camera_x;
|
||||
|
||||
let mut map_x = p.x.floor() as i32;
|
||||
let mut map_y = p.y.floor() as i32;
|
||||
let delta_x = if rd_x == 0.0 {
|
||||
f32::MAX
|
||||
} else {
|
||||
(1.0 / rd_x).abs()
|
||||
};
|
||||
let delta_y = if rd_y == 0.0 {
|
||||
f32::MAX
|
||||
} else {
|
||||
(1.0 / rd_y).abs()
|
||||
};
|
||||
let (step_x, mut side_x) = if rd_x < 0.0 {
|
||||
(-1, (p.x - map_x as f32) * delta_x)
|
||||
} else {
|
||||
(1, (map_x as f32 + 1.0 - p.x) * delta_x)
|
||||
};
|
||||
let (step_y, mut side_y) = if rd_y < 0.0 {
|
||||
(-1, (p.y - map_y as f32) * delta_y)
|
||||
} else {
|
||||
(1, (map_y as f32 + 1.0 - p.y) * delta_y)
|
||||
};
|
||||
|
||||
// DDA until a solid cell. The map border is fully solid, so
|
||||
// bound the loop defensively rather than trusting it blindly.
|
||||
let mut side = 0;
|
||||
let mut tex_id = 1u8;
|
||||
for _ in 0..256 {
|
||||
if side_x < side_y {
|
||||
side_x += delta_x;
|
||||
map_x += step_x;
|
||||
side = 0;
|
||||
} else {
|
||||
side_y += delta_y;
|
||||
map_y += step_y;
|
||||
side = 1;
|
||||
}
|
||||
let cell = game.map.cell(map_x, map_y);
|
||||
if cell != 0 {
|
||||
tex_id = cell;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let perp = if side == 0 {
|
||||
(map_x as f32 - p.x + (1 - step_x) as f32 / 2.0) / rd_x
|
||||
} else {
|
||||
(map_y as f32 - p.y + (1 - step_y) as f32 / 2.0) / rd_y
|
||||
};
|
||||
let perp = perp.max(1e-4);
|
||||
fb.zbuf[x] = perp;
|
||||
|
||||
let line_h = (h as f32 / perp) as i32;
|
||||
let draw_start = ((h as i32 - line_h) / 2).max(0);
|
||||
let draw_end = ((h as i32 + line_h) / 2).min(h as i32);
|
||||
// Record the strip so draw_floor_ceiling skips these rows.
|
||||
fb.wall_top[x] = draw_start;
|
||||
fb.wall_bottom[x] = draw_end;
|
||||
|
||||
// Texture column.
|
||||
let wall_x = if side == 0 {
|
||||
p.y + perp * rd_y
|
||||
} else {
|
||||
p.x + perp * rd_x
|
||||
};
|
||||
let wall_x = wall_x - wall_x.floor();
|
||||
let mut tex_x = (wall_x * TEX_SIZE as f32) as usize;
|
||||
if (side == 0 && rd_x > 0.0) || (side == 1 && rd_y < 0.0) {
|
||||
tex_x = TEX_SIZE - 1 - tex_x.min(TEX_SIZE - 1);
|
||||
}
|
||||
|
||||
let texture = &self.textures[(tex_id as usize - 1).min(self.textures.len() - 1)];
|
||||
let side_shade = if side == 1 { 0.72 } else { 1.0 };
|
||||
let fog_shade = (1.0 / (1.0 + perp * FOG)) * side_shade * light;
|
||||
|
||||
let tex_step = TEX_SIZE as f32 / line_h.max(1) as f32;
|
||||
let mut tex_pos = (draw_start as f32 - h as f32 / 2.0 + line_h as f32 / 2.0) * tex_step;
|
||||
for y in draw_start..draw_end {
|
||||
let tex_y = (tex_pos as usize).min(TEX_SIZE - 1);
|
||||
tex_pos += tex_step;
|
||||
let c = shade(texture.sample(tex_x, tex_y), fog_shade);
|
||||
fb.put(x, y as usize, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_imps(&self, fb: &mut FrameBuffer, game: &Game, light: f32) {
|
||||
let (w, h) = (fb.w, fb.h);
|
||||
let p = &game.player;
|
||||
let (dir_x, dir_y) = p.dir();
|
||||
let (plane_x, plane_y) = (-dir_y * PLANE_LEN, dir_x * PLANE_LEN);
|
||||
let inv_det = 1.0 / (plane_x * dir_y - dir_x * plane_y);
|
||||
|
||||
// Painter's order: far → near. The order buffer lives on the
|
||||
// framebuffer so the 30 fps render loop stays allocation-free;
|
||||
// it is taken out for the duration of the draw because the loop
|
||||
// body needs `fb` mutably.
|
||||
let mut order = std::mem::take(&mut fb.sprite_order);
|
||||
order.clear();
|
||||
order.extend(game.imps.iter().enumerate().map(|(i, imp)| {
|
||||
let d2 = (imp.x - p.x).powi(2) + (imp.y - p.y).powi(2);
|
||||
(i, d2)
|
||||
}));
|
||||
order.sort_unstable_by(|a, b| b.1.total_cmp(&a.1));
|
||||
|
||||
for &(i, _) in &order {
|
||||
let imp = &game.imps[i];
|
||||
let rel_x = imp.x - p.x;
|
||||
let rel_y = imp.y - p.y;
|
||||
// Camera-space transform: ty = forward depth, tx = lateral.
|
||||
let tx = inv_det * (dir_y * rel_x - dir_x * rel_y);
|
||||
let ty = inv_det * (-plane_y * rel_x + plane_x * rel_y);
|
||||
if ty <= 0.08 {
|
||||
continue; // behind or on top of the camera
|
||||
}
|
||||
|
||||
let sprite = match imp.visual() {
|
||||
ImpVisual::WalkA => &self.imps.walk_a,
|
||||
ImpVisual::WalkB => &self.imps.walk_b,
|
||||
ImpVisual::Attack => &self.imps.attack,
|
||||
ImpVisual::Pain => &self.imps.pain,
|
||||
ImpVisual::DieA => &self.imps.die_a,
|
||||
ImpVisual::DieB => &self.imps.die_b,
|
||||
ImpVisual::Corpse => &self.imps.corpse,
|
||||
};
|
||||
|
||||
let screen_x = (w as f32 / 2.0) * (1.0 + tx / ty);
|
||||
// Vertical span from world heights [0, IMP_WORLD_HEIGHT] with the
|
||||
// camera eye at 0.5: y(world_z) = h/2 + (0.5 - z) * h / ty.
|
||||
let y_feet = h as f32 / 2.0 + 0.5 * h as f32 / ty;
|
||||
let y_head = h as f32 / 2.0 + (0.5 - IMP_WORLD_HEIGHT) * h as f32 / ty;
|
||||
let sprite_h = (y_feet - y_head).max(1.0);
|
||||
let sprite_w = sprite_h * sprite.w as f32 / sprite.h as f32;
|
||||
|
||||
// Small vertical bob while walking sells the gait.
|
||||
let bob_px = imp.walk_bob().map_or(0.0, |phase| phase * sprite_h * 0.02);
|
||||
|
||||
let x0 = (screen_x - sprite_w / 2.0).floor() as i32;
|
||||
let x1 = (screen_x + sprite_w / 2.0).ceil() as i32;
|
||||
let y0 = (y_head + bob_px).floor() as i32;
|
||||
let y1 = (y_feet + bob_px).ceil() as i32;
|
||||
|
||||
let fog_shade = (1.0 / (1.0 + ty * FOG)) * light;
|
||||
|
||||
// Soft elliptical contact shadow under standing demons. Drawn
|
||||
// before the body, z-tested per column like the body.
|
||||
if !matches!(imp.visual(), ImpVisual::Corpse) {
|
||||
draw_contact_shadow(fb, screen_x, y_feet, sprite_w, sprite_h, ty);
|
||||
}
|
||||
|
||||
// Pain frames flash toward white so hits register instantly.
|
||||
let pain_flash = imp.visual() == ImpVisual::Pain;
|
||||
|
||||
for sx in x0.max(0)..x1.min(w as i32) {
|
||||
if fb.zbuf[sx as usize] <= ty {
|
||||
continue; // occluded by a wall
|
||||
}
|
||||
let u = (sx as f32 - x0 as f32) / (x1 - x0).max(1) as f32;
|
||||
for sy in y0.max(0)..y1.min(h as i32) {
|
||||
let v = (sy as f32 - y0 as f32) / (y1 - y0).max(1) as f32;
|
||||
if let Some(c) = sprite.sample(u, v) {
|
||||
// Glowing eyes ignore fog; everything else fades.
|
||||
let mut lit = if c == assets::EYE_GLOW {
|
||||
c
|
||||
} else {
|
||||
shade(c, fog_shade)
|
||||
};
|
||||
if pain_flash {
|
||||
lit = lerp_color(lit, [255, 255, 255], 0.40);
|
||||
}
|
||||
fb.put(sx as usize, sy as usize, lit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fb.sprite_order = order;
|
||||
}
|
||||
|
||||
fn draw_gun(&self, fb: &mut FrameBuffer, game: &Game) {
|
||||
let (w, h) = (fb.w, fb.h);
|
||||
let sprite = if game.player.muzzle > 0.0 {
|
||||
&self.guns.fire
|
||||
} else {
|
||||
&self.guns.idle
|
||||
};
|
||||
|
||||
// Gun occupies ~42% of frame height, bottom-center, with walk bob.
|
||||
let gun_h = (h as f32 * 0.42) as i32;
|
||||
let gun_w = gun_h * sprite.w as i32 / sprite.h as i32;
|
||||
let bob_x = (game.player.bob * 1.7).sin() * w as f32 * 0.012;
|
||||
let bob_y = (game.player.bob * 3.4).cos().abs() * h as f32 * 0.018;
|
||||
let x0 = w as i32 / 2 - gun_w / 2 + bob_x as i32;
|
||||
let y0 = h as i32 - gun_h + bob_y as i32;
|
||||
|
||||
for sy in y0.max(0)..h as i32 {
|
||||
let v = (sy - y0) as f32 / gun_h.max(1) as f32;
|
||||
for sx in x0.max(0)..(x0 + gun_w).min(w as i32) {
|
||||
let u = (sx - x0) as f32 / gun_w.max(1) as f32;
|
||||
if let Some(c) = sprite.sample(u, v) {
|
||||
fb.put(sx as usize, sy as usize, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Crosshair.
|
||||
let (cx, cy) = (w / 2, h / 2);
|
||||
// Aim feedback: the crosshair turns red over a hittable demon and
|
||||
// gains a center dot.
|
||||
let on_target = game.target_in_crosshair().is_some();
|
||||
let ch_c: Rgb = if on_target {
|
||||
assets::GBOOM_RED
|
||||
} else {
|
||||
[210, 210, 210]
|
||||
};
|
||||
for d in 2..5usize {
|
||||
if cx >= d && cx + d < w {
|
||||
fb.put(cx - d, cy, ch_c);
|
||||
fb.put(cx + d, cy, ch_c);
|
||||
}
|
||||
if cy >= d && cy + d < h {
|
||||
fb.put(cx, cy - d, ch_c);
|
||||
fb.put(cx, cy + d, ch_c);
|
||||
}
|
||||
}
|
||||
if on_target {
|
||||
fb.put(cx, cy, ch_c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Soft elliptical contact shadow at a sprite's feet, z-tested per column
|
||||
/// with the sprite's own depth so walls still occlude it.
|
||||
fn draw_contact_shadow(
|
||||
fb: &mut FrameBuffer,
|
||||
center_x: f32,
|
||||
y_feet: f32,
|
||||
sprite_w: f32,
|
||||
sprite_h: f32,
|
||||
depth: f32,
|
||||
) {
|
||||
let (w, h) = (fb.w, fb.h);
|
||||
let rx = (sprite_w * 0.38).max(1.0);
|
||||
let ry = (sprite_h * 0.05).max(1.5);
|
||||
let x0 = (center_x - rx).floor() as i32;
|
||||
let x1 = (center_x + rx).ceil() as i32;
|
||||
let y0 = (y_feet - ry).floor() as i32;
|
||||
let y1 = (y_feet + ry).ceil() as i32;
|
||||
for sx in x0.max(0)..x1.min(w as i32) {
|
||||
if fb.zbuf[sx as usize] <= depth {
|
||||
continue;
|
||||
}
|
||||
let nx = (sx as f32 - center_x) / rx;
|
||||
for sy in y0.max(0)..y1.min(h as i32) {
|
||||
let ny = (sy as f32 - y_feet) / ry;
|
||||
let r2 = nx * nx + ny * ny;
|
||||
if r2 < 1.0 {
|
||||
// Darkest at the center, fading out toward the rim.
|
||||
fb.darken(sx as usize, sy as usize, 0.55 + 0.45 * r2);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Title / end screens: animated fire + 5x7 pixel text
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// The classic PSX-style fire effect: a cellular automaton on a coarse
|
||||
/// grid, upscaled at draw time. Heat values 0..=36 index a fire palette.
|
||||
pub(super) struct FireSim {
|
||||
w: usize,
|
||||
h: usize,
|
||||
heat: Vec<u8>,
|
||||
rng: XorShift64,
|
||||
}
|
||||
|
||||
const FIRE_MAX: u8 = 36;
|
||||
|
||||
impl FireSim {
|
||||
pub fn new() -> Self {
|
||||
let (w, h) = (160, 84);
|
||||
let mut heat = vec![0u8; w * h];
|
||||
// Bottom row is the white-hot source.
|
||||
for x in 0..w {
|
||||
heat[(h - 1) * w + x] = FIRE_MAX;
|
||||
}
|
||||
Self {
|
||||
w,
|
||||
h,
|
||||
heat,
|
||||
rng: XorShift64::new(0xDEAD_BEEF_CAFE_F00D),
|
||||
}
|
||||
}
|
||||
|
||||
/// One simulation step: heat propagates upward with random decay/drift.
|
||||
pub fn step(&mut self) {
|
||||
for y in 1..self.h {
|
||||
for x in 0..self.w {
|
||||
let src = y * self.w + x;
|
||||
let r = self.rng.next_u32();
|
||||
let decay = (r & 1) as i32; // cool by 0 or 1
|
||||
let drift = (r >> 2) % 3; // 0, 1, 2 → left, stay, right
|
||||
let dst_x = (x as i32 + drift as i32 - 1).rem_euclid(self.w as i32) as usize;
|
||||
let dst = (y - 1) * self.w + dst_x;
|
||||
self.heat[dst] = (self.heat[src] as i32 - decay).max(0) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn palette(heat: u8) -> Rgb {
|
||||
// Black → deep red → orange → yellow → white.
|
||||
let t = heat as f32 / FIRE_MAX as f32;
|
||||
if t < 0.02 {
|
||||
[7, 7, 9]
|
||||
} else if t < 0.4 {
|
||||
lerp_color([24, 8, 6], [180, 30, 10], t / 0.4)
|
||||
} else if t < 0.75 {
|
||||
lerp_color([180, 30, 10], [240, 150, 30], (t - 0.4) / 0.35)
|
||||
} else {
|
||||
lerp_color([240, 150, 30], [255, 250, 200], (t - 0.75) / 0.25)
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the fire across the bottom `frac` of the framebuffer.
|
||||
pub fn draw(&self, fb: &mut FrameBuffer, frac: f32) {
|
||||
let (w, h) = (fb.w, fb.h);
|
||||
if w == 0 || h == 0 {
|
||||
return;
|
||||
}
|
||||
let fire_h = (h as f32 * frac) as usize;
|
||||
let y_start = h - fire_h.min(h);
|
||||
for y in y_start..h {
|
||||
let fy = (y - y_start) * self.h / fire_h.max(1);
|
||||
for x in 0..w {
|
||||
let fx = x * self.w / w;
|
||||
let heat = self.heat[fy.min(self.h - 1) * self.w + fx.min(self.w - 1)];
|
||||
if heat > 1 {
|
||||
fb.put(x, y, Self::palette(heat));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill the framebuffer with a flat color.
|
||||
pub(super) fn clear(fb: &mut FrameBuffer, c: Rgb) {
|
||||
for px in fb.pixels.chunks_exact_mut(3) {
|
||||
px.copy_from_slice(&c);
|
||||
}
|
||||
}
|
||||
|
||||
/// Measure the pixel width of `text` at `scale` (5x7 glyphs, 1px tracking).
|
||||
pub(super) fn text_width(text: &str, scale: usize) -> usize {
|
||||
text.chars().count() * 6 * scale
|
||||
}
|
||||
|
||||
/// Draw 5x7 pixel text with its top-left at `(x0, y0)`.
|
||||
pub(super) fn draw_text(fb: &mut FrameBuffer, text: &str, x0: i32, y0: i32, scale: usize, c: Rgb) {
|
||||
let mut pen_x = x0;
|
||||
for ch in text.chars() {
|
||||
let glyph = assets::glyph5x7(ch);
|
||||
for (row, bits) in glyph.iter().enumerate() {
|
||||
for col in 0..5 {
|
||||
if bits & (1 << (4 - col)) == 0 {
|
||||
continue;
|
||||
}
|
||||
for dy in 0..scale {
|
||||
for dx in 0..scale {
|
||||
let px = pen_x + (col * scale + dx) as i32;
|
||||
let py = y0 + (row * scale + dy) as i32;
|
||||
if px >= 0 && py >= 0 && (px as usize) < fb.w && (py as usize) < fb.h {
|
||||
fb.put(px as usize, py as usize, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pen_x += (6 * scale) as i32;
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw centered text with an 8-direction outline, which keeps the chunky
|
||||
/// font legible over the animated fire background.
|
||||
pub(super) fn draw_text_centered_outlined(
|
||||
fb: &mut FrameBuffer,
|
||||
text: &str,
|
||||
y0: i32,
|
||||
scale: usize,
|
||||
c: Rgb,
|
||||
outline: Rgb,
|
||||
) {
|
||||
let x0 = (fb.w as i32 - text_width(text, scale) as i32) / 2;
|
||||
let o = (scale as i32 / 2).max(1);
|
||||
for (dx, dy) in [
|
||||
(-o, -o),
|
||||
(0, -o),
|
||||
(o, -o),
|
||||
(-o, 0),
|
||||
(o, 0),
|
||||
(-o, o),
|
||||
(0, o),
|
||||
(o, o),
|
||||
] {
|
||||
draw_text(fb, text, x0 + dx, y0 + dy, scale, outline);
|
||||
}
|
||||
draw_text(fb, text, x0, y0, scale, c);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn render_game_fills_framebuffer() {
|
||||
let renderer = Renderer::new();
|
||||
let mut fb = FrameBuffer::new();
|
||||
fb.resize(320, 200);
|
||||
renderer.render_game(&mut fb, &Game::new());
|
||||
// The floor/ceiling pass paints the full frame, so it can't be all-zero.
|
||||
assert!(fb.pixels.iter().any(|&b| b != 0));
|
||||
assert_eq!(fb.pixels.len(), 320 * 200 * 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_survives_extreme_sizes() {
|
||||
let renderer = Renderer::new();
|
||||
let game = Game::new();
|
||||
let mut fb = FrameBuffer::new();
|
||||
for (w, h) in [(1usize, 1usize), (2, 2), (16, 8), (639, 401)] {
|
||||
fb.resize(w, h);
|
||||
renderer.render_game(&mut fb, &game);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zbuffer_occludes_sprites_behind_walls() {
|
||||
let renderer = Renderer::new();
|
||||
let mut game = Game::new();
|
||||
// Move all imps far behind the player so none are visible, render,
|
||||
// then put one directly in front and confirm pixels change.
|
||||
for imp in &mut game.imps {
|
||||
imp.x = game.player.x - 8.0;
|
||||
imp.y = game.player.y;
|
||||
}
|
||||
let mut fb = FrameBuffer::new();
|
||||
fb.resize(160, 100);
|
||||
renderer.render_game(&mut fb, &game);
|
||||
let before = fb.pixels.clone();
|
||||
|
||||
let (dx, dy) = game.player.dir();
|
||||
game.imps[0].x = game.player.x + dx * 1.5;
|
||||
game.imps[0].y = game.player.y + dy * 1.5;
|
||||
renderer.render_game(&mut fb, &game);
|
||||
assert_ne!(before, fb.pixels, "visible imp must change the frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fire_sim_burns_upward() {
|
||||
let mut fire = FireSim::new();
|
||||
for _ in 0..60 {
|
||||
fire.step();
|
||||
}
|
||||
// After enough steps some heat must exist above the source row.
|
||||
let above: u32 = (0..fire.w)
|
||||
.map(|x| fire.heat[(fire.h / 2) * fire.w + x] as u32)
|
||||
.sum();
|
||||
assert!(above > 0, "fire should propagate upward");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,916 @@
|
||||
//! World simulation for the `/gboom` easter egg: map, momentum-based player
|
||||
//! movement, imp AI, and hitscan combat.
|
||||
//!
|
||||
//! `step(dt)` advances by wall-clock time, so the game plays identically at
|
||||
//! any frame rate.
|
||||
|
||||
/// One hand-authored level. Digits are walls and pick the texture:
|
||||
/// `1` brick, `2` stone, `3` tech, `4` hellstone. `.` is floor, `P` the
|
||||
/// player start, `I` an imp spawn. Spawn reachability is enforced by test.
|
||||
const MAP_ART: &[&str] = &[
|
||||
"1111111111111111111111",
|
||||
"1P...1....2......2...1",
|
||||
"1....1.22.2.3333.2.I.1",
|
||||
"1....1.2..2.3..3.2...1",
|
||||
"1.11.1.2.I2.3.I3.222.1",
|
||||
"1.1..1.2..2.33.3...2.1",
|
||||
"1.1..1.22.2....3.2.2.1",
|
||||
"1.1......2..33.3.2...1",
|
||||
"1.111111.2.I3..32222.1",
|
||||
"1......1.2..3333.....1",
|
||||
"144444.1.2........11.1",
|
||||
"1....4.1.22222222..1.1",
|
||||
"1.I..4.1........2.I1.1",
|
||||
"1....4.11111111.2..1.1",
|
||||
"1.4444.......41.2222.1",
|
||||
"1.4..444444..41......1",
|
||||
"1.4.I......I.41.111111",
|
||||
"1.4..444444..4....I..1",
|
||||
"1.444........4.11....1",
|
||||
"1...44444444.4.1..1111",
|
||||
"1............4.1.....1",
|
||||
"1111111111111111111111",
|
||||
];
|
||||
|
||||
/// Player collision radius, in tiles. A touch under a quarter-tile so the
|
||||
/// 1-tile-wide corridors have comfortable clearance.
|
||||
const PLAYER_RADIUS: f32 = 0.20;
|
||||
/// Imp collision radius, in tiles.
|
||||
const IMP_RADIUS: f32 = 0.30;
|
||||
|
||||
/// Movement tuning — continuous "held" model.
|
||||
///
|
||||
/// With no key-release events, each press/repeat refreshes a per-control
|
||||
/// hold timer ([`HOLD_WINDOW`]); while it's positive, velocity eases toward
|
||||
/// a steady target. A constant target while held means speed doesn't
|
||||
/// sawtooth with the OS key-repeat cadence, yet releasing glides to a stop.
|
||||
const MOVE_SPEED: f32 = 3.3; // tiles/s while a move key is held
|
||||
const TURN_SPEED: f32 = 2.2; // rad/s (~125°/s) while a turn key is held
|
||||
/// Velocity-smoothing time constants (seconds). Small = snappy response
|
||||
/// with just enough ramp to read as momentum rather than teleporting.
|
||||
const MOVE_ACCEL_TAU: f32 = 0.08;
|
||||
const TURN_ACCEL_TAU: f32 = 0.07;
|
||||
/// How long after each press/repeat a control stays "held". Must exceed
|
||||
/// the slowest expected key-repeat interval (≈30–60 ms) so motion never
|
||||
/// stutters between repeats, while staying short enough that releasing
|
||||
/// stops promptly.
|
||||
const HOLD_WINDOW: f32 = 0.16;
|
||||
|
||||
const PLAYER_MAX_HP: i32 = 100;
|
||||
const FIRE_COOLDOWN: f32 = 0.32;
|
||||
const MUZZLE_TIME: f32 = 0.09;
|
||||
/// Hitscan half-width: an imp is hit when its center is within this
|
||||
/// perpendicular distance of the aim ray.
|
||||
const HIT_WIDTH: f32 = 0.33;
|
||||
const PISTOL_DAMAGE: i32 = 11;
|
||||
|
||||
const IMP_HP: i32 = 30;
|
||||
const IMP_SPEED: f32 = 1.55;
|
||||
const IMP_SIGHT_RANGE: f32 = 9.0;
|
||||
const IMP_MELEE_RANGE: f32 = 0.95;
|
||||
const IMP_WINDUP: f32 = 0.38;
|
||||
const IMP_ATTACK_COOLDOWN: f32 = 0.95;
|
||||
const IMP_PAIN_TIME: f32 = 0.28;
|
||||
const IMP_DEATH_TIME: f32 = 0.55;
|
||||
const IMP_BITE_DAMAGE: i32 = 7;
|
||||
|
||||
/// Grid map with texture-id cells.
|
||||
pub(super) struct Map {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
cells: Vec<u8>, // 0 = floor, 1..=4 = wall texture id
|
||||
}
|
||||
|
||||
impl Map {
|
||||
/// Wall texture id at a cell, or 0 for floor. Out of bounds is solid.
|
||||
#[inline]
|
||||
pub fn cell(&self, x: i32, y: i32) -> u8 {
|
||||
if x < 0 || y < 0 || x >= self.w as i32 || y >= self.h as i32 {
|
||||
return 1;
|
||||
}
|
||||
self.cells[y as usize * self.w + x as usize]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn solid(&self, x: i32, y: i32) -> bool {
|
||||
self.cell(x, y) != 0
|
||||
}
|
||||
|
||||
/// Whether a circle of `radius` at `(x, y)` overlaps any solid cell.
|
||||
fn blocked(&self, x: f32, y: f32, radius: f32) -> bool {
|
||||
let min_x = (x - radius).floor() as i32;
|
||||
let max_x = (x + radius).floor() as i32;
|
||||
let min_y = (y - radius).floor() as i32;
|
||||
let max_y = (y + radius).floor() as i32;
|
||||
for cy in min_y..=max_y {
|
||||
for cx in min_x..=max_x {
|
||||
if self.solid(cx, cy) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Line-of-sight check between two points (wall occlusion only).
|
||||
/// Standard DDA over grid cells.
|
||||
pub fn los(&self, x0: f32, y0: f32, x1: f32, y1: f32) -> bool {
|
||||
let dx = x1 - x0;
|
||||
let dy = y1 - y0;
|
||||
let dist = (dx * dx + dy * dy).sqrt();
|
||||
if dist < 1e-4 {
|
||||
return true;
|
||||
}
|
||||
let (rdx, rdy) = (dx / dist, dy / dist);
|
||||
let mut map_x = x0.floor() as i32;
|
||||
let mut map_y = y0.floor() as i32;
|
||||
let delta_x = if rdx == 0.0 {
|
||||
f32::MAX
|
||||
} else {
|
||||
(1.0 / rdx).abs()
|
||||
};
|
||||
let delta_y = if rdy == 0.0 {
|
||||
f32::MAX
|
||||
} else {
|
||||
(1.0 / rdy).abs()
|
||||
};
|
||||
let (step_x, mut side_x) = if rdx < 0.0 {
|
||||
(-1, (x0 - map_x as f32) * delta_x)
|
||||
} else {
|
||||
(1, (map_x as f32 + 1.0 - x0) * delta_x)
|
||||
};
|
||||
let (step_y, mut side_y) = if rdy < 0.0 {
|
||||
(-1, (y0 - map_y as f32) * delta_y)
|
||||
} else {
|
||||
(1, (map_y as f32 + 1.0 - y0) * delta_y)
|
||||
};
|
||||
loop {
|
||||
let travelled = if side_x < side_y {
|
||||
map_x += step_x;
|
||||
let t = side_x;
|
||||
side_x += delta_x;
|
||||
t
|
||||
} else {
|
||||
map_y += step_y;
|
||||
let t = side_y;
|
||||
side_y += delta_y;
|
||||
t
|
||||
};
|
||||
if travelled >= dist {
|
||||
return true;
|
||||
}
|
||||
if self.solid(map_x, map_y) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Player state.
|
||||
pub(super) struct Player {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub angle: f32,
|
||||
/// Forward velocity (negative = backpedal), tiles/s.
|
||||
pub vel_forward: f32,
|
||||
/// Strafe velocity (positive = right), tiles/s.
|
||||
pub vel_strafe: f32,
|
||||
/// Angular velocity, rad/s (positive = turn right).
|
||||
pub vel_rot: f32,
|
||||
pub hp: i32,
|
||||
/// Seconds until the pistol can fire again.
|
||||
fire_cooldown: f32,
|
||||
/// Remaining muzzle-flash display time.
|
||||
pub muzzle: f32,
|
||||
/// Damage flash intensity, decays to 0.
|
||||
pub damage_flash: f32,
|
||||
/// Accumulated distance for view/gun bobbing.
|
||||
pub bob: f32,
|
||||
}
|
||||
|
||||
impl Player {
|
||||
#[inline]
|
||||
pub fn dir(&self) -> (f32, f32) {
|
||||
(self.angle.cos(), self.angle.sin())
|
||||
}
|
||||
}
|
||||
|
||||
/// Movement controls, fed by key press/repeat events. The discriminants
|
||||
/// double as indices into [`Game::hold`], so keep them field-less.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) enum Control {
|
||||
Forward,
|
||||
Back,
|
||||
TurnLeft,
|
||||
TurnRight,
|
||||
StrafeLeft,
|
||||
StrafeRight,
|
||||
}
|
||||
|
||||
impl Control {
|
||||
/// Number of controls — the size of the hold-timer array.
|
||||
const COUNT: usize = 6;
|
||||
}
|
||||
|
||||
/// What an imp is doing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) enum ImpState {
|
||||
Idle,
|
||||
Chasing,
|
||||
/// Wind-up before a melee hit; `t` counts down.
|
||||
Attacking {
|
||||
t: f32,
|
||||
},
|
||||
Pain {
|
||||
t: f32,
|
||||
},
|
||||
Dying {
|
||||
t: f32,
|
||||
},
|
||||
Dead,
|
||||
}
|
||||
|
||||
/// Which sprite frame to draw for an imp.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum ImpVisual {
|
||||
WalkA,
|
||||
WalkB,
|
||||
Attack,
|
||||
Pain,
|
||||
DieA,
|
||||
DieB,
|
||||
Corpse,
|
||||
}
|
||||
|
||||
pub(super) struct Imp {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub hp: i32,
|
||||
pub state: ImpState,
|
||||
/// Walk-cycle clock.
|
||||
anim: f32,
|
||||
/// Seconds until the next melee attempt is allowed.
|
||||
attack_cooldown: f32,
|
||||
}
|
||||
|
||||
impl Imp {
|
||||
pub fn alive(&self) -> bool {
|
||||
!matches!(self.state, ImpState::Dying { .. } | ImpState::Dead)
|
||||
}
|
||||
|
||||
/// Walk-cycle bob phase in `[-1, 1]`, or `None` when not walking.
|
||||
/// Drives a small vertical offset in the renderer.
|
||||
pub fn walk_bob(&self) -> Option<f32> {
|
||||
matches!(self.state, ImpState::Chasing).then(|| (self.anim * 9.0).sin())
|
||||
}
|
||||
|
||||
pub fn visual(&self) -> ImpVisual {
|
||||
match self.state {
|
||||
ImpState::Idle => ImpVisual::WalkA,
|
||||
ImpState::Chasing => {
|
||||
if ((self.anim * 3.0) as u32).is_multiple_of(2) {
|
||||
ImpVisual::WalkA
|
||||
} else {
|
||||
ImpVisual::WalkB
|
||||
}
|
||||
}
|
||||
ImpState::Attacking { .. } => ImpVisual::Attack,
|
||||
ImpState::Pain { .. } => ImpVisual::Pain,
|
||||
ImpState::Dying { t } => {
|
||||
if t > IMP_DEATH_TIME * 0.5 {
|
||||
ImpVisual::DieA
|
||||
} else {
|
||||
ImpVisual::DieB
|
||||
}
|
||||
}
|
||||
ImpState::Dead => ImpVisual::Corpse,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole game world.
|
||||
pub(super) struct Game {
|
||||
pub map: Map,
|
||||
pub player: Player,
|
||||
pub imps: Vec<Imp>,
|
||||
pub kills: u32,
|
||||
pub time: f32,
|
||||
/// Per-control "held" countdown in seconds, indexed by `Control as
|
||||
/// usize`. Positive means held. In timer mode each press/repeat
|
||||
/// refreshes it to [`HOLD_WINDOW`] and `step` decrements it; in
|
||||
/// release-aware mode a press latches it (and only [`Game::release`]
|
||||
/// clears it), so several keys can be held at once.
|
||||
hold: [f32; Control::COUNT],
|
||||
/// Whether the terminal delivers key-release events (Kitty keyboard
|
||||
/// protocol). When true, controls are latched on press and cleared on
|
||||
/// release — enabling true simultaneous move + turn. When false, the
|
||||
/// timer bridges the gaps between OS key-repeats for a single key.
|
||||
release_aware: bool,
|
||||
/// Set by [`Game::queue_fire`], consumed by the next `step`.
|
||||
fire_queued: bool,
|
||||
rng: super::assets::XorShift64,
|
||||
}
|
||||
|
||||
impl Game {
|
||||
pub fn new() -> Self {
|
||||
let h = MAP_ART.len();
|
||||
let w = MAP_ART[0].len();
|
||||
let mut cells = vec![0u8; w * h];
|
||||
let mut player_start = (1.5f32, 1.5f32);
|
||||
let mut imps = Vec::new();
|
||||
for (y, row) in MAP_ART.iter().enumerate() {
|
||||
debug_assert_eq!(row.len(), w, "map rows must be equal length");
|
||||
for (x, ch) in row.bytes().enumerate() {
|
||||
let center = (x as f32 + 0.5, y as f32 + 0.5);
|
||||
match ch {
|
||||
b'1'..=b'4' => cells[y * w + x] = ch - b'0',
|
||||
b'P' => player_start = center,
|
||||
b'I' => imps.push(Imp {
|
||||
x: center.0,
|
||||
y: center.1,
|
||||
hp: IMP_HP,
|
||||
state: ImpState::Idle,
|
||||
anim: (x * 7 + y * 13) as f32 * 0.1, // desync walk cycles
|
||||
attack_cooldown: 0.0,
|
||||
}),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Self {
|
||||
map: Map { w, h, cells },
|
||||
player: Player {
|
||||
x: player_start.0,
|
||||
y: player_start.1,
|
||||
angle: 0.0,
|
||||
vel_forward: 0.0,
|
||||
vel_strafe: 0.0,
|
||||
vel_rot: 0.0,
|
||||
hp: PLAYER_MAX_HP,
|
||||
fire_cooldown: 0.0,
|
||||
muzzle: 0.0,
|
||||
damage_flash: 0.0,
|
||||
bob: 0.0,
|
||||
},
|
||||
imps,
|
||||
kills: 0,
|
||||
time: 0.0,
|
||||
hold: [0.0; Control::COUNT],
|
||||
release_aware: false,
|
||||
fire_queued: false,
|
||||
rng: super::assets::XorShift64::new(0x9E3779B97F4A7C15),
|
||||
}
|
||||
}
|
||||
|
||||
/// Switch between the release-aware and timer movement models. Set once
|
||||
/// when the game opens, from the terminal's keyboard capability.
|
||||
pub fn set_release_aware(&mut self, release_aware: bool) {
|
||||
self.release_aware = release_aware;
|
||||
}
|
||||
|
||||
pub fn total_imps(&self) -> u32 {
|
||||
self.imps.len() as u32
|
||||
}
|
||||
|
||||
pub fn won(&self) -> bool {
|
||||
self.kills == self.total_imps()
|
||||
}
|
||||
|
||||
pub fn dead(&self) -> bool {
|
||||
self.player.hp <= 0
|
||||
}
|
||||
|
||||
/// Register a press/repeat event for `control`. In release-aware mode
|
||||
/// the control latches until [`Game::release`]; otherwise it stays held
|
||||
/// for [`HOLD_WINDOW`] seconds. Velocity is applied in `step`.
|
||||
pub fn press(&mut self, control: Control) {
|
||||
self.hold[control as usize] = if self.release_aware {
|
||||
f32::INFINITY
|
||||
} else {
|
||||
HOLD_WINDOW
|
||||
};
|
||||
}
|
||||
|
||||
/// Register a key-release for `control` (release-aware mode only).
|
||||
pub fn release(&mut self, control: Control) {
|
||||
self.hold[control as usize] = 0.0;
|
||||
}
|
||||
|
||||
/// Un-latch every control. Called on focus loss so a release event
|
||||
/// dropped while the window was unfocused can't latch movement forever.
|
||||
pub fn release_all(&mut self) {
|
||||
self.hold = [0.0; Control::COUNT];
|
||||
}
|
||||
|
||||
/// Whether any movement control is currently held (latched or within
|
||||
/// the repeat-bridging window). Used to assert hold-clearing behavior.
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn any_held(&self) -> bool {
|
||||
self.hold.iter().any(|&h| h > 0.0)
|
||||
}
|
||||
|
||||
/// Request a pistol shot; fires on the next `step` if off cooldown.
|
||||
pub fn queue_fire(&mut self) {
|
||||
self.fire_queued = true;
|
||||
}
|
||||
|
||||
/// Advance the world by `dt` seconds.
|
||||
pub fn step(&mut self, dt: f32) {
|
||||
self.time += dt;
|
||||
self.step_player(dt);
|
||||
if self.fire_queued {
|
||||
self.fire_queued = false;
|
||||
self.try_fire();
|
||||
}
|
||||
self.step_imps(dt);
|
||||
}
|
||||
|
||||
fn step_player(&mut self, dt: f32) {
|
||||
// Age the hold timers, then read which controls are still held.
|
||||
for h in &mut self.hold {
|
||||
*h = (*h - dt).max(0.0);
|
||||
}
|
||||
let held = |c: Control| self.hold[c as usize] > 0.0;
|
||||
let axis = |pos: Control, neg: Control| (held(pos) as i32 - held(neg) as i32) as f32;
|
||||
|
||||
// Steady target velocities from the held controls. The
|
||||
// forward/strafe pair is clamped to unit length so moving
|
||||
// diagonally isn't faster than moving straight.
|
||||
let mut fwd = axis(Control::Forward, Control::Back);
|
||||
let mut strafe = axis(Control::StrafeRight, Control::StrafeLeft);
|
||||
let mag = (fwd * fwd + strafe * strafe).sqrt();
|
||||
if mag > 1.0 {
|
||||
fwd /= mag;
|
||||
strafe /= mag;
|
||||
}
|
||||
let target_forward = fwd * MOVE_SPEED;
|
||||
let target_strafe = strafe * MOVE_SPEED;
|
||||
let target_rot = axis(Control::TurnRight, Control::TurnLeft) * TURN_SPEED;
|
||||
|
||||
// Frame-rate-independent exponential smoothing toward the targets:
|
||||
// a constant target while held means no sawtooth, and a zero target
|
||||
// on release glides to a stop.
|
||||
let move_blend = 1.0 - (-dt / MOVE_ACCEL_TAU).exp();
|
||||
let turn_blend = 1.0 - (-dt / TURN_ACCEL_TAU).exp();
|
||||
|
||||
let p = &mut self.player;
|
||||
p.vel_forward += (target_forward - p.vel_forward) * move_blend;
|
||||
p.vel_strafe += (target_strafe - p.vel_strafe) * move_blend;
|
||||
p.vel_rot += (target_rot - p.vel_rot) * turn_blend;
|
||||
|
||||
// Integrate rotation, then position.
|
||||
p.angle += p.vel_rot * dt;
|
||||
let (dx, dy) = p.dir();
|
||||
// Strafe axis is dir rotated +90°.
|
||||
let (sx, sy) = (-dy, dx);
|
||||
let step_x = (dx * p.vel_forward + sx * p.vel_strafe) * dt;
|
||||
let step_y = (dy * p.vel_forward + sy * p.vel_strafe) * dt;
|
||||
|
||||
// Axis-separated movement → slide along walls.
|
||||
if !self.map.blocked(p.x + step_x, p.y, PLAYER_RADIUS) {
|
||||
p.x += step_x;
|
||||
}
|
||||
if !self.map.blocked(p.x, p.y + step_y, PLAYER_RADIUS) {
|
||||
p.y += step_y;
|
||||
}
|
||||
|
||||
p.bob += (p.vel_forward.abs() + p.vel_strafe.abs()) * dt;
|
||||
p.fire_cooldown = (p.fire_cooldown - dt).max(0.0);
|
||||
p.muzzle = (p.muzzle - dt).max(0.0);
|
||||
p.damage_flash = (p.damage_flash - dt * 1.8).max(0.0);
|
||||
}
|
||||
|
||||
/// The live imp the pistol would hit right now: nearest one within
|
||||
/// [`HIT_WIDTH`] of the aim ray with clear line of sight. Shared by
|
||||
/// [`Game::try_fire`] and the renderer's crosshair feedback.
|
||||
pub fn target_in_crosshair(&self) -> Option<usize> {
|
||||
let (px, py) = (self.player.x, self.player.y);
|
||||
let (dx, dy) = self.player.dir();
|
||||
let mut best: Option<(usize, f32)> = None;
|
||||
for (i, imp) in self.imps.iter().enumerate() {
|
||||
if !imp.alive() {
|
||||
continue;
|
||||
}
|
||||
let (rx, ry) = (imp.x - px, imp.y - py);
|
||||
let along = rx * dx + ry * dy;
|
||||
if along <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let perp = (rx * dy - ry * dx).abs();
|
||||
if perp > HIT_WIDTH {
|
||||
continue;
|
||||
}
|
||||
if !self.map.los(px, py, imp.x, imp.y) {
|
||||
continue;
|
||||
}
|
||||
if best.is_none_or(|(_, d)| along < d) {
|
||||
best = Some((i, along));
|
||||
}
|
||||
}
|
||||
best.map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// Hitscan pistol: damage the imp under the crosshair, if any.
|
||||
fn try_fire(&mut self) {
|
||||
if self.player.fire_cooldown > 0.0 {
|
||||
return;
|
||||
}
|
||||
self.player.fire_cooldown = FIRE_COOLDOWN;
|
||||
self.player.muzzle = MUZZLE_TIME;
|
||||
|
||||
if let Some(i) = self.target_in_crosshair() {
|
||||
let damage = PISTOL_DAMAGE + (self.rng.next_f32() * 7.0) as i32;
|
||||
let imp = &mut self.imps[i];
|
||||
imp.hp -= damage;
|
||||
if imp.hp <= 0 {
|
||||
imp.state = ImpState::Dying { t: IMP_DEATH_TIME };
|
||||
self.kills += 1;
|
||||
} else {
|
||||
imp.state = ImpState::Pain { t: IMP_PAIN_TIME };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn step_imps(&mut self, dt: f32) {
|
||||
let (px, py) = (self.player.x, self.player.y);
|
||||
let mut player_damage = 0;
|
||||
|
||||
for i in 0..self.imps.len() {
|
||||
let (ix, iy, state) = {
|
||||
let imp = &self.imps[i];
|
||||
(imp.x, imp.y, imp.state)
|
||||
};
|
||||
// Corpses never act — skip the distance sqrt for them (late game
|
||||
// is mostly corpses).
|
||||
if matches!(state, ImpState::Dead) {
|
||||
continue;
|
||||
}
|
||||
let dist = ((px - ix).powi(2) + (py - iy).powi(2)).sqrt();
|
||||
|
||||
match state {
|
||||
ImpState::Idle => {
|
||||
if dist < IMP_SIGHT_RANGE && self.map.los(ix, iy, px, py) {
|
||||
self.imps[i].state = ImpState::Chasing;
|
||||
}
|
||||
}
|
||||
ImpState::Chasing => {
|
||||
self.imps[i].attack_cooldown = (self.imps[i].attack_cooldown - dt).max(0.0);
|
||||
if dist < IMP_MELEE_RANGE {
|
||||
if self.imps[i].attack_cooldown <= 0.0 {
|
||||
self.imps[i].state = ImpState::Attacking { t: IMP_WINDUP };
|
||||
}
|
||||
} else {
|
||||
// The walk cycle only advances while actually
|
||||
// moving, so an imp waiting out its attack
|
||||
// cooldown doesn't march in place.
|
||||
self.imps[i].anim += dt;
|
||||
self.chase_step(i, px, py, dist, dt);
|
||||
}
|
||||
}
|
||||
ImpState::Attacking { t } => {
|
||||
let t = t - dt;
|
||||
if t <= 0.0 {
|
||||
// Bite lands if the player is still close.
|
||||
let imp = &mut self.imps[i];
|
||||
imp.state = ImpState::Chasing;
|
||||
imp.attack_cooldown = IMP_ATTACK_COOLDOWN;
|
||||
if dist < IMP_MELEE_RANGE * 1.25 {
|
||||
player_damage += IMP_BITE_DAMAGE + (self.rng.next_f32() * 5.0) as i32;
|
||||
}
|
||||
} else {
|
||||
self.imps[i].state = ImpState::Attacking { t };
|
||||
}
|
||||
}
|
||||
ImpState::Pain { t } => {
|
||||
let t = t - dt;
|
||||
self.imps[i].state = if t <= 0.0 {
|
||||
ImpState::Chasing
|
||||
} else {
|
||||
ImpState::Pain { t }
|
||||
};
|
||||
}
|
||||
ImpState::Dying { t } => {
|
||||
let t = t - dt;
|
||||
self.imps[i].state = if t <= 0.0 {
|
||||
ImpState::Dead
|
||||
} else {
|
||||
ImpState::Dying { t }
|
||||
};
|
||||
}
|
||||
ImpState::Dead => {}
|
||||
}
|
||||
}
|
||||
|
||||
if player_damage > 0 {
|
||||
self.player.hp = (self.player.hp - player_damage).max(0);
|
||||
self.player.damage_flash = 1.0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Move imp `i` toward the player with wall sliding and a small
|
||||
/// separation force from other live imps.
|
||||
fn chase_step(&mut self, i: usize, px: f32, py: f32, dist: f32, dt: f32) {
|
||||
let (ix, iy) = (self.imps[i].x, self.imps[i].y);
|
||||
let mut mx = (px - ix) / dist;
|
||||
let mut my = (py - iy) / dist;
|
||||
|
||||
// Separation: push away from live imps closer than 0.7 tiles
|
||||
// (0.49 = 0.7²) so the pack doesn't collapse into one sprite.
|
||||
for (j, other) in self.imps.iter().enumerate() {
|
||||
if i == j || !other.alive() {
|
||||
continue;
|
||||
}
|
||||
let (ox, oy) = (ix - other.x, iy - other.y);
|
||||
let d2 = ox * ox + oy * oy;
|
||||
if d2 < 0.49 && d2 > 1e-6 {
|
||||
let d = d2.sqrt();
|
||||
mx += (ox / d) * 0.6;
|
||||
my += (oy / d) * 0.6;
|
||||
}
|
||||
}
|
||||
let mag = (mx * mx + my * my).sqrt().max(1e-4);
|
||||
let step = IMP_SPEED * dt;
|
||||
let (sx, sy) = (mx / mag * step, my / mag * step);
|
||||
|
||||
let imp = &mut self.imps[i];
|
||||
if !self.map.blocked(imp.x + sx, imp.y, IMP_RADIUS) {
|
||||
imp.x += sx;
|
||||
}
|
||||
if !self.map.blocked(imp.x, imp.y + sy, IMP_RADIUS) {
|
||||
imp.y += sy;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn all_imp_spawns_reachable_from_player_start() {
|
||||
// Flood-fill walkable cells from the player start; every imp spawn
|
||||
// must be in the same connected component. This subsumes "spawns are
|
||||
// on floor tiles" (reachable cells are non-solid) and guards future
|
||||
// map edits against sealing a demon into an unreachable room.
|
||||
let game = Game::new();
|
||||
assert!(game.total_imps() >= 5, "want a meaningful demon count");
|
||||
let (w, h) = (game.map.w, game.map.h);
|
||||
let start = (game.player.x.floor() as i32, game.player.y.floor() as i32);
|
||||
let mut reachable = vec![false; w * h];
|
||||
let mut stack = vec![start];
|
||||
while let Some((x, y)) = stack.pop() {
|
||||
if game.map.solid(x, y) || reachable[y as usize * w + x as usize] {
|
||||
continue;
|
||||
}
|
||||
reachable[y as usize * w + x as usize] = true;
|
||||
stack.extend([(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]);
|
||||
}
|
||||
for imp in &game.imps {
|
||||
let (ix, iy) = (imp.x.floor() as usize, imp.y.floor() as usize);
|
||||
assert!(
|
||||
reachable[iy * w + ix],
|
||||
"imp spawn at ({ix}, {iy}) unreachable from player start"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_border_is_solid() {
|
||||
let game = Game::new();
|
||||
for x in 0..game.map.w as i32 {
|
||||
assert!(game.map.solid(x, 0));
|
||||
assert!(game.map.solid(x, game.map.h as i32 - 1));
|
||||
}
|
||||
for y in 0..game.map.h as i32 {
|
||||
assert!(game.map.solid(0, y));
|
||||
assert!(game.map.solid(game.map.w as i32 - 1, y));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn player_cannot_walk_through_walls() {
|
||||
let mut game = Game::new();
|
||||
// Face straight up (-y) into the top border and push hard.
|
||||
game.player.angle = -std::f32::consts::FRAC_PI_2;
|
||||
for _ in 0..600 {
|
||||
game.press(Control::Forward);
|
||||
game.step(1.0 / 30.0);
|
||||
}
|
||||
assert!(
|
||||
game.player.y >= 1.0 + PLAYER_RADIUS - 1e-3,
|
||||
"clipped into border wall"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn los_blocked_by_walls_and_open_in_room() {
|
||||
let game = Game::new();
|
||||
let (px, py) = (game.player.x, game.player.y);
|
||||
// Opposite map corner is far behind many walls.
|
||||
assert!(!game.map.los(px, py, 20.5, 20.5));
|
||||
// A spot in the same starting room is visible.
|
||||
assert!(game.map.los(px, py, px + 1.0, py + 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shooting_an_imp_in_front_damages_and_eventually_kills() {
|
||||
let mut game = Game::new();
|
||||
// Plant a target two tiles in front of the player, clear LOS.
|
||||
let (dx, dy) = game.player.dir();
|
||||
let (tx, ty) = (game.player.x + dx * 2.0, game.player.y + dy * 2.0);
|
||||
game.imps[0].x = tx;
|
||||
game.imps[0].y = ty;
|
||||
game.imps[0].state = ImpState::Idle;
|
||||
|
||||
let hp_before = game.imps[0].hp;
|
||||
game.queue_fire();
|
||||
game.step(0.016);
|
||||
assert!(game.imps[0].hp < hp_before, "first shot must connect");
|
||||
|
||||
for _ in 0..20 {
|
||||
game.step(FIRE_COOLDOWN + 0.01); // let cooldown lapse
|
||||
game.queue_fire();
|
||||
game.step(0.016);
|
||||
if !game.imps[0].alive() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(!game.imps[0].alive(), "imp should die after repeated hits");
|
||||
assert_eq!(game.kills, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fire_respects_cooldown() {
|
||||
let mut game = Game::new();
|
||||
let (dx, dy) = game.player.dir();
|
||||
game.imps[0].x = game.player.x + dx * 2.0;
|
||||
game.imps[0].y = game.player.y + dy * 2.0;
|
||||
|
||||
game.queue_fire();
|
||||
game.step(0.016);
|
||||
let hp_after_first = game.imps[0].hp;
|
||||
// Immediate second shot is swallowed by the cooldown.
|
||||
game.queue_fire();
|
||||
game.step(0.016);
|
||||
assert_eq!(game.imps[0].hp, hp_after_first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imp_chases_and_bites_player() {
|
||||
let mut game = Game::new();
|
||||
// Keep only one imp and put it right next to the player.
|
||||
game.imps.truncate(1);
|
||||
game.imps[0].x = game.player.x + 1.5;
|
||||
game.imps[0].y = game.player.y;
|
||||
game.imps[0].state = ImpState::Idle;
|
||||
|
||||
let mut bitten = false;
|
||||
for _ in 0..400 {
|
||||
game.step(1.0 / 30.0);
|
||||
if game.player.hp < PLAYER_MAX_HP {
|
||||
bitten = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(bitten, "imp should reach and bite the player");
|
||||
assert!(game.player.damage_flash > 0.0 || game.player.hp < PLAYER_MAX_HP);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn win_condition_when_all_imps_dead() {
|
||||
let mut game = Game::new();
|
||||
for imp in &mut game.imps {
|
||||
imp.state = ImpState::Dead;
|
||||
}
|
||||
game.kills = game.total_imps();
|
||||
assert!(game.won());
|
||||
assert!(!game.dead());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn movement_decays_to_rest() {
|
||||
// A single press (no further repeats) glides to a stop once the
|
||||
// hold window lapses.
|
||||
let mut game = Game::new();
|
||||
game.press(Control::Forward);
|
||||
game.press(Control::TurnRight);
|
||||
for _ in 0..120 {
|
||||
game.step(1.0 / 30.0);
|
||||
}
|
||||
assert!(game.player.vel_forward.abs() < 0.01);
|
||||
assert!(game.player.vel_rot.abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn held_forward_reaches_and_sustains_target_speed() {
|
||||
// Holding forward (a press every frame) must converge to MOVE_SPEED
|
||||
// and then stay there — no sawtooth.
|
||||
let mut game = Game::new();
|
||||
// Aim down an open stretch so walls don't cap velocity.
|
||||
game.player.angle = std::f32::consts::FRAC_PI_2; // +y
|
||||
let dt = 1.0 / 30.0;
|
||||
for _ in 0..40 {
|
||||
game.press(Control::Forward);
|
||||
game.step(dt);
|
||||
}
|
||||
let speed = game.player.vel_forward;
|
||||
assert!(
|
||||
(speed - MOVE_SPEED).abs() < 0.05,
|
||||
"expected ~{MOVE_SPEED}, got {speed}"
|
||||
);
|
||||
// Sustained: the spread over the next second stays tiny.
|
||||
let (mut lo, mut hi) = (f32::MAX, f32::MIN);
|
||||
for _ in 0..30 {
|
||||
game.press(Control::Forward);
|
||||
game.step(dt);
|
||||
lo = lo.min(game.player.vel_forward);
|
||||
hi = hi.max(game.player.vel_forward);
|
||||
}
|
||||
assert!(hi - lo < 0.02, "velocity sawtoothed: [{lo}, {hi}]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_aware_supports_simultaneous_move_and_turn() {
|
||||
// The bug: on a Kitty-keyboard terminal, holding W + an arrow must
|
||||
// move AND turn. The terminal only auto-repeats the last key, so
|
||||
// forward gets a single press then nothing until release — latching
|
||||
// on press (release-aware) keeps it moving without repeats.
|
||||
let mut game = Game::new();
|
||||
game.set_release_aware(true);
|
||||
game.player.angle = 0.0; // facing +x
|
||||
game.press(Control::Forward);
|
||||
game.press(Control::TurnLeft);
|
||||
|
||||
let angle0 = game.player.angle;
|
||||
for _ in 0..30 {
|
||||
game.step(1.0 / 30.0); // no further presses
|
||||
}
|
||||
assert!(
|
||||
game.player.vel_forward > 1.0,
|
||||
"forward must persist without repeats, got {}",
|
||||
game.player.vel_forward
|
||||
);
|
||||
assert!(
|
||||
game.player.angle < angle0,
|
||||
"should have turned left while moving"
|
||||
);
|
||||
|
||||
// Releasing forward stops forward; turning continues.
|
||||
game.release(Control::Forward);
|
||||
for _ in 0..30 {
|
||||
game.step(1.0 / 30.0);
|
||||
}
|
||||
assert!(
|
||||
game.player.vel_forward.abs() < 0.2,
|
||||
"released forward should glide to rest, got {}",
|
||||
game.player.vel_forward
|
||||
);
|
||||
assert!(game.player.vel_rot.abs() > 0.1, "turn should still be held");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_all_un_latches_movement() {
|
||||
// Safety valve for a release dropped on focus loss: latched keys
|
||||
// must all clear so the player doesn't walk forever.
|
||||
let mut game = Game::new();
|
||||
game.set_release_aware(true);
|
||||
game.press(Control::Forward);
|
||||
game.press(Control::TurnLeft);
|
||||
game.release_all();
|
||||
for _ in 0..30 {
|
||||
game.step(1.0 / 30.0);
|
||||
}
|
||||
assert!(game.player.vel_forward.abs() < 0.1);
|
||||
assert!(game.player.vel_rot.abs() < 0.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sustained_speed_is_independent_of_repeat_cadence() {
|
||||
// The whole point of the hold model: a slow key-repeat cadence must
|
||||
// reach the same sustained speed as a fast one (no stutter), as long
|
||||
// as repeats arrive within HOLD_WINDOW.
|
||||
fn sustained_speed(repeat_interval: f32) -> f32 {
|
||||
let mut game = Game::new();
|
||||
game.player.angle = std::f32::consts::FRAC_PI_2;
|
||||
let dt = 1.0 / 60.0;
|
||||
let mut since_repeat = repeat_interval; // press on the first frame
|
||||
// Run 2s of simulation, pressing every `repeat_interval`.
|
||||
for _ in 0..120 {
|
||||
since_repeat += dt;
|
||||
if since_repeat >= repeat_interval {
|
||||
game.press(Control::Forward);
|
||||
since_repeat = 0.0;
|
||||
}
|
||||
game.step(dt);
|
||||
}
|
||||
game.player.vel_forward
|
||||
}
|
||||
let fast = sustained_speed(0.03); // ~33 Hz
|
||||
let slow = sustained_speed(0.12); // ~8 Hz, still under HOLD_WINDOW
|
||||
assert!((fast - MOVE_SPEED).abs() < 0.1, "fast cadence: {fast}");
|
||||
assert!(
|
||||
(fast - slow).abs() < 0.25,
|
||||
"cadence changed sustained speed: fast={fast}, slow={slow}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,723 @@
|
||||
//! `/gboom` easter egg: a tiny single-level raycaster shooter rendered in
|
||||
//! the terminal via the kitty graphics protocol.
|
||||
//!
|
||||
//! Typing `/gboom` (and nothing else) opens a modal overlay — the same
|
||||
//! surface the imagine-video player uses — and streams PNG frames via
|
||||
//! per-frame kitty `a=T` retransmission at the ~30 fps animation tick. The
|
||||
//! simulation steps with wall-clock `dt`, so gameplay speed is independent
|
||||
//! of the achieved frame rate.
|
||||
//!
|
||||
//! Controls: `W`/`↑` forward, `S`/`↓` back, `A`/`D` strafe, `←`/`→` turn,
|
||||
//! mouse move/drag aim (in-modal, Playing only), click or `Space`/`Enter`
|
||||
//! fire, `Esc`/`q` quit. Movement uses the continuous held-key model in
|
||||
//! [`game`] — terminals deliver no key-release events, so it eases toward a
|
||||
//! steady target while a key is held, staying smooth regardless of the OS
|
||||
//! key-repeat cadence.
|
||||
|
||||
mod assets;
|
||||
mod engine;
|
||||
mod game;
|
||||
|
||||
pub(crate) use assets::GBOOM_RED;
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
|
||||
|
||||
use engine::{FireSim, FrameBuffer, Renderer};
|
||||
use game::{Control, Game};
|
||||
|
||||
/// Maximum rendered frame width in pixels. Each frame is PNG-encoded and
|
||||
/// pushed through the PTY every tick (~100 KB / ~3 MB/s at 30 fps at this
|
||||
/// cap), comfortably within what the video player already streams.
|
||||
const MAX_FRAME_W: usize = 480;
|
||||
/// Maximum rendered frame height in pixels.
|
||||
const MAX_FRAME_H: usize = 320;
|
||||
/// Assumed cell size in pixels for aspect mapping (cell aspect 0.5,
|
||||
/// consistent with `terminal::image::fit_image_to_cells`).
|
||||
const CELL_PX_W: usize = 8;
|
||||
const CELL_PX_H: usize = 16;
|
||||
/// Largest simulation step; longer gaps (lag, suspend) are clamped.
|
||||
const MAX_DT: f32 = 0.1;
|
||||
/// Delay before end screens accept a dismissal key.
|
||||
const END_SCREEN_GRACE: f32 = 0.8;
|
||||
/// Radians of yaw per terminal cell of horizontal mouse motion.
|
||||
const MOUSE_AIM_SENSITIVITY: f32 = 0.06;
|
||||
/// Column jumps larger than this re-seed the baseline without yawing.
|
||||
const MAX_MOUSE_AIM_DX: i32 = 12;
|
||||
/// Near-black outline that keeps screen text legible over the fire.
|
||||
const TEXT_OUTLINE: [u8; 3] = [16, 6, 6];
|
||||
|
||||
/// Where the player is in the easter egg flow. Time spent in the current
|
||||
/// phase is tracked by `GboomState::phase_time` (reset on every transition).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Phase {
|
||||
Title,
|
||||
Playing,
|
||||
Won,
|
||||
Dead,
|
||||
}
|
||||
|
||||
/// Result of a key event while the game modal is open.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum GboomKeyOutcome {
|
||||
/// Close the modal (caller clears the kitty placement).
|
||||
Close,
|
||||
/// Key consumed; state may have changed.
|
||||
Changed,
|
||||
}
|
||||
|
||||
/// HUD values for the overlay chrome.
|
||||
pub struct GboomHud {
|
||||
pub(crate) hp: i32,
|
||||
pub(crate) kills: u32,
|
||||
pub(crate) total: u32,
|
||||
pub(crate) playing: bool,
|
||||
}
|
||||
|
||||
/// Modal state for the `/gboom` easter egg. Owned by the agent view like
|
||||
/// the video viewer; ticked from the animation tick; rendered in the draw
|
||||
/// path via post-flush kitty escapes.
|
||||
pub struct GboomState {
|
||||
game: Game,
|
||||
renderer: Renderer,
|
||||
fire: FireSim,
|
||||
phase: Phase,
|
||||
last_tick: Instant,
|
||||
/// Monotonic simulation generation; bumps invalidate the frame cache.
|
||||
sim_gen: u64,
|
||||
fb: FrameBuffer,
|
||||
png: Vec<u8>,
|
||||
/// `(sim_gen, w, h)` of the cached PNG in `png`.
|
||||
cached: Option<(u64, usize, usize)>,
|
||||
/// Wall-clock time inside the current phase.
|
||||
phase_time: f32,
|
||||
last_mouse_col: Option<u16>,
|
||||
/// Popup cell rect `(x, y, w, h)` for mouse hit-testing; set from draw.
|
||||
mouse_region: Option<(u16, u16, u16, u16)>,
|
||||
}
|
||||
|
||||
impl GboomState {
|
||||
pub fn new() -> Self {
|
||||
let mut game = Game::new();
|
||||
// On terminals that report key releases (Kitty keyboard protocol),
|
||||
// latch keys on press/release so the player can move and turn at
|
||||
// once; otherwise fall back to the repeat-bridging timer model.
|
||||
game.set_release_aware(crate::terminal::kitty_flags_pushed());
|
||||
Self {
|
||||
game,
|
||||
renderer: Renderer::new(),
|
||||
fire: FireSim::new(),
|
||||
phase: Phase::Title,
|
||||
last_tick: Instant::now(),
|
||||
sim_gen: 0,
|
||||
fb: FrameBuffer::new(),
|
||||
png: Vec::new(),
|
||||
cached: None,
|
||||
phase_time: 0.0,
|
||||
last_mouse_col: None,
|
||||
mouse_region: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_mouse_region(&mut self, x: u16, y: u16, width: u16, height: u16) {
|
||||
self.mouse_region = Some((x, y, width, height));
|
||||
}
|
||||
|
||||
pub fn clear_mouse_region(&mut self) {
|
||||
self.mouse_region = None;
|
||||
self.last_mouse_col = None;
|
||||
}
|
||||
|
||||
fn in_mouse_region(&self, col: u16, row: u16) -> bool {
|
||||
let Some((x, y, w, h)) = self.mouse_region else {
|
||||
return false;
|
||||
};
|
||||
col >= x && row >= y && col < x.saturating_add(w) && row < y.saturating_add(h)
|
||||
}
|
||||
|
||||
/// Map a key to its movement control, if any.
|
||||
fn control_for(code: KeyCode) -> Option<Control> {
|
||||
match code {
|
||||
KeyCode::Char('w' | 'W') | KeyCode::Up => Some(Control::Forward),
|
||||
KeyCode::Char('s' | 'S') | KeyCode::Down => Some(Control::Back),
|
||||
KeyCode::Char('a' | 'A') => Some(Control::StrafeLeft),
|
||||
KeyCode::Char('d' | 'D') => Some(Control::StrafeRight),
|
||||
KeyCode::Left => Some(Control::TurnLeft),
|
||||
KeyCode::Right => Some(Control::TurnRight),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Advance the game by wall-clock time. Every tick produces a new
|
||||
/// frame (the world, fire, and bob animations are continuous), so the
|
||||
/// caller should always redraw after ticking.
|
||||
pub fn tick(&mut self) {
|
||||
let dt = self.last_tick.elapsed().as_secs_f32().min(MAX_DT);
|
||||
self.last_tick = Instant::now();
|
||||
self.phase_time += dt;
|
||||
|
||||
match self.phase {
|
||||
Phase::Title | Phase::Won | Phase::Dead => self.fire.step(),
|
||||
Phase::Playing => {
|
||||
self.game.step(dt);
|
||||
if self.game.dead() {
|
||||
self.set_phase(Phase::Dead);
|
||||
} else if self.game.won() && self.all_corpses_settled() {
|
||||
// The corpse check makes the win screen wait for the
|
||||
// final death animation to play out.
|
||||
self.set_phase(Phase::Won);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.sim_gen += 1;
|
||||
}
|
||||
|
||||
fn set_phase(&mut self, phase: Phase) {
|
||||
self.phase = phase;
|
||||
self.phase_time = 0.0;
|
||||
self.last_mouse_col = None;
|
||||
}
|
||||
|
||||
fn all_corpses_settled(&self) -> bool {
|
||||
self.game
|
||||
.imps
|
||||
.iter()
|
||||
.all(|imp| matches!(imp.state, game::ImpState::Dead))
|
||||
}
|
||||
|
||||
/// Handle a key press/repeat event.
|
||||
pub fn handle_key(&mut self, key: &KeyEvent) -> GboomKeyOutcome {
|
||||
// Esc / q always quit, in every phase.
|
||||
if matches!(
|
||||
key.code,
|
||||
KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('Q')
|
||||
) {
|
||||
return GboomKeyOutcome::Close;
|
||||
}
|
||||
|
||||
match self.phase {
|
||||
Phase::Title => {
|
||||
self.set_phase(Phase::Playing);
|
||||
self.last_tick = Instant::now();
|
||||
self.sim_gen += 1;
|
||||
}
|
||||
Phase::Playing => {
|
||||
// No `sim_gen` bump: held keys and queued shots only take
|
||||
// effect on the next tick (which bumps it), so the current
|
||||
// frame's cache stays valid.
|
||||
if let Some(control) = Self::control_for(key.code) {
|
||||
self.game.press(control);
|
||||
} else if matches!(key.code, KeyCode::Char(' ') | KeyCode::Enter) {
|
||||
self.game.queue_fire();
|
||||
}
|
||||
}
|
||||
Phase::Won | Phase::Dead => {
|
||||
if self.phase_time > END_SCREEN_GRACE {
|
||||
return GboomKeyOutcome::Close;
|
||||
}
|
||||
}
|
||||
}
|
||||
GboomKeyOutcome::Changed
|
||||
}
|
||||
|
||||
/// Handle a key-release event (release-aware terminals only): un-latch
|
||||
/// the corresponding movement control so the player stops that motion.
|
||||
pub fn handle_release(&mut self, key: &KeyEvent) {
|
||||
if matches!(self.phase, Phase::Playing)
|
||||
&& let Some(control) = Self::control_for(key.code)
|
||||
{
|
||||
self.game.release(control);
|
||||
}
|
||||
}
|
||||
|
||||
/// In-region move/drag aims; left-click fires (Playing only).
|
||||
pub fn handle_mouse(&mut self, mouse: &MouseEvent) {
|
||||
if !matches!(self.phase, Phase::Playing) {
|
||||
return;
|
||||
}
|
||||
let in_region = self.in_mouse_region(mouse.column, mouse.row);
|
||||
match mouse.kind {
|
||||
MouseEventKind::Down(MouseButton::Left) => {
|
||||
if in_region {
|
||||
self.game.queue_fire();
|
||||
}
|
||||
}
|
||||
MouseEventKind::Moved | MouseEventKind::Drag(_) => {
|
||||
if !in_region {
|
||||
self.last_mouse_col = None;
|
||||
return;
|
||||
}
|
||||
let col = mouse.column;
|
||||
if let Some(prev) = self.last_mouse_col {
|
||||
let dx = col as i32 - prev as i32;
|
||||
if dx.abs() > MAX_MOUSE_AIM_DX {
|
||||
self.last_mouse_col = Some(col);
|
||||
return;
|
||||
}
|
||||
if dx != 0 {
|
||||
self.game.player.angle += dx as f32 * MOUSE_AIM_SENSITIVITY;
|
||||
self.sim_gen += 1;
|
||||
}
|
||||
}
|
||||
self.last_mouse_col = Some(col);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Un-latch all movement (on focus loss), so a release dropped while
|
||||
/// unfocused can't leave the player walking forever.
|
||||
pub fn release_all(&mut self) {
|
||||
self.game.release_all();
|
||||
self.last_mouse_col = None;
|
||||
}
|
||||
|
||||
/// Whether the game currently holds a latched movement control. Lets the
|
||||
/// app layer assert that backgrounded games drop their holds.
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn any_movement_held(&self) -> bool {
|
||||
self.game.any_held()
|
||||
}
|
||||
|
||||
/// HUD values for the chrome line.
|
||||
pub fn hud(&self) -> GboomHud {
|
||||
GboomHud {
|
||||
hp: self.game.player.hp,
|
||||
kills: self.game.kills,
|
||||
total: self.game.total_imps(),
|
||||
playing: matches!(self.phase, Phase::Playing),
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a cell box to the internal render resolution: match the box's
|
||||
/// pixel aspect (8x16 px cells), capped to bound PNG payload and CPU.
|
||||
pub fn frame_size_for_cells(cols: u16, rows: u16) -> (usize, usize) {
|
||||
let mut w = (cols as usize * CELL_PX_W).max(64);
|
||||
let mut h = (rows as usize * CELL_PX_H).max(64);
|
||||
let scale = (MAX_FRAME_W as f32 / w as f32)
|
||||
.min(MAX_FRAME_H as f32 / h as f32)
|
||||
.min(1.0);
|
||||
w = ((w as f32 * scale) as usize).max(64);
|
||||
h = ((h as f32 * scale) as usize).max(64);
|
||||
(w, h)
|
||||
}
|
||||
|
||||
/// Render the current frame at `(w, h)` and return it PNG-encoded.
|
||||
/// Cached per `(sim_gen, w, h)` so extra draws between ticks are free.
|
||||
pub fn frame_png(&mut self, w: usize, h: usize) -> Option<&[u8]> {
|
||||
if w < 8 || h < 8 {
|
||||
return None;
|
||||
}
|
||||
if self.cached == Some((self.sim_gen, w, h)) {
|
||||
return Some(&self.png);
|
||||
}
|
||||
|
||||
self.fb.resize(w, h);
|
||||
match self.phase {
|
||||
Phase::Title => self.render_title_screen(),
|
||||
Phase::Playing => self.renderer.render_game(&mut self.fb, &self.game),
|
||||
Phase::Won => self.render_end_screen("VICTORY!", [255, 214, 80]),
|
||||
Phase::Dead => self.render_end_screen("YOU DIED", assets::GBOOM_RED),
|
||||
}
|
||||
|
||||
self.png.clear();
|
||||
{
|
||||
use image::codecs::png::{CompressionType, FilterType, PngEncoder};
|
||||
use image::{ExtendedColorType, ImageEncoder};
|
||||
let encoder = PngEncoder::new_with_quality(
|
||||
&mut self.png,
|
||||
CompressionType::Fast,
|
||||
FilterType::Adaptive,
|
||||
);
|
||||
if encoder
|
||||
.write_image(&self.fb.pixels, w as u32, h as u32, ExtendedColorType::Rgb8)
|
||||
.is_err()
|
||||
{
|
||||
self.cached = None;
|
||||
return None;
|
||||
}
|
||||
}
|
||||
self.cached = Some((self.sim_gen, w, h));
|
||||
Some(&self.png)
|
||||
}
|
||||
|
||||
fn render_title_screen(&mut self) {
|
||||
engine::clear(&mut self.fb, [7, 7, 9]);
|
||||
self.fire.draw(&mut self.fb, 0.62);
|
||||
|
||||
let h = self.fb.h as i32;
|
||||
let title_scale = (self.fb.w / 36).clamp(2, 10);
|
||||
let small_scale = (title_scale / 3).max(1);
|
||||
engine::draw_text_centered_outlined(
|
||||
&mut self.fb,
|
||||
"GBOOM",
|
||||
h / 6,
|
||||
title_scale,
|
||||
assets::GBOOM_RED,
|
||||
TEXT_OUTLINE,
|
||||
);
|
||||
engine::draw_text_centered_outlined(
|
||||
&mut self.fb,
|
||||
"KNEE-DEEP IN THE TOKENS",
|
||||
h / 6 + 8 * title_scale as i32,
|
||||
small_scale,
|
||||
[212, 168, 92],
|
||||
TEXT_OUTLINE,
|
||||
);
|
||||
// Blink the prompt line.
|
||||
if ((self.phase_time * 1.6) as u32).is_multiple_of(2) {
|
||||
engine::draw_text_centered_outlined(
|
||||
&mut self.fb,
|
||||
"PRESS ANY KEY",
|
||||
h / 6 + 8 * title_scale as i32 + 10 * small_scale as i32,
|
||||
small_scale,
|
||||
[220, 210, 190],
|
||||
TEXT_OUTLINE,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn render_end_screen(&mut self, text: &str, color: [u8; 3]) {
|
||||
engine::clear(&mut self.fb, [7, 7, 9]);
|
||||
self.fire.draw(&mut self.fb, 0.5);
|
||||
|
||||
let h = self.fb.h as i32;
|
||||
let scale = (self.fb.w / 40).clamp(2, 8);
|
||||
engine::draw_text_centered_outlined(&mut self.fb, text, h / 5, scale, color, TEXT_OUTLINE);
|
||||
|
||||
// Show the blinking dismissal hint once the grace period is over.
|
||||
if self.phase_time > END_SCREEN_GRACE && ((self.phase_time * 1.6) as u32).is_multiple_of(2)
|
||||
{
|
||||
engine::draw_text_centered_outlined(
|
||||
&mut self.fb,
|
||||
"PRESS ANY KEY",
|
||||
h / 5 + 10 * scale as i32,
|
||||
(scale / 3).max(1),
|
||||
[220, 210, 190],
|
||||
TEXT_OUTLINE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GboomState {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crossterm::event::{KeyEvent, KeyModifiers};
|
||||
|
||||
fn key(code: KeyCode) -> KeyEvent {
|
||||
KeyEvent::new(code, KeyModifiers::NONE)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starts_on_title_and_any_key_starts_game() {
|
||||
let mut state = GboomState::new();
|
||||
assert_eq!(state.phase, Phase::Title);
|
||||
assert_eq!(
|
||||
state.handle_key(&key(KeyCode::Char('w'))),
|
||||
GboomKeyOutcome::Changed
|
||||
);
|
||||
assert_eq!(state.phase, Phase::Playing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn esc_and_q_close_in_every_phase() {
|
||||
for phase in [Phase::Title, Phase::Playing, Phase::Won, Phase::Dead] {
|
||||
for code in [KeyCode::Esc, KeyCode::Char('q')] {
|
||||
let mut state = GboomState::new();
|
||||
state.phase = phase;
|
||||
assert_eq!(state.handle_key(&key(code)), GboomKeyOutcome::Close);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_screens_have_dismissal_grace_period() {
|
||||
let mut state = GboomState::new();
|
||||
state.phase = Phase::Dead;
|
||||
state.phase_time = 0.1;
|
||||
// Within the grace period, non-quit keys are swallowed.
|
||||
assert_eq!(
|
||||
state.handle_key(&key(KeyCode::Char(' '))),
|
||||
GboomKeyOutcome::Changed
|
||||
);
|
||||
state.phase_time = END_SCREEN_GRACE + 0.1;
|
||||
assert_eq!(
|
||||
state.handle_key(&key(KeyCode::Char(' '))),
|
||||
GboomKeyOutcome::Close
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_png_produces_valid_png_at_requested_size() {
|
||||
let mut state = GboomState::new();
|
||||
state.tick();
|
||||
let png = state.frame_png(320, 200).expect("png frame").to_vec();
|
||||
assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n");
|
||||
let dims = crate::prompt_images::decode_image_dimensions(&png).expect("decodable");
|
||||
assert_eq!(dims, (320, 200));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_png_is_cached_until_state_changes() {
|
||||
let mut state = GboomState::new();
|
||||
state.tick();
|
||||
let a = state.frame_png(160, 100).unwrap().to_vec();
|
||||
let b = state.frame_png(160, 100).unwrap().to_vec();
|
||||
assert_eq!(a, b, "same gen + dims must reuse the cached frame");
|
||||
state.tick();
|
||||
// After a tick the fire animates, so the title frame changes.
|
||||
let c = state.frame_png(160, 100).unwrap().to_vec();
|
||||
assert_ne!(a, c, "tick must invalidate the cached frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_size_mapping_respects_caps_and_aspect() {
|
||||
// A huge cell box gets capped.
|
||||
let (w, h) = GboomState::frame_size_for_cells(300, 80);
|
||||
assert!(w <= MAX_FRAME_W && h <= MAX_FRAME_H);
|
||||
// A typical popup box keeps the cell-box pixel aspect.
|
||||
let (w, h) = GboomState::frame_size_for_cells(60, 15);
|
||||
assert_eq!(
|
||||
(w as f32 / h as f32 * 10.0).round(),
|
||||
((60.0 * CELL_PX_W as f32) / (15.0 * CELL_PX_H as f32) * 10.0).round()
|
||||
);
|
||||
// Tiny boxes stay above the floor.
|
||||
let (w, h) = GboomState::frame_size_for_cells(1, 1);
|
||||
assert!(w >= 64 && h >= 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playing_to_dead_transition() {
|
||||
let mut state = GboomState::new();
|
||||
state.handle_key(&key(KeyCode::Char('w'))); // leave title
|
||||
state.game.player.hp = 0;
|
||||
state.tick();
|
||||
assert_eq!(state.phase, Phase::Dead);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playing_to_won_transition_after_corpses_settle() {
|
||||
let mut state = GboomState::new();
|
||||
state.handle_key(&key(KeyCode::Char('w')));
|
||||
let total = state.game.total_imps();
|
||||
for imp in &mut state.game.imps {
|
||||
imp.state = game::ImpState::Dead;
|
||||
}
|
||||
state.game.kills = total;
|
||||
state.tick();
|
||||
assert_eq!(state.phase, Phase::Won);
|
||||
}
|
||||
|
||||
fn playing_with_region() -> GboomState {
|
||||
let mut state = GboomState::new();
|
||||
state.handle_key(&key(KeyCode::Char('w')));
|
||||
state.set_mouse_region(0, 0, 200, 50);
|
||||
state
|
||||
}
|
||||
|
||||
fn mouse_at(kind: MouseEventKind, column: u16, row: u16) -> MouseEvent {
|
||||
MouseEvent {
|
||||
kind,
|
||||
column,
|
||||
row,
|
||||
modifiers: KeyModifiers::NONE,
|
||||
}
|
||||
}
|
||||
|
||||
fn mouse_moved(column: u16) -> MouseEvent {
|
||||
mouse_at(MouseEventKind::Moved, column, 10)
|
||||
}
|
||||
|
||||
fn mouse_click(column: u16, row: u16) -> MouseEvent {
|
||||
mouse_at(MouseEventKind::Down(MouseButton::Left), column, row)
|
||||
}
|
||||
|
||||
/// In-region yaw: Δangle = Δcol × sensitivity (first event seeds only).
|
||||
#[test]
|
||||
fn mouse_aim_delta_matches_column_delta() {
|
||||
let mut state = playing_with_region();
|
||||
state.game.player.angle = 0.0;
|
||||
state.handle_mouse(&mouse_moved(40));
|
||||
assert_eq!(state.game.player.angle, 0.0);
|
||||
state.handle_mouse(&mouse_moved(45));
|
||||
assert_eq!(state.game.player.angle, 5.0 * MOUSE_AIM_SENSITIVITY);
|
||||
state.handle_mouse(&mouse_moved(42));
|
||||
assert!((state.game.player.angle - 2.0 * MOUSE_AIM_SENSITIVITY).abs() < 1e-5);
|
||||
}
|
||||
|
||||
/// Non-Playing phases ignore mouse aim.
|
||||
#[test]
|
||||
fn mouse_aim_only_while_playing() {
|
||||
for phase in [Phase::Title, Phase::Won, Phase::Dead] {
|
||||
let mut state = GboomState::new();
|
||||
state.set_mouse_region(0, 0, 200, 50);
|
||||
state.phase = phase;
|
||||
state.game.player.angle = 0.5;
|
||||
state.handle_mouse(&mouse_moved(10));
|
||||
state.handle_mouse(&mouse_moved(50));
|
||||
assert_eq!(state.game.player.angle, 0.5);
|
||||
}
|
||||
}
|
||||
|
||||
/// Continuity breaks (release_all / teleport dx) re-seed without applying the gap as yaw.
|
||||
#[test]
|
||||
fn mouse_aim_baseline_reseeds_on_discontinuity() {
|
||||
let mut state = playing_with_region();
|
||||
state.game.player.angle = 0.0;
|
||||
state.handle_mouse(&mouse_moved(10));
|
||||
state.handle_mouse(&mouse_moved(12));
|
||||
let after_aim = state.game.player.angle;
|
||||
assert_eq!(after_aim, 2.0 * MOUSE_AIM_SENSITIVITY);
|
||||
|
||||
state.release_all();
|
||||
state.handle_mouse(&mouse_moved(50));
|
||||
assert_eq!(state.game.player.angle, after_aim);
|
||||
state.handle_mouse(&mouse_moved(52));
|
||||
assert_eq!(
|
||||
state.game.player.angle,
|
||||
after_aim + 2.0 * MOUSE_AIM_SENSITIVITY
|
||||
);
|
||||
|
||||
state.game.player.angle = 0.0;
|
||||
state.last_mouse_col = None;
|
||||
state.handle_mouse(&mouse_moved(10));
|
||||
state.handle_mouse(&mouse_moved(10 + MAX_MOUSE_AIM_DX as u16 + 1));
|
||||
assert_eq!(state.game.player.angle, 0.0);
|
||||
state.handle_mouse(&mouse_moved(10 + MAX_MOUSE_AIM_DX as u16 + 1 + 3));
|
||||
assert_eq!(state.game.player.angle, 3.0 * MOUSE_AIM_SENSITIVITY);
|
||||
}
|
||||
|
||||
/// Out-of-region motion does not yaw; re-entry does not apply the OOB span.
|
||||
#[test]
|
||||
fn out_of_region_motion_does_not_aim() {
|
||||
let mut state = playing_with_region();
|
||||
state.set_mouse_region(20, 5, 20, 10);
|
||||
state.game.player.angle = 0.0;
|
||||
state.handle_mouse(&mouse_at(MouseEventKind::Moved, 25, 10));
|
||||
state.handle_mouse(&mouse_at(MouseEventKind::Moved, 30, 10));
|
||||
let angle = state.game.player.angle;
|
||||
assert_eq!(angle, 5.0 * MOUSE_AIM_SENSITIVITY);
|
||||
|
||||
state.handle_mouse(&mouse_at(MouseEventKind::Moved, 100, 10));
|
||||
assert_eq!(state.game.player.angle, angle);
|
||||
state.handle_mouse(&mouse_at(MouseEventKind::Moved, 22, 10));
|
||||
assert_eq!(state.game.player.angle, angle);
|
||||
state.handle_mouse(&mouse_at(MouseEventKind::Moved, 24, 10));
|
||||
assert_eq!(state.game.player.angle, angle + 2.0 * MOUSE_AIM_SENSITIVITY);
|
||||
}
|
||||
|
||||
/// Left-click fires only when Playing and in-region (same queue as Space).
|
||||
#[test]
|
||||
fn click_fires_only_playing_in_region() {
|
||||
let mut state = playing_with_region();
|
||||
state.handle_mouse(&mouse_click(40, 10));
|
||||
state.tick();
|
||||
assert!(state.game.player.muzzle > 0.0);
|
||||
|
||||
let mut state = GboomState::new();
|
||||
state.set_mouse_region(0, 0, 200, 50);
|
||||
state.handle_mouse(&mouse_click(40, 10));
|
||||
state.tick();
|
||||
assert_eq!(state.game.player.muzzle, 0.0);
|
||||
|
||||
state.handle_key(&key(KeyCode::Char('w')));
|
||||
state.handle_mouse(&mouse_click(250, 10));
|
||||
state.tick();
|
||||
assert_eq!(state.game.player.muzzle, 0.0);
|
||||
|
||||
for phase in [Phase::Won, Phase::Dead] {
|
||||
let mut state = GboomState::new();
|
||||
state.set_mouse_region(0, 0, 200, 50);
|
||||
state.phase = phase;
|
||||
state.handle_mouse(&mouse_click(40, 10));
|
||||
state.tick();
|
||||
assert_eq!(state.game.player.muzzle, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// No region ⇒ no aim or click-fire.
|
||||
#[test]
|
||||
fn clear_mouse_region_disables_aim_and_fire() {
|
||||
let mut state = playing_with_region();
|
||||
state.game.player.angle = 0.0;
|
||||
state.handle_mouse(&mouse_moved(40));
|
||||
state.handle_mouse(&mouse_moved(45));
|
||||
let angle = state.game.player.angle;
|
||||
state.clear_mouse_region();
|
||||
state.handle_mouse(&mouse_moved(50));
|
||||
state.handle_mouse(&mouse_moved(55));
|
||||
assert_eq!(state.game.player.angle, angle);
|
||||
state.handle_mouse(&mouse_click(40, 10));
|
||||
state.tick();
|
||||
assert_eq!(state.game.player.muzzle, 0.0);
|
||||
}
|
||||
|
||||
/// Dumps representative frames to a temp dir for eyeballing.
|
||||
/// Run manually: `cargo test -p kigi-tui gboom::tests::dump -- --ignored`
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn dump_frames_for_visual_inspection() {
|
||||
let dir = std::env::temp_dir().join("grok-gboom-frames");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let dump = |name: &str, state: &mut GboomState| {
|
||||
state.sim_gen += 1;
|
||||
std::fs::write(dir.join(name), state.frame_png(480, 300).unwrap()).unwrap();
|
||||
};
|
||||
|
||||
// Title screen with developed fire.
|
||||
let mut state = GboomState::new();
|
||||
for _ in 0..70 {
|
||||
state.tick();
|
||||
}
|
||||
dump("title.png", &mut state);
|
||||
|
||||
// Corridor vantage: spawn looking south down the long west corridor.
|
||||
let mut state = GboomState::new();
|
||||
state.handle_key(&key(KeyCode::Char('w'))); // leave title
|
||||
state.phase = Phase::Playing;
|
||||
state.game.player.angle = std::f32::consts::FRAC_PI_2; // +y, south
|
||||
state.game.step(0.016);
|
||||
dump("game.png", &mut state);
|
||||
|
||||
// Imp 3 tiles ahead in that corridor, walking at us.
|
||||
state.game.imps[0].x = state.game.player.x;
|
||||
state.game.imps[0].y = state.game.player.y + 3.0;
|
||||
state.game.imps[0].state = game::ImpState::Chasing;
|
||||
// A second one further away to check fog/scale falloff.
|
||||
state.game.imps[1].x = state.game.player.x;
|
||||
state.game.imps[1].y = state.game.player.y + 6.0;
|
||||
state.game.imps[1].state = game::ImpState::Attacking { t: 0.2 };
|
||||
dump("imp.png", &mut state);
|
||||
|
||||
// Muzzle flash over that scene.
|
||||
state.game.queue_fire();
|
||||
state.game.step(0.016);
|
||||
dump("fire.png", &mut state);
|
||||
|
||||
// Damage flash + pain.
|
||||
state.game.player.damage_flash = 0.8;
|
||||
dump("hurt.png", &mut state);
|
||||
|
||||
// End screens (past the grace period so the hint line shows, with
|
||||
// the fire developed as it would be after a few seconds of play).
|
||||
for _ in 0..80 {
|
||||
state.fire.step();
|
||||
}
|
||||
state.phase = Phase::Dead;
|
||||
state.phase_time = 2.0;
|
||||
dump("dead.png", &mut state);
|
||||
state.phase = Phase::Won;
|
||||
dump("won.png", &mut state);
|
||||
|
||||
eprintln!("frames dumped to {}", dir.display());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user