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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
// Engine orchestrates per-tick work and per-frame rendering; sector /
// line indices are loader-validated and HUD pixel offsets are proven in
// bounds by the surrounding `if sx < SCREENWIDTH && sy < SCREENHEIGHT`
// guards. See policy in src/render/mod.rs.
#![allow(clippy::indexing_slicing)]

//! Top-level engine — owns the world, map, textures, and renderer, and
//! exposes the tick / render API.
//!
//! For single-player: build a [`ClassicEngine`] via `ClassicEngine::new`
//! and drive it with [`DoomEngine::tick`] / [`DoomEngine::tick_single`].
//! For multi-peer: build via `DoomEngine::new_with_rules`, spawn players
//! with [`DoomEngine::spawn_player`], then alternate
//! [`DoomEngine::simulate`] + [`DoomEngine::render_for`] per peer each
//! frame.

use alloc::vec::Vec;

use crate::game_data::MOBJINFO;
use crate::map::MapData;
use crate::math::*;
use crate::render::sprites::ThingRef;
use crate::render::Renderer;
use crate::world::HasPose;
use crate::rules::{GameRules, PlayerAction, WorldAction};
use crate::specials;
use crate::texture::TextureData;
use crate::wad::Wad;
use crate::world::{Entity, EntityId, EntityType, PeerId, Pose, SectorState, World};

/// The top-level Doom engine, generic over game rules.
///
/// For classic single-player: `DoomEngine<ClassicDoomRules>`
/// For custom multiplayer: `DoomEngine<YourRules>`
///
/// Fields are crate-private. Use `world()`/`world_mut()`, `map()`/`map_mut()`,
/// `textures()`, `renderer()`/`renderer_mut()` to access them.
pub struct DoomEngine<R: GameRules> {
    pub(crate) rules: R,
    pub(crate) world: World,
    pub(crate) map: MapData,
    pub(crate) textures: TextureData,
    pub(crate) renderer: Renderer,
    thing_refs: Vec<ThingRef>,
}

impl<R: GameRules> DoomEngine<R> {
    /// Borrow the rules.
    #[inline]
    pub fn rules(&self) -> &R {
        &self.rules
    }
    /// Borrow the world state (entities, sectors, controllers).
    #[inline]
    pub fn world(&self) -> &World {
        &self.world
    }
    /// Borrow the world state mutably.
    #[inline]
    pub fn world_mut(&mut self) -> &mut World {
        &mut self.world
    }
    /// Borrow the loaded map geometry.
    #[inline]
    pub fn map(&self) -> &MapData {
        &self.map
    }
    /// Borrow the loaded map geometry mutably (e.g. to clear secret
    /// sectors or adjust sector specials before a run).
    #[inline]
    pub fn map_mut(&mut self) -> &mut MapData {
        &mut self.map
    }
    /// Borrow the loaded textures, patches, flats, and palettes.
    #[inline]
    pub fn textures(&self) -> &TextureData {
        &self.textures
    }
    /// Borrow the renderer. Normally you don't need this — use
    /// `render_for(peer)` and the framebuffer getters instead.
    #[inline]
    pub fn renderer(&self) -> &Renderer {
        &self.renderer
    }
    /// Mutable borrow of the renderer. Exposed for low-level integration
    /// tests that drive the renderer directly (see `tests/compare_puredoom.rs`).
    #[inline]
    pub fn renderer_mut(&mut self) -> &mut Renderer {
        &mut self.renderer
    }
    /// Split borrow: `&mut Renderer` + `&MapData` + `&TextureData`
    /// simultaneously. Needed for low-level integration tests that call
    /// renderer methods (which require `&mut self`) while also passing
    /// `&map` / `&textures` by reference.
    #[inline]
    pub fn render_parts_mut(&mut self) -> (&mut Renderer, &MapData, &TextureData) {
        (&mut self.renderer, &self.map, &self.textures)
    }
    /// Has the level been completed (player crossed an exit line)?
    #[inline]
    pub fn level_complete(&self) -> bool {
        self.world.level_exit != crate::world::LevelExit::None
    }

    /// Which kind of exit was used (or `LevelExit::None` if still in-play).
    #[inline]
    pub fn level_exit(&self) -> crate::world::LevelExit {
        self.world.level_exit
    }

