Skip to main content

ob_game/
world.rs

1//! Runtime world state built from a Blood map.
2
3use ob_engine::geom;
4use ob_engine::map::{Map, Sector, Sprite, Wall, XSector, XSprite, XWall};
5use ob_engine::render::{Ror, RorLink};
6
7/// Blood status lists (sprite `statnum`).
8pub mod stat {
9    pub const DECORATION: i16 = 0;
10    pub const FX: i16 = 1;
11    pub const EXPLOSION: i16 = 2;
12    pub const ITEM: i16 = 3;
13    pub const THING: i16 = 4;
14    pub const PROJECTILE: i16 = 5;
15    pub const DUDE: i16 = 6;
16    pub const INACTIVE: i16 = 7;
17    pub const RESPAWN: i16 = 8;
18    pub const PURGE: i16 = 9;
19    pub const MARKER: i16 = 10;
20    pub const TRAPS: i16 = 11;
21    pub const AMBIENCE: i16 = 12;
22    pub const SPARES: i16 = 13;
23    pub const FLARE: i16 = 14;
24    pub const DEBRIS: i16 = 15;
25    pub const PATH_MARKER: i16 = 16;
26    pub const FREE: i16 = 1024;
27}
28
29/// Per-sprite runtime data not present in the map record.
30#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Default)]
31pub struct SpriteRt {
32    /// Velocity in xy units / z units per 120Hz tick.
33    pub vx: f64,
34    pub vy: f64,
35    pub vz: f64,
36    /// Current SEQ animation id and frame (-1 when none).
37    pub seq: i32,
38    pub seq_frame: i32,
39    pub seq_time: i32,
40    /// Health for dudes/things.
41    pub health: i32,
42    pub on_ground: bool,
43    pub ai_state: i32,
44    pub ai_timer: i32,
45    pub target: i32,
46    pub burn_time: i32,
47    /// Facing the dude was placed with (idle wandering turns back to it).
48    pub home_ang: i16,
49    /// Eye height above the feet (from the sprite's size), for sight checks.
50    pub eye: i32,
51}
52
53#[derive(serde::Serialize, serde::Deserialize)]
54pub struct World {
55    pub map_name: String,
56    pub sectors: Vec<Sector>,
57    pub walls: Vec<Wall>,
58    pub sprites: Vec<Sprite>,
59    pub rt: Vec<SpriteRt>,
60    pub xsectors: Vec<XSector>,
61    pub xwalls: Vec<XWall>,
62    pub xsprites: Vec<XSprite>,
63    pub sky_offsets: Vec<i16>,
64    pub sky_bits: i32,
65    pub visibility: i32,
66    pub song_id: i32,
67    /// Original floor/ceiling heights, used by movers.
68    pub base_floor: Vec<i32>,
69    pub base_ceil: Vec<i32>,
70    /// Original wall vertices, used by sliding/rotating sectors.
71    pub base_wall_xy: Vec<(i32, i32)>,
72    pub base_sprite_xy: Vec<(i32, i32, i32)>,
73    /// Original shades, used by sector lighting effects.
74    pub base_floor_shade: Vec<i8>,
75    pub base_ceil_shade: Vec<i8>,
76    pub base_wall_shade: Vec<i8>,
77    /// Floor/ceiling links between stacked rooms (all marker kinds, used for movement).
78    pub links: Vec<Ror>,
79    /// The subset of links you can see through (stacks and generic links; water is opaque).
80    pub ror_view: Vec<Ror>,
81}
82
83impl World {
84    pub fn from_map(name: &str, m: Map) -> Self {
85        let n = m.sprites.len();
86        let mut w = World {
87            map_name: name.to_string(),
88            base_floor: m.sectors.iter().map(|s| s.floor.z).collect(),
89            base_ceil: m.sectors.iter().map(|s| s.ceiling.z).collect(),
90            base_wall_xy: m.walls.iter().map(|w| (w.x, w.y)).collect(),
91            base_sprite_xy: m.sprites.iter().map(|s| (s.x, s.y, s.z)).collect(),
92            base_floor_shade: m.sectors.iter().map(|s| s.floor.shade).collect(),
93            base_ceil_shade: m.sectors.iter().map(|s| s.ceiling.shade).collect(),
94            base_wall_shade: m.walls.iter().map(|w| w.shade).collect(),
95            links: Vec::new(),
96            ror_view: Vec::new(),
97            sectors: m.sectors,
98            walls: m.walls,
99            sprites: m.sprites,
100            rt: vec![
101                SpriteRt {
102                    seq: -1,
103                    target: -1,
104                    ..Default::default()
105                };
106                n
107            ],
108            xsectors: m.xsectors,
109            xwalls: m.xwalls,
110            xsprites: m.xsprites,
111            sky_offsets: m.sky_offsets,
112            sky_bits: m.sky_bits as i32,
113            visibility: m.visibility,
114            song_id: m.song_id,
115        };
116        for (i, s) in w.sprites.iter().enumerate() {
117            if let Some(x) = (s.extra > 0).then(|| &w.xsprites[s.extra as usize]) {
118                w.rt[i].health = x.health as i32;
119            }
120        }
121        w.build_links();
122        w
123    }
124
125    pub fn xsector(&self, s: usize) -> Option<&XSector> {
126        let e = self.sectors.get(s)?.extra;
127        (e > 0).then(|| &self.xsectors[e as usize])
128    }
129    pub fn xsector_mut(&mut self, s: usize) -> Option<&mut XSector> {
130        let e = self.sectors.get(s)?.extra;
131        if e > 0 {
132            Some(&mut self.xsectors[e as usize])
133        } else {
134            None
135        }
136    }
137    pub fn xwall(&self, w: usize) -> Option<&XWall> {
138        let e = self.walls.get(w)?.extra;
139        (e > 0).then(|| &self.xwalls[e as usize])
140    }
141    pub fn xwall_mut(&mut self, w: usize) -> Option<&mut XWall> {
142        let e = self.walls.get(w)?.extra;
143        if e > 0 {
144            Some(&mut self.xwalls[e as usize])
145        } else {
146            None
147        }
148    }
149    pub fn xsprite(&self, s: usize) -> Option<&XSprite> {
150        let e = self.sprites.get(s)?.extra;
151        (e > 0).then(|| &self.xsprites[e as usize])
152    }
153    pub fn xsprite_mut(&mut self, s: usize) -> Option<&mut XSprite> {
154        let e = self.sprites.get(s)?.extra;
155        if e > 0 {
156            Some(&mut self.xsprites[e as usize])
157        } else {
158            None
159        }
160    }
161
162    pub fn zs_at(&self, sect: usize, x: f64, y: f64) -> (f64, f64) {
163        geom::zs_of_slope(&self.sectors, &self.walls, sect, x, y)
164    }
165
166    pub fn sector_walls(&self, s: usize) -> std::ops::Range<usize> {
167        let sec = &self.sectors[s];
168        sec.wallptr as usize..(sec.wallptr + sec.wallnum) as usize
169    }
170
171    /// Spawns a new sprite (reusing freed slots) and returns its index.
172    pub fn spawn(&mut self, s: Sprite) -> usize {
173        if let Some(i) = self.sprites.iter().position(|sp| sp.statnum == stat::FREE) {
174            self.sprites[i] = s;
175            self.rt[i] = SpriteRt {
176                seq: -1,
177                target: -1,
178                ..Default::default()
179            };
180            return i;
181        }
182        self.sprites.push(s);
183        self.rt.push(SpriteRt {
184            seq: -1,
185            target: -1,
186            ..Default::default()
187        });
188        self.base_sprite_xy.push((0, 0, 0));
189        self.sprites.len() - 1
190    }
191
192    pub fn delete_sprite(&mut self, i: usize) {
193        if let Some(s) = self.sprites.get_mut(i) {
194            s.statnum = stat::FREE;
195            s.cstat = 0x8000;
196            s.extra = -1;
197        }
198    }
199
200    /// Sprite indices with the given status number.
201    pub fn with_stat(&self, st: i16) -> Vec<usize> {
202        self.sprites
203            .iter()
204            .enumerate()
205            .filter(|(_, s)| s.statnum == st)
206            .map(|(i, _)| i)
207            .collect()
208    }
209
210    /// Pairs Blood's room-over-room markers. Odd types (7 link, 9 water, 11 stack, 13 goo)
211    /// sit in the upper room and make its floor a portal; the even partner (6, 10, 12, 14)
212    /// sits in the lower room and makes its ceiling a portal. Partners share `data1`.
213    pub fn build_links(&mut self) {
214        let n = self.sectors.len();
215        self.links = vec![Ror::default(); n];
216        self.ror_view = vec![Ror::default(); n];
217        let markers: Vec<(usize, i16, i32)> = self
218            .sprites
219            .iter()
220            .enumerate()
221            .filter(|(_, s)| matches!(s.lotag, 6 | 7 | 9..=14) && s.sectnum >= 0)
222            .map(|(i, s)| (i, s.lotag, self.xsprite(i).map_or(0, |x| x.data1)))
223            .collect();
224        for &(ui, ut, id) in markers.iter().filter(|m| m.1 % 2 == 1) {
225            let lower_type = if ut == 7 { 6 } else { ut + 1 };
226            let Some(&(li, _, _)) = markers.iter().find(|m| m.1 == lower_type && m.2 == id) else {
227                continue;
228            };
229            let (u, l) = (&self.sprites[ui], &self.sprites[li]);
230            let (us, ls) = (u.sectnum as usize, l.sectnum as usize);
231            if us >= n || ls >= n {
232                continue;
233            }
234            let down = RorLink {
235                sector: ls as i32,
236                dx: (l.x - u.x) as f64,
237                dy: (l.y - u.y) as f64,
238                dz: (l.z - u.z) as f64,
239            };
240            let up = RorLink {
241                sector: us as i32,
242                dx: -down.dx,
243                dy: -down.dy,
244                dz: -down.dz,
245            };
246            self.links[us].floor = Some(down);
247            self.links[ls].ceil = Some(up);
248            if matches!(ut, 7 | 11) {
249                self.ror_view[us].floor = Some(down);
250                self.ror_view[ls].ceil = Some(up);
251            }
252        }
253    }
254
255    pub fn player_start(&self, player: i32) -> Option<&Sprite> {
256        self.sprites
257            .iter()
258            .enumerate()
259            .find(|(i, s)| s.lotag == 1 && self.xsprite(*i).map_or(player == 0, |x| x.data1 == player))
260            .map(|(_, s)| s)
261            .or_else(|| self.sprites.iter().find(|s| s.lotag == 1))
262    }
263}