neurodoom 0.6.7

Deterministic no_std Doom engine with semantic and depth perception buffers for AI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! World state — the complete, serializable, deterministic game state.
//!
//! The `World` contains all entities and mutable sector state. It has no
//! rendering state, no behavior logic, no WAD data — just pure game state
//! that can be hashed, serialized, and verified across peers.

use alloc::collections::BTreeMap;
use alloc::vec::Vec;

use strum::EnumCount;

use crate::map::MapThing;
use crate::math::{Angle, Fixed, ANG90, FRACBITS, FRACUNIT};
use crate::specials::SpecialThinker;
use crate::types::{AmmoType, ArmorType, Card, WeaponType};

/// A 3D position + facing angle — the minimum description of where and
/// how an entity exists in the world.
///
/// `z` is typically overwritten with the floor height at `(x, y)` at
/// spawn time; callers usually only care about `x`, `y`, `angle`. Build
/// one with `Pose::on_floor(x, y, angle)` for the common case.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Pose {
    pub x: Fixed,
    pub y: Fixed,
    pub z: Fixed,
    pub angle: Angle,
}

impl Pose {
    /// Pose on the floor at the given `(x, y)`, with the given facing.
    /// The engine will sample the floor height at spawn time.
    #[inline]
    pub fn on_floor(x: Fixed, y: Fixed, angle: Angle) -> Self {
        Self { x, y, z: 0, angle }
    }

    /// Pose from a raw WAD `MapThing`, converting integer map coordinates
    /// to fixed-point and degree-based angles to BAM.
    #[inline]
    pub fn from_map_thing(thing: &MapThing) -> Self {
        let x = (thing.x as Fixed) << FRACBITS;
        let y = (thing.y as Fixed) << FRACBITS;
        let deg = (thing.angle as i32).rem_euclid(360) as u64;
        let angle = (deg * ANG90 as u64 / 90) as Angle;
        Self { x, y, z: 0, angle }
    }
}

/// Types that can report their `Pose`. Lets the renderer and other
/// systems accept anything "located in the world" without caring whether
/// it's an `Entity`, a camera viewpoint, or a projected sprite.
pub trait HasPose {
    fn pose(&self) -> Pose;
}

impl HasPose for Pose {
    #[inline]
    fn pose(&self) -> Pose {
        *self
    }
}

impl HasPose for Entity {
    #[inline]
    fn pose(&self) -> Pose {
        Pose {
            x: self.x,
            y: self.y,
            z: self.z,
            angle: self.angle,
        }
    }
}

/// Unique identifier for an entity in the world.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct EntityId(pub u32);

pub use crate::game_data::EntityType;

/// Identifies a peer/player in a multiplayer game.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct PeerId(pub u32);

/// Mutable sector state (heights and light change during gameplay).
#[derive(Clone, Debug)]
pub struct SectorState {
    pub floor_height: Fixed,
    pub ceiling_height: Fixed,
    pub light_level: i16,
    pub special: i16,
}

/// Per-player inventory and status — only exists for player-controlled entities.
#[derive(Clone, Debug)]
pub struct PlayerState {
    pub armor_points: i32,
    pub armor_type: ArmorType,
    pub ammo: [i32; AmmoType::COUNT],
    pub max_ammo: [i32; AmmoType::COUNT],
    pub weapon_owned: [bool; WeaponType::COUNT],
    pub ready_weapon: WeaponType,
    pub pending_weapon: WeaponType,
    pub cards: [bool; Card::COUNT],
    pub use_down: bool,
    pub attack_down: bool,
    /// Number of consecutive refires (0 = first shot, accurate).
    pub refire_count: i32,
    pub kill_count: i32,
    pub item_count: i32,
    pub secret_count: i32,
    /// Weapon psprite state machine.
    pub psp_state: crate::game_data::StateNum,
    pub psp_tics: i32,
    /// Weapon psprite screen position (fixed-point).
    pub psp_sx: Fixed,
    pub psp_sy: Fixed,
    /// Muzzle flash psprite (overlaid on weapon during fire).
    pub flash_state: crate::game_data::StateNum,
    pub flash_tics: i32,
    /// Bob magnitude (derived from player momentum, fixed-point).
    pub bob: Fixed,
}