    /// Spawn an entity of `kind` at `pose`, reading radius / height /
    /// spawn health / flags / spawn state from `MOBJINFO`. `pose.z` is
    /// overwritten with the floor height at `(pose.x, pose.y)`.
    ///
    /// Returns `None` if `kind` isn't in the mobj table.
    pub fn spawn_entity(&mut self, kind: EntityType, pose: Pose) -> Option<EntityId> {
        let info = kind.info()?;
        let (fz, cz) = crate::physics::find_sector_heights(&self.map, pose.x, pose.y);
        let mut entity = Entity {
            entity_type: kind,
            x: pose.x,
            y: pose.y,
            z: fz,
            angle: pose.angle,
            floor_z: fz,
            ceiling_z: cz,
            radius: info.radius,
            height: info.height,
            health: info.spawnhealth,
            flags: info.flags(),
            reaction_time: info.reactiontime,
            ..Entity::default()
        };
        if let Some(st) = info.spawnstate.get() {
            entity.sprite = st.sprite;
            entity.frame = st.frame;
            entity.state = info.spawnstate;
            entity.tics = st.tics;
        }
        Some(self.world.spawn(entity))
    }

    /// Spawn an MT_PLAYER entity at `pose` and bind it to `peer`.
    /// Returns `None` if the player mobj type is missing from MOBJINFO.
    pub fn spawn_player(&mut self, peer: PeerId, pose: Pose) -> Option<EntityId> {
        let eid = self.spawn_entity(EntityType(0), pose)?;
        self.world.set_controller(peer, eid);
        Some(eid)
    }

    /// Teleport an existing entity to a fresh `pose` and reset it to
    /// its spawn state (health, flags, state machine). Typical use:
    /// respawning a dead bot without removing/recreating the entity.
    ///
    /// Returns `None` if the entity doesn't exist or its kind is unknown.
    pub fn respawn(&mut self, eid: EntityId, pose: Pose) -> Option<()> {
        let kind = self.world.get(eid)?.entity_type;
        let info = kind.info()?;
        let (fz, cz) = crate::physics::find_sector_heights(&self.map, pose.x, pose.y);
        let e = self.world.get_mut(eid)?;
        e.x = pose.x;
        e.y = pose.y;
        e.z = fz;
        e.floor_z = fz;
        e.ceiling_z = cz;
        e.angle = pose.angle;
        e.momx = 0;
        e.momy = 0;
        e.momz = 0;
        e.health = info.spawnhealth;
        e.flags = info.flags();
        if let Some(st) = info.spawnstate.get() {
            e.sprite = st.sprite;
            e.frame = st.frame;
            e.state = info.spawnstate;
            e.tics = st.tics;
        }
        Some(())
    }
}

/// Error during engine initialization.
#[derive(Debug)]
pub enum DoomError {
    WadError(crate::wad::WadError),
    MapError(crate::map::MapError),
    TextureError(crate::texture::TextureError),
    NoPlayerStart,
}

impl core::fmt::Display for DoomError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::WadError(e) => write!(f, "WAD parse error: {e}"),
            Self::MapError(e) => write!(f, "map load error: {e}"),
            Self::TextureError(e) => write!(f, "texture load error: {e}"),
            Self::NoPlayerStart => write!(f, "map has no PLAYER1_START thing"),
        }
    }
}

impl core::error::Error for DoomError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::WadError(e) => Some(e),
            Self::MapError(e) => Some(e),
            Self::TextureError(e) => Some(e),
            Self::NoPlayerStart => None,
        }
    }
}

impl<R: GameRules> DoomEngine<R> {
    /// Create a new engine with custom rules. Loads map geometry and textures
    /// from the WAD but does NOT spawn entities — call `spawn_map_things()`
    /// for classic Doom or spawn entities manually.
    pub fn new_with_rules(wad_data: &[u8], map_name: &str, rules: R) -> Result<Self, DoomError> {
        let wad = Wad::parse(wad_data).map_err(DoomError::WadError)?;
        let mut map = MapData::load(&wad, map_name).map_err(DoomError::MapError)?;
        let textures = TextureData::load(&wad).map_err(DoomError::TextureError)?;
        map.resolve_textures(&textures);

        let mut renderer = Renderer::new();

        let sky_name = *b"F_SKY1\0\0";
        renderer.sky_flat_num = textures.flat_num_for_name(&sky_name);
        let sky_tex_name = *b"SKY1\0\0\0\0";
        renderer.sky_texture_num = textures.texture_num_for_name(&sky_tex_name);

        let world = world_from_map(&map);

        Ok(Self {
            rules,
            world,
            map,
            textures,
            renderer,
            thing_refs: Vec::new(),
        })
    }

    /// Swap the current map for `map_name` loaded from `wad_data`. Resets
    /// the world (entities, sectors, specials, tick, level_exit) but keeps
    /// the textures, renderer, and rules. Call `spawn_map_things(peer)`
    /// afterwards to re-populate the new map with its starts and items.
    ///
    /// Typical use: level progression in a single-player loop — after
    /// `engine.level_complete()` goes true, pick the next map with your
    /// own logic (see `examples/classic.rs`) and feed it here.
    pub fn load_map(&mut self, wad_data: &[u8], map_name: &str) -> Result<(), DoomError> {
        let wad = Wad::parse(wad_data).map_err(DoomError::WadError)?;
        let mut map = MapData::load(&wad, map_name).map_err(DoomError::MapError)?;
        map.resolve_textures(&self.textures);
        self.world = world_from_map(&map);
        self.map = map;
        self.thing_refs.clear();
        Ok(())
    }