impl Default for PlayerState {
    fn default() -> Self {
        Self::new()
    }
}

impl PlayerState {
    pub fn new() -> Self {
        Self {
            armor_points: 0,
            armor_type: ArmorType::None,
            ammo: [50, 0, 0, 0], // start with 50 bullets
            max_ammo: [200, 50, 300, 50],
            weapon_owned: [true, true, false, false, false, false, false, false, false],
            ready_weapon: WeaponType::Pistol,
            pending_weapon: WeaponType::Pistol,
            cards: [false; Card::COUNT],
            use_down: false,
            attack_down: false,
            refire_count: 0,
            kill_count: 0,
            item_count: 0,
            secret_count: 0,
            psp_state: crate::game_data::S_PISTOL,
            psp_tics: 1,
            psp_sx: FRACUNIT, // centered
            psp_sy: 32 * FRACUNIT, // WEAPONTOP
            flash_state: crate::game_data::StateNum::NULL,
            flash_tics: 0,
            bob: 0,
        }
    }

    pub fn give_ammo(&mut self, ammo: AmmoType, amount: i32) -> bool {
        let i = ammo as usize;
        let (Some(cur), Some(&max)) = (self.ammo.get_mut(i), self.max_ammo.get(i)) else {
            return false;
        };
        if *cur >= max {
            return false;
        }
        *cur = cur.saturating_add(amount).min(max);
        true
    }

    /// Mark a weapon as owned. No-op on unknown indices (defensive).
    pub fn grant_weapon(&mut self, w: WeaponType) {
        if let Some(slot) = self.weapon_owned.get_mut(w as usize) {
            *slot = true;
        }
    }

    /// Mark a keycard/skull as held. No-op on unknown indices (defensive).
    pub fn grant_card(&mut self, c: Card) {
        if let Some(slot) = self.cards.get_mut(c as usize) {
            *slot = true;
        }
    }

    /// Double the max capacity of every ammo slot (backpack pickup).
    pub fn double_max_ammo(&mut self) {
        for slot in &mut self.max_ammo {
            *slot = slot.saturating_mul(2);
        }
    }
}

/// Complete game state — deterministic, serializable.
/// What kind of exit the player triggered.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LevelExit {
    /// Level still in progress.
    #[default]
    None,
    /// Normal exit (line specials 11, 52, 124).
    Normal,
    /// Secret exit (line special 51 — goes to the episode's secret map).
    Secret,
}

/// Classify a linedef special as a normal or secret exit.
#[inline]
pub fn exit_kind(special: i16) -> LevelExit {
    use crate::map::line_special::EXIT_SECRET;
    if special == EXIT_SECRET {
        LevelExit::Secret
    } else {
        LevelExit::Normal
    }
}

pub struct World {
    entities: Vec<Option<Entity>>,
    id_to_slot: BTreeMap<EntityId, usize>,
    free_slots: Vec<usize>,
    next_id: u32,
    pub sectors: Vec<SectorState>,
    pub tick: u32,
    /// Set when a player crosses / uses an exit line. Part of the
    /// deterministic game state; cleared on next map load.
    pub level_exit: LevelExit,
    /// Maps peers to the entities they control. Networking concern,
    /// not stored on Entity — entities don't know about peers.
    controllers: BTreeMap<PeerId, EntityId>,
    /// Per-player inventory state, keyed by the entity they control.
    player_states: BTreeMap<EntityId, PlayerState>,
    /// Sector special thinkers (doors, lifts, lights).
    pub specials: Vec<SpecialThinker>,
    /// Reusable scratch buffer for snapshotting entity IDs during iteration.
    id_scratch: Vec<EntityId>,
    /// Doom-compatible PRNG index (deterministic, uses fixed table).
    prng_index: u8,
}

impl World {
    pub fn new(sectors: Vec<SectorState>) -> Self {
        Self {
            entities: Vec::new(),
            id_to_slot: BTreeMap::new(),
            free_slots: Vec::new(),
            next_id: 1,
            sectors,
            tick: 0,
            level_exit: LevelExit::None,
            controllers: BTreeMap::new(),
            player_states: BTreeMap::new(),
            specials: Vec::new(),
            id_scratch: Vec::new(),
            prng_index: 0,
        }
    }