    /// Spawn entities from the WAD's THINGS lump (classic Doom map things).
    /// Call after `new_with_rules()` for a classic single-player experience.
    pub fn spawn_map_things(&mut self, local_peer: PeerId) {
        use crate::types::doomednum as dn;
        // Snapshot so we don't hold a borrow of `self.map.things` while
        // spawn_entity() mutates self.
        let things = self.map.things.to_vec();
        for thing in &things {
            let pose = Pose::from_map_thing(thing);
            if thing.type_num == dn::PLAYER1_START {
                self.spawn_player(local_peer, pose);
                continue;
            }
            // Other player/deathmatch starts are skipped in single-player.
            if (dn::PLAYER2_START..=dn::PLAYER4_START).contains(&thing.type_num) {
                continue;
            }
            if let Some(kind) = doomednum_to_type(thing.type_num as i32) {
                self.spawn_entity(kind, pose);
            }
        }
    }

    /// Advance one tick of simulation only — no rendering. Useful when you
    /// drive rendering yourself (e.g. multi-bot demos that call `render_for`
    /// per peer). Pair with one or more `render_for(peer)` calls.
    pub fn simulate(
        &mut self,
        player_actions: &[(PeerId, PlayerAction)],
        world_actions: &[WorldAction],
    ) {
        self.rules
            .tick(&mut self.world, &self.map, player_actions, world_actions);

        // Update sector specials (doors, lifts, lights)
        specials::update_specials(&mut self.world.specials, &mut self.map.sectors);

        // Sync mutable sector state back to world
        for (i, sector) in self.map.sectors.iter().enumerate() {
            if i < self.world.sectors.len() {
                self.world.sectors[i].floor_height = sector.floor_height;
                self.world.sectors[i].ceiling_height = sector.ceiling_height;
                self.world.sectors[i].light_level = sector.light_level;
            }
        }

        // Update entity floor_z/ceiling_z when sectors move (prevents floating corpses)
        let ids = self.world.take_entity_ids();
        for &id in &ids {
            let is_player = self.world.is_controlled(id);
            if let Some(entity) = self.world.get_mut(id) {
                let (fz, cz) = crate::physics::find_sector_heights(&self.map, entity.x, entity.y);
                // Non-player entities on the floor follow it down/up
                // Players handle their own z via physics (gravity/stepping)
                if !is_player && (entity.z == entity.floor_z || entity.z < fz) {
                    entity.z = fz;
                }
                entity.floor_z = fz;
                entity.ceiling_z = cz;
            }
        }
        self.world.return_id_scratch(ids);
    }

    /// Advance one tick and render the local player's view (PeerId(0)).
    /// Convenience for single-player flows; for multi-peer rendering,
    /// call `simulate()` and then `render_for(peer)` per peer instead.
    pub fn tick(
        &mut self,
        player_actions: &[(PeerId, PlayerAction)],
        world_actions: &[WorldAction],
    ) {
        self.simulate(player_actions, world_actions);
        self.render_for(PeerId(0));
    }

    /// Convenience: tick with a single local player's input.
    pub fn tick_single(&mut self, peer: PeerId, input: PlayerAction) {
        self.tick(&[(peer, input)], &[]);
    }

    fn player_view(&self, peer: PeerId) -> Pose {
        let Some(eid) = self.world.controlled_by(peer) else {
            return Pose::default();
        };
        let Some(e) = self.world.get(eid) else {
            return Pose::default();
        };
        let Some(ps) = self.world.player_state(eid) else {
            return e.pose();
        };

        // Dead — drop the view low (Doom's DEATHVIEWHEIGHT) and stop bobbing.
        if e.health <= 0 {
            let mut v = e.pose();
            v.z = e.z + 6 * FRACUNIT;
            return v;
        }

        // View bob: sinusoidal oscillation from player momentum
        // Original Doom: angle = (FINEANGLES/20 * leveltime) & FINEMASK
        //                bob = (player->bob/2) * finesine[angle]
        let bob_angle = (FINEANGLES / 20 * self.world.tick as usize) & FINEMASK;
        let view_bob = fixed_mul(ps.bob / 2, finesine(bob_angle));
        let mut v = e.pose();
        v.z = e.z + 41 * FRACUNIT + view_bob;
        v
    }

    /// Render the world from `peer`'s POV, including 3D scene, that player's
    /// weapon overlay (with bob + muzzle flash), and the bottom HUD. Leaves
    /// `framebuffer()`, `semantic_buffer()`, and `depth_buffer()` populated
    /// for that POV. Called automatically by `tick()` for `PeerId(0)`; call
    /// it explicitly to render any other peer's view (e.g. multi-bot demos).
    pub fn render_for(&mut self, peer: PeerId) {
        let view_entity = self.world.controlled_by(peer);
        let view = self.player_view(peer);
        self.renderer
            .render_player_view(&self.map, &self.textures, &view);

        // Draw sprites for all entities (skip the one we're viewing from)
        self.thing_refs.clear();
        self.thing_refs.extend(
            self.world
                .iter()
                .filter(|e| Some(e.id) != view_entity)
                .map(|e| ThingRef {
                    x: e.x,
                    y: e.y,
                    z: e.z,
                    angle: e.angle,
                    sprite_num: e.sprite.0 as usize,
                    frame: e.frame as usize,
                    flags: e.flags.bits(),
                    mobj_type: e.entity_type.0,
                    light_level: sector_light_at(&self.map, e.x, e.y),
                }),
        );
        self.renderer.draw_things(&self.thing_refs, &self.textures);

        // Draw masked midtextures AFTER sprites, with depth testing
        self.renderer.draw_masked_walls(&self.map, &self.textures);

        // Draw weapon overlay for this peer (only while alive)
        let alive = view_entity
            .and_then(|eid| self.world.get(eid))
            .is_some_and(|e| e.health > 0);
        if alive
            && let Some(ps) = view_entity.and_then(|eid| self.world.player_state(eid))
        {
            self.renderer
                .draw_weapon_psp(ps.psp_state, ps.psp_sx, ps.psp_sy, &self.textures);
            // Draw muzzle flash overlay (same position as weapon)
            if !ps.flash_state.is_null() {
                self.renderer
                    .draw_weapon_psp(ps.flash_state, ps.psp_sx, ps.psp_sy, &self.textures);
            }
        }

        // HUD overlay (drawn on top of the 3D scene). Build the inputs
        // from the viewing peer's entity + player state, then hand off to
        // render::hud which has no World dependency.
        if let Some(eid) = view_entity
            && let Some(e) = self.world.get(eid)
        {
            let (armor, ammo, weapon) = self
                .world
                .player_state(eid)
                .map(|ps| (ps.armor_points, ps.ammo, ps.ready_weapon))
                .unwrap_or((0, [0; 4], crate::types::WeaponType::Pistol));
            self.renderer
                .draw_hud(crate::render::HudFrame::from_stats(e.health, armor, ammo, weapon));
        }

        self.renderer.indexed_to_rgba(&self.textures);
    }

    pub fn framebuffer(&self) -> &[u8] {
        &self.renderer.rgba
    }
    pub fn semantic_buffer(&self) -> &[u8] {
        &self.renderer.semantic
    }
    pub fn depth_buffer(&self) -> &[Fixed] {
        &self.renderer.depth
    }
    pub fn buffer_size(&self) -> (usize, usize) {
        (SCREENWIDTH, SCREENHEIGHT)
    }

}

/// Convenience type alias for classic single-player.
pub type ClassicEngine = DoomEngine<crate::classic::ClassicDoomRules>;

impl ClassicEngine {
    /// Create a classic Doom engine — loads WAD, spawns map things, ready to play.
    pub fn new(wad_data: &[u8], map_name: &str) -> Result<Self, DoomError> {
        let mut engine =
            Self::new_with_rules(wad_data, map_name, crate::classic::ClassicDoomRules)?;
        engine.spawn_map_things(PeerId(0));
        Ok(engine)
    }
}

// --- Helpers ---

/// Build a fresh `World` from a map — sector snapshot + spawned specials.
fn world_from_map(map: &MapData) -> World {
    let sectors = map
        .sectors
        .iter()
        .map(|s| SectorState {
            floor_height: s.floor_height,
            ceiling_height: s.ceiling_height,
            light_level: s.light_level,
            special: s.special,
        })
        .collect();
    let mut world = World::new(sectors);
    world.specials = specials::spawn_specials(map);
    world
}

fn sector_light_at(map: &MapData, x: Fixed, y: Fixed) -> i16 {
    let ssect = crate::physics::find_subsector(map, x, y);
    if ssect < map.subsectors.len() {
        map.sectors[map.subsectors[ssect].sector as usize].light_level
    } else {
        160
    }
}

fn doomednum_to_type(doomednum: i32) -> Option<EntityType> {
    MOBJINFO
        .iter()
        .enumerate()
        .find(|(_, info)| info.doomednum == doomednum)
        .map(|(i, _)| EntityType(i as u16))
}