    /// Assign a peer to control an entity and initialize its player state.
    pub fn set_controller(&mut self, peer: PeerId, entity: EntityId) {
        self.controllers.insert(peer, entity);
        self.player_states.entry(entity).or_default();
    }

    /// Get player state for an entity (if it's player-controlled).
    pub fn player_state(&self, entity: EntityId) -> Option<&PlayerState> {
        self.player_states.get(&entity)
    }

    /// Get mutable player state for an entity.
    pub fn player_state_mut(&mut self, entity: EntityId) -> Option<&mut PlayerState> {
        self.player_states.get_mut(&entity)
    }

    /// Which entity does this peer control?
    pub fn controlled_by(&self, peer: PeerId) -> Option<EntityId> {
        self.controllers.get(&peer).copied()
    }

    /// Is this entity controlled by any peer?
    pub fn is_controlled(&self, entity: EntityId) -> bool {
        self.controllers.values().any(|&eid| eid == entity)
    }

    /// Iterate over all controlled entity IDs (all players).
    pub fn controlled_entities(&self) -> impl Iterator<Item = EntityId> + '_ {
        self.controllers.values().copied()
    }

    /// Spawn an entity. Returns its ID.
    pub fn spawn(&mut self, mut entity: Entity) -> EntityId {
        let id = EntityId(self.next_id);
        self.next_id = self.next_id.wrapping_add(1);
        entity.id = id;

        // Reuse a free slot if possible (and that slot is actually valid);
        // otherwise push a new one.
        let reused = self
            .free_slots
            .pop()
            .filter(|&s| s < self.entities.len());
        let slot = match reused {
            Some(s) => {
                if let Some(cell) = self.entities.get_mut(s) {
                    *cell = Some(entity);
                }
                s
            }
            None => {
                let slot = self.entities.len();
                self.entities.push(Some(entity));
                slot
            }
        };
        self.id_to_slot.insert(id, slot);
        id
    }

    /// Remove an entity.
    pub fn remove(&mut self, id: EntityId) {
        if let Some(slot) = self.id_to_slot.remove(&id)
            && let Some(cell) = self.entities.get_mut(slot)
        {
            *cell = None;
            self.free_slots.push(slot);
        }
    }

    /// Get entity by ID.
    pub fn get(&self, id: EntityId) -> Option<&Entity> {
        let &slot = self.id_to_slot.get(&id)?;
        self.entities.get(slot)?.as_ref()
    }

    /// Get mutable entity by ID.
    pub fn get_mut(&mut self, id: EntityId) -> Option<&mut Entity> {
        let &slot = self.id_to_slot.get(&id)?;
        self.entities.get_mut(slot)?.as_mut()
    }

    /// Iterate all active entities.
    pub fn iter(&self) -> impl Iterator<Item = &Entity> {
        self.entities.iter().filter_map(|s| s.as_ref())
    }

    /// Take a snapshot of active entity IDs into the scratch buffer.
    /// Caller must return it via `return_id_scratch` when done.
    pub fn take_entity_ids(&mut self) -> Vec<EntityId> {
        self.id_scratch.clear();
        self.id_scratch.extend(
            self.entities.iter().filter_map(|s| s.as_ref().map(|e| e.id))
        );
        core::mem::take(&mut self.id_scratch)
    }

    /// Return the scratch buffer for reuse.
    pub fn return_id_scratch(&mut self, buf: Vec<EntityId>) {
        self.id_scratch = buf;
    }

    /// Number of active entities.
    pub fn entity_count(&self) -> usize {
        self.id_to_slot.len()
    }

    /// Doom-compatible P_Random: returns 0..255 from a fixed lookup table.
    pub fn p_random(&mut self) -> i32 {
        self.prng_index = self.prng_index.wrapping_add(1);
        // `prng_index` is u8 (0..=255), RNDTABLE has 256 entries, so this
        // is always in-bounds — the compiler elides the bounds check.
        #[allow(clippy::indexing_slicing)]
        let v = RNDTABLE[self.prng_index as usize];
        v as i32
    }
}

/// Doom's fixed random number table (256 entries).
static RNDTABLE: [u8; 256] = [
      0,   8, 109, 220, 222, 241, 149, 107,  75, 248, 254, 140,  16,  66,  74,  21,
    211,  47,  80, 242, 154,  27, 205, 128, 161,  89,  77,  36,  95, 110,  85,  48,
    212, 140, 211, 249,  22,  79, 200,  50,  28, 188,  52, 140, 202, 120,  68, 145,
     62,  70, 184, 190,  91, 197, 152, 224, 149, 104,  25, 178, 252, 182, 202, 182,
    141, 197,   4,  81, 181, 242, 145,  42,  39, 227, 156, 198, 225, 193, 219,  93,
    122, 175, 249,   0, 175, 143,  70, 239,  46, 246, 163,  53, 163, 109, 168, 135,
      2, 235,  25,  92,  20, 145, 138,  77,  69, 166,  78, 176, 173, 212, 166, 113,
     94, 161,  41,  50, 239,  49, 111, 164,  70,  60,   2,  37, 171,  75, 136, 156,
     11,  56,  42, 146, 138, 229,  73, 146,  77,  61,  98, 196, 135, 106,  63, 197,
    195,  86,  96, 203, 113, 101, 170, 247, 181, 113,  80, 250, 108,   7, 255, 237,
    129, 226,  79, 107, 112, 166, 103, 241,  24, 223, 239, 120, 198,  58,  60,  82,
    128,   3, 184,  66, 143, 224, 145, 224,  81, 206, 163,  45,  63,  90, 168, 114,
     59,  33, 159,  95,  28, 139, 123,  98, 125, 196,  15,  70, 194, 253,  54,  14,
    109, 226,  71,  17, 161,  93, 186,  87, 244, 138,  20,  52, 123, 204,  51, 233,
    231, 243, 213, 187, 128, 173,  85, 203, 197, 235,  60, 129, 148,  64, 107, 171,
     55,  82, 100, 186, 249, 206, 162, 227, 159,  28, 168, 174, 122, 110, 187, 213,
];

/// An entity in the world.
#[derive(Clone, Debug)]
pub struct Entity {
    pub id: EntityId,
    pub entity_type: EntityType,

    // Position
    pub x: Fixed,
    pub y: Fixed,
    pub z: Fixed,
    pub angle: Angle,
    pub floor_z: Fixed,
    pub ceiling_z: Fixed,

    // Physics
    pub momx: Fixed,
    pub momy: Fixed,
    pub momz: Fixed,
    pub radius: Fixed,
    pub height: Fixed,

    // Gameplay
    pub health: i32,
    pub flags: crate::game_data::MobjFlags,

    // Rendering
    pub sprite: crate::game_data::SpriteNum,
    pub frame: i32,

    // State machine (used by classic behavior, ignored by puppets)
    pub state: crate::game_data::StateNum,
    pub tics: i32,

    // AI (used by classic behavior)
    pub target: Option<EntityId>,
    pub reaction_time: i32,
    pub move_dir: u8,
    pub move_count: i32,
}

impl Default for Entity {
    /// Truly empty entity — all fields zero / null. Intended as a
    /// starting point inside the engine's spawn paths, which then
    /// overwrite radius, height, health, flags, and spawn state from
    /// the MOBJINFO table. Do NOT use `..Entity::default()` from
    /// outside the crate to build a playable entity: it will have
    /// zero health / radius / height and misbehave. Use
    /// `DoomEngine::spawn_entity(kind, pose)` instead.
    fn default() -> Self {
        Self {
            id: EntityId(0),
            entity_type: EntityType(0),
            x: 0, y: 0, z: 0, angle: 0,
            floor_z: 0, ceiling_z: 0,
            momx: 0, momy: 0, momz: 0,
            radius: 0,
            height: 0,
            health: 0,
            flags: crate::game_data::MobjFlags::empty(),
            sprite: crate::game_data::SpriteNum(0), frame: 0,
            state: crate::game_data::StateNum::NULL, tics: -1,
            target: None,
            reaction_time: 0,
            move_dir: 0,
            move_count: 0,
        }
    }
}