Skip to main content

ob_game/
triggers.rs

1//! Blood's object messaging system: x-objects listen on receive channels (`rx_id`),
2//! change state when commanded (optionally animated over a busy time), and broadcast
3//! their own command on `tx_id` when reaching the on/off state.
4
5use crate::world::World;
6use std::collections::HashMap;
7
8pub mod cmd {
9    pub const OFF: u8 = 0;
10    pub const ON: u8 = 1;
11    pub const STATE: u8 = 2;
12    pub const TOGGLE: u8 = 3;
13    pub const NOT_STATE: u8 = 4;
14    pub const LINK: u8 = 5;
15    pub const LOCK: u8 = 6;
16    pub const UNLOCK: u8 = 7;
17    pub const TOGGLE_LOCK: u8 = 8;
18    pub const STOP_OFF: u8 = 9;
19    pub const STOP_ON: u8 = 10;
20    pub const STOP_NEXT: u8 = 11;
21    pub const COUNTER_SECTOR: u8 = 12;
22    pub const CALLBACK: u8 = 20;
23    pub const REPEAT: u8 = 21;
24    pub const SPRITE_PUSH: u8 = 30;
25    pub const SPRITE_IMPACT: u8 = 31;
26    pub const SPRITE_PICKUP: u8 = 32;
27    pub const SPRITE_TOUCH: u8 = 33;
28    pub const SPRITE_SIGHT: u8 = 34;
29    pub const SPRITE_PROXIMITY: u8 = 35;
30    pub const SPRITE_EXPLODE: u8 = 36;
31    pub const SECTOR_PUSH: u8 = 40;
32    pub const SECTOR_IMPACT: u8 = 41;
33    pub const SECTOR_ENTER: u8 = 42;
34    pub const SECTOR_EXIT: u8 = 43;
35    pub const WALL_PUSH: u8 = 50;
36    pub const WALL_IMPACT: u8 = 51;
37    pub const WALL_TOUCH: u8 = 52;
38}
39
40/// Reserved channels.
41pub mod chan {
42    pub const SET_TOTAL_SECRETS: u32 = 1;
43    pub const SECRET_FOUND: u32 = 2;
44    pub const TEXT_OVER: u32 = 3;
45    pub const LEVEL_EXIT_NORMAL: u32 = 4;
46    pub const LEVEL_EXIT_SECRET: u32 = 5;
47    /// Broadcast once when a single-player level starts.
48    pub const LEVEL_START: u32 = 7;
49    pub const LEVEL_START_MATCH: u32 = 8;
50    pub const LEVEL_START_COOP: u32 = 9;
51    pub const FIRST_USER: u32 = 100;
52}
53
54pub mod sector_type {
55    pub const Z_MOTION: i16 = 600;
56    pub const Z_MOTION_SPRITE: i16 = 602;
57    pub const WARP: i16 = 603;
58    pub const TELEPORT: i16 = 604;
59    pub const PATH: i16 = 612;
60    pub const ROTATE_STEP: i16 = 613;
61    pub const SLIDE_MARKED: i16 = 614;
62    pub const ROTATE_MARKED: i16 = 615;
63    pub const SLIDE: i16 = 616;
64    pub const ROTATE: i16 = 617;
65    pub const DAMAGE: i16 = 618;
66    pub const COUNTER: i16 = 619;
67}
68
69/// Wall flags used by sliding sectors.
70pub const WALL_MOVE_FORWARD: u16 = 0x4000;
71pub const WALL_MOVE_REVERSE: u16 = 0x8000;
72
73/// Placement of a moving sector relative to its map position: translation plus a
74/// rotation by `ang` radians around (cx, cy).
75#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, Default, PartialEq)]
76pub struct Xform {
77    pub dx: f64,
78    pub dy: f64,
79    pub ang: f64,
80    pub cx: f64,
81    pub cy: f64,
82}
83
84/// Change of a moving sector's transform during one update.
85#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy)]
86pub struct Carry {
87    pub sector: usize,
88    pub old: Xform,
89    pub new: Xform,
90}
91
92impl Carry {
93    pub fn dang(&self) -> f64 {
94        self.new.ang - self.old.ang
95    }
96    pub fn is_identity(&self) -> bool {
97        (self.new.dx - self.old.dx).abs() < 1e-9
98            && (self.new.dy - self.old.dy).abs() < 1e-9
99            && self.dang().abs() < 1e-12
100    }
101    /// Maps a point that moved with the sector from the old placement to the new one.
102    pub fn apply(&self, x: f64, y: f64) -> (f64, f64) {
103        let (x, y) = (x - self.old.dx, y - self.old.dy);
104        let a = self.dang();
105        let (c, s) = (a.cos(), a.sin());
106        let (rx, ry) = (x - self.new.cx, y - self.new.cy);
107        let (x, y) = (self.new.cx + rx * c - ry * s, self.new.cy + rx * s + ry * c);
108        (x + self.new.dx, y + self.new.dy)
109    }
110}
111
112#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
113pub enum Obj {
114    Sector(usize),
115    Wall(usize),
116    Sprite(usize),
117}
118
119#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy)]
120struct Event {
121    time: u64,
122    obj: Obj,
123    cmd: u8,
124}
125
126#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy)]
127struct Busy {
128    obj: Obj,
129    /// Target busy value 0 or 65536.
130    target: u32,
131    /// Busy units per tick.
132    rate: f64,
133    pos: f64,
134}
135
136/// Notifications for the game layer (sounds, messages, level flow).
137#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
138pub enum Notice {
139    LevelExit { secret: bool },
140    SecretFound,
141    TotalSecrets(i32),
142    Text(u32),
143    SectorStart(usize, bool),
144    SectorStop(usize, bool),
145    SwitchToggled(Obj, u8),
146    Teleport { sector: usize },
147}
148
149#[derive(serde::Serialize, serde::Deserialize)]
150pub struct Triggers {
151    pub tick: u64,
152    events: Vec<Event>,
153    busy: Vec<Busy>,
154    #[serde(skip)]
155    rx_index: HashMap<u32, Vec<Obj>>,
156    /// Vertex groups: walls sharing a position (for moving shared vertices together).
157    #[serde(skip)]
158    vertex_group: Vec<Vec<usize>>,
159    /// Slide sectors whose walls stay put: moving them would fold a sector over itself
160    /// (E1M1's coffin), which the original never shows.
161    #[serde(skip)]
162    frozen_slides: std::collections::HashSet<usize>,
163    pub notices: Vec<Notice>,
164    /// Sector movements since the game last consumed them (to carry the player).
165    pub carries: Vec<Carry>,
166    xforms: HashMap<usize, Xform>,
167    init_state: HashMap<usize, f64>,
168    pub secrets_total: i32,
169    pub secrets_found: i32,
170}
171
172/// Interpolation curves for busy motion (Blood "waves").
173pub fn wave(busy: f64, kind: u8) -> f64 {
174    let b = busy.clamp(0.0, 1.0);
175    match kind {
176        0 => b,
177        1 => {
178            if b >= 0.5 {
179                1.0
180            } else {
181                0.0
182            }
183        }
184        2 => (1.0 - (b * std::f64::consts::PI).cos()) * 0.5,
185        3 => b * b,
186        4 => 1.0 - (1.0 - b) * (1.0 - b),
187        _ => b,
188    }
189}
190
191/// Busy/wait times are stored in twentieths of a second; the game clock runs at 120 Hz.
192///
193/// Measured in DOSBox at the E1M1 start: a wait of 6 then a busy time of 40 make the coffin
194/// floor start rising ~0.2-0.3 s after the first input and finish ~2.1 s later, and a wait of
195/// 20 plays the player's voice line at ~1.0 s (tenths would give 0.6, 4.0 and 2.0 s).
196pub fn time_units_to_ticks(t: u32) -> u64 {
197    (t as u64 * 6).max(1)
198}
199
200impl Triggers {
201    pub fn new(world: &World) -> Self {
202        let mut t = Triggers {
203            tick: 0,
204            events: Vec::new(),
205            busy: Vec::new(),
206            rx_index: HashMap::new(),
207            vertex_group: Vec::new(),
208            frozen_slides: Default::default(),
209            notices: Vec::new(),
210            carries: Vec::new(),
211            xforms: HashMap::new(),
212            init_state: HashMap::new(),
213            secrets_total: 0,
214            secrets_found: 0,
215        };
216        t.rebuild(world);
217        t
218    }
219
220    /// Recomputes lookup tables that are not saved (receive index, shared vertices).
221    pub fn rebuild(&mut self, world: &World) {
222        self.reindex(world);
223        let mut by_pos: HashMap<(i32, i32), Vec<usize>> = HashMap::new();
224        for (i, &(x, y)) in world.base_wall_xy.iter().enumerate() {
225            by_pos.entry((x, y)).or_default().push(i);
226        }
227        self.vertex_group = world.base_wall_xy.iter().map(|p| by_pos[p].clone()).collect();
228        self.frozen_slides = self.find_folding_slides(world);
229    }
230
231    /// Slide sectors left in place because moving them would fold geometry.
232    pub fn frozen_slides(&self) -> Vec<usize> {
233        let mut v: Vec<usize> = self.frozen_slides.iter().copied().collect();
234        v.sort_unstable();
235        v
236    }
237
238    /// Slide sectors whose full travel would make some sector polygon self-intersecting.
239    fn find_folding_slides(&self, world: &World) -> std::collections::HashSet<usize> {
240        let mut wall_sector = vec![usize::MAX; world.walls.len()];
241        for s in 0..world.sectors.len() {
242            for w in world.sector_walls(s) {
243                if w < wall_sector.len() {
244                    wall_sector[w] = s;
245                }
246            }
247        }
248        let mut out = std::collections::HashSet::new();
249        for s in 0..world.sectors.len() {
250            // Only marked slides move single vertices; whole-sector slides (trains) are fine.
251            let t = world.sectors[s].lotag;
252            if t != sector_type::SLIDE_MARKED {
253                continue;
254            }
255            let Some(x) = world.xsector(s) else { continue };
256            let (m0, m1) = (x.marker0 as usize, x.marker1 as usize);
257            if m0 >= world.sprites.len() || m1 >= world.sprites.len() {
258                continue;
259            }
260            // Split doors (forward + reverse panels) always move.
261            if world
262                .sector_walls(s)
263                .any(|w| world.walls[w].cstat & WALL_MOVE_REVERSE != 0)
264            {
265                continue;
266            }
267            let (ax, ay, _) = world.base_sprite_xy[m0];
268            let (bx, by, _) = world.base_sprite_xy[m1];
269            let init = x.state as i32;
270            for f in [1 - init, -init] {
271                if f == 0 {
272                    continue;
273                }
274                let (dx, dy) = ((bx - ax) * f, (by - ay) * f);
275                let mut pos: Vec<(i32, i32)> = world.base_wall_xy.clone();
276                let mut touched = std::collections::BTreeSet::new();
277                for (w, sign) in Self::moved_walls(world, s, t == sector_type::SLIDE_MARKED) {
278                    let (px, py) = world.base_wall_xy[w];
279                    for &g in &self.vertex_group[w] {
280                        pos[g] = (px + dx * sign, py + dy * sign);
281                        touched.insert(wall_sector[g]);
282                    }
283                }
284                // Folding a neighbouring sector (not the slide itself) means the walls
285                // would be dragged out into solid space.
286                let beside: std::collections::BTreeSet<usize> = Self::moved_walls(world, s, true)
287                    .iter()
288                    .filter_map(|&(w, _)| usize::try_from(world.walls[w].nextsector).ok())
289                    .collect();
290                if touched
291                    .iter()
292                    .any(|&ts| beside.contains(&ts) && sector_folds(world, ts, &pos))
293                {
294                    out.insert(s);
295                }
296            }
297        }
298        out
299    }
300
301    pub fn reindex(&mut self, world: &World) {
302        self.rx_index.clear();
303        for s in 0..world.sectors.len() {
304            if let Some(x) = world.xsector(s) {
305                if x.rx_id > 0 {
306                    self.rx_index.entry(x.rx_id).or_default().push(Obj::Sector(s));
307                }
308            }
309        }
310        for w in 0..world.walls.len() {
311            if let Some(x) = world.xwall(w) {
312                if x.rx_id > 0 {
313                    self.rx_index.entry(x.rx_id).or_default().push(Obj::Wall(w));
314                }
315            }
316        }
317        for s in 0..world.sprites.len() {
318            if world.sprites[s].statnum == crate::world::stat::FREE {
319                continue;
320            }
321            if let Some(x) = world.xsprite(s) {
322                if x.rx_id > 0 {
323                    self.rx_index.entry(x.rx_id).or_default().push(Obj::Sprite(s));
324                }
325            }
326        }
327    }
328
329    /// Initial pass after loading: apply start states and count secrets.
330    pub fn init_level(&mut self, world: &mut World) {
331        for s in 0..world.sectors.len() {
332            if let Some(x) = world.xsector(s).cloned() {
333                let busy = if x.state != 0 { 65536 } else { 0 };
334                if let Some(xm) = world.xsector_mut(s) {
335                    xm.busy = busy;
336                }
337                self.apply_sector(world, s, busy as f64 / 65536.0);
338            }
339        }
340    }
341
342    pub fn post(&mut self, obj: Obj, cmd: u8, delay_ticks: u64) {
343        self.events.push(Event {
344            time: self.tick + delay_ticks,
345            obj,
346            cmd,
347        });
348    }
349
350    /// Broadcast `cmd` on channel `ch`.
351    pub fn send(&mut self, world: &mut World, ch: u32, cmd: u8) {
352        if ch == 0 {
353            return;
354        }
355        match ch {
356            chan::SET_TOTAL_SECRETS => {
357                self.secrets_total += 1;
358                self.notices.push(Notice::TotalSecrets(self.secrets_total));
359                return;
360            }
361            chan::SECRET_FOUND => {
362                self.secrets_found += 1;
363                self.notices.push(Notice::SecretFound);
364                return;
365            }
366            chan::TEXT_OVER => {
367                self.notices.push(Notice::Text(cmd as u32));
368                return;
369            }
370            chan::LEVEL_EXIT_NORMAL => {
371                self.notices.push(Notice::LevelExit { secret: false });
372                return;
373            }
374            chan::LEVEL_EXIT_SECRET => {
375                self.notices.push(Notice::LevelExit { secret: true });
376                return;
377            }
378            _ => {}
379        }
380        if let Some(list) = self.rx_index.get(&ch).cloned() {
381            for o in list {
382                self.trigger(world, o, cmd);
383            }
384        }
385    }
386
387    fn state_of(world: &World, o: Obj) -> Option<(u8, bool)> {
388        match o {
389            Obj::Sector(s) => world.xsector(s).map(|x| (x.state, x.locked)),
390            Obj::Wall(w) => world.xwall(w).map(|x| (x.state, x.locked)),
391            Obj::Sprite(s) => world.xsprite(s).map(|x| (x.state, x.locked)),
392        }
393    }
394
395    fn set_locked(world: &mut World, o: Obj, v: Option<bool>) {
396        let f = |l: &mut bool| *l = v.unwrap_or(!*l);
397        match o {
398            Obj::Sector(s) => {
399                if let Some(x) = world.xsector_mut(s) {
400                    f(&mut x.locked)
401                }
402            }
403            Obj::Wall(w) => {
404                if let Some(x) = world.xwall_mut(w) {
405                    f(&mut x.locked)
406                }
407            }
408            Obj::Sprite(s) => {
409                if let Some(x) = world.xsprite_mut(s) {
410                    f(&mut x.locked)
411                }
412            }
413        }
414    }
415
416    /// Delivers a command to one object.
417    pub fn trigger(&mut self, world: &mut World, o: Obj, c: u8) {
418        let Some((state, locked)) = Self::state_of(world, o) else {
419            return;
420        };
421        match c {
422            cmd::LOCK => return Self::set_locked(world, o, Some(true)),
423            cmd::UNLOCK => return Self::set_locked(world, o, Some(false)),
424            cmd::TOGGLE_LOCK => return Self::set_locked(world, o, None),
425            _ => {}
426        }
427        if locked {
428            return;
429        }
430        if let Obj::Sector(s) = o {
431            let t = world.sectors[s].lotag;
432            if t == sector_type::TELEPORT || t == sector_type::WARP {
433                self.notices.push(Notice::Teleport { sector: s });
434                return;
435            }
436            if t == sector_type::COUNTER {
437                return;
438            }
439        }
440        // Busy objects interrupted mid-motion reverse direction.
441        let busy_now = self.busy.iter().position(|b| b.obj == o);
442        let target = match c {
443            cmd::OFF => 0,
444            cmd::ON => 1,
445            cmd::STOP_OFF | cmd::STOP_ON | cmd::STOP_NEXT => {
446                if let Some(i) = busy_now {
447                    self.busy.remove(i);
448                }
449                return;
450            }
451            cmd::NOT_STATE => {
452                if state == 0 {
453                    1
454                } else {
455                    0
456                }
457            }
458            cmd::CALLBACK | cmd::REPEAT | cmd::LINK | cmd::COUNTER_SECTOR => return,
459            _ => {
460                // Toggle and all "event" commands toggle the object; a busy object reverses.
461                if let Some(i) = busy_now {
462                    if self.busy[i].target == 65536 {
463                        0
464                    } else {
465                        1
466                    }
467                } else if state == 0 {
468                    1
469                } else {
470                    0
471                }
472            }
473        };
474        self.set_state(world, o, target);
475    }
476
477    fn busy_ticks(world: &World, o: Obj, target: u8) -> u32 {
478        match o {
479            Obj::Sector(s) => world
480                .xsector(s)
481                .map(|x| {
482                    if target == 1 {
483                        x.busy_time_a
484                    } else {
485                        x.busy_time_b.max(if x.busy_time_b == 0 { x.busy_time_a } else { 0 })
486                    }
487                })
488                .unwrap_or(0),
489            Obj::Wall(w) => world.xwall(w).map(|x| x.busy_time).unwrap_or(0),
490            Obj::Sprite(s) => world.xsprite(s).map(|x| x.busy_time).unwrap_or(0),
491        }
492    }
493
494    fn current_busy(world: &World, o: Obj) -> u32 {
495        match o {
496            Obj::Sector(s) => world.xsector(s).map(|x| x.busy).unwrap_or(0),
497            Obj::Wall(w) => world.xwall(w).map(|x| x.busy).unwrap_or(0),
498            Obj::Sprite(s) => world.xsprite(s).map(|x| x.busy).unwrap_or(0),
499        }
500    }
501
502    fn set_busy(world: &mut World, o: Obj, b: u32) {
503        match o {
504            Obj::Sector(s) => {
505                if let Some(x) = world.xsector_mut(s) {
506                    x.busy = b
507                }
508            }
509            Obj::Wall(w) => {
510                if let Some(x) = world.xwall_mut(w) {
511                    x.busy = b
512                }
513            }
514            Obj::Sprite(s) => {
515                if let Some(x) = world.xsprite_mut(s) {
516                    x.busy = b
517                }
518            }
519        }
520    }
521
522    fn set_state(&mut self, world: &mut World, o: Obj, target: u8) {
523        let (state, _) = Self::state_of(world, o).unwrap_or((0, false));
524        let busy_target = target as u32 * 65536;
525        let cur = Self::current_busy(world, o);
526        let already = self.busy.iter().position(|b| b.obj == o);
527        if already.is_none() && state == target && cur == busy_target {
528            return;
529        }
530        let bt = Self::busy_ticks(world, o, target);
531        let animated = matches!(o, Obj::Sector(_)) && bt > 0;
532        if let Some(i) = already {
533            self.busy.remove(i);
534        }
535        if animated {
536            if let Obj::Sector(s) = o {
537                self.notices.push(Notice::SectorStart(s, target == 1));
538            }
539            let ticks = time_units_to_ticks(bt) as f64;
540            self.busy.push(Busy {
541                obj: o,
542                target: busy_target,
543                rate: 65536.0 / ticks,
544                pos: cur as f64,
545            });
546        } else {
547            Self::set_busy(world, o, busy_target);
548            if let Obj::Sector(s) = o {
549                self.apply_sector(world, s, target as f64);
550            }
551            self.reach_state(world, o, target);
552        }
553    }
554
555    fn reach_state(&mut self, world: &mut World, o: Obj, st: u8) {
556        let (tx, command, on, off, wait, rest, once) = match o {
557            Obj::Sector(s) => {
558                let Some(x) = world.xsector_mut(s) else { return };
559                x.state = st;
560                let wait = if st == 1 { x.wait_time_a } else { x.wait_time_b };
561                // Sectors return to the opposite state after their wait time.
562                (
563                    x.tx_id,
564                    x.command,
565                    x.trigger_on,
566                    x.trigger_off,
567                    wait,
568                    1 - st,
569                    x.trigger_once,
570                )
571            }
572            Obj::Wall(w) => {
573                let Some(x) = world.xwall_mut(w) else { return };
574                x.state = st;
575                (
576                    x.tx_id,
577                    x.command,
578                    x.trigger_on,
579                    x.trigger_off,
580                    x.wait_time,
581                    x.rest_state as u8,
582                    x.trigger_once,
583                )
584            }
585            Obj::Sprite(s) => {
586                let Some(x) = world.xsprite_mut(s) else { return };
587                x.state = st;
588                (
589                    x.tx_id,
590                    x.command,
591                    x.trigger_on,
592                    x.trigger_off,
593                    x.wait_time,
594                    x.rest_state as u8,
595                    x.trigger_once,
596                )
597            }
598        };
599        if let Obj::Sector(s) = o {
600            self.notices.push(Notice::SectorStop(s, st == 1));
601        } else {
602            self.notices.push(Notice::SwitchToggled(o, st));
603        }
604        if (st == 1 && on) || (st == 0 && off) {
605            self.send(world, tx, command);
606            if once {
607                Self::set_locked(world, o, Some(true));
608            }
609        }
610        if wait > 0 && st != rest {
611            let c = if rest == 1 { cmd::ON } else { cmd::OFF };
612            self.post(o, c, time_units_to_ticks(wait));
613        }
614    }
615
616    /// Advances one 120 Hz tick.
617    pub fn update(&mut self, world: &mut World) {
618        self.tick += 1;
619        // Due events.
620        let now = self.tick;
621        let mut due: Vec<Event> = Vec::new();
622        self.events.retain(|e| {
623            if e.time <= now {
624                due.push(*e);
625                false
626            } else {
627                true
628            }
629        });
630        due.sort_by_key(|e| e.time);
631        for e in due {
632            self.trigger(world, e.obj, e.cmd);
633        }
634        // Busy motion.
635        let mut finished = Vec::new();
636        for b in self.busy.iter_mut() {
637            if (b.target as f64) > b.pos {
638                b.pos = (b.pos + b.rate).min(b.target as f64);
639            } else {
640                b.pos = (b.pos - b.rate).max(b.target as f64);
641            }
642            if (b.pos - b.target as f64).abs() < 0.5 {
643                finished.push(*b);
644            }
645        }
646        let snapshot: Vec<Busy> = self.busy.clone();
647        for b in &snapshot {
648            Self::set_busy(world, b.obj, b.pos as u32);
649            if let Obj::Sector(s) = b.obj {
650                let w = world
651                    .xsector(s)
652                    .map(|x| if b.target > 0 { x.busy_wave_a } else { x.busy_wave_b })
653                    .unwrap_or(0);
654                self.apply_sector(world, s, wave(b.pos / 65536.0, w));
655            }
656        }
657        for b in finished {
658            self.busy.retain(|x| x.obj != b.obj);
659            self.reach_state(world, b.obj, (b.target / 65536) as u8);
660        }
661    }
662
663    pub fn is_busy(&self, o: Obj) -> bool {
664        self.busy.iter().any(|b| b.obj == o)
665    }
666
667    /// Positions a moving sector for interpolation factor `f` (0 = off, 1 = on).
668    pub fn apply_sector(&mut self, world: &mut World, s: usize, f: f64) {
669        let t = world.sectors[s].lotag;
670        let Some(x) = world.xsector(s).cloned() else { return };
671        match t {
672            sector_type::Z_MOTION | sector_type::Z_MOTION_SPRITE => Self::apply_z(world, s, &x, f),
673            sector_type::SLIDE | sector_type::SLIDE_MARKED => {
674                Self::apply_z(world, s, &x, f);
675                let m0 = x.marker0 as usize;
676                let m1 = x.marker1 as usize;
677                if m0 >= world.sprites.len() || m1 >= world.sprites.len() {
678                    return;
679                }
680                let (ax, ay, _) = world.base_sprite_xy[m0];
681                let (bx, by, _) = world.base_sprite_xy[m1];
682                // Map geometry is stored at the sector's initial state.
683                let f = f - self.initial_state(world, s);
684                let dx = ((bx - ax) as f64 * f).round() as i32;
685                let dy = ((by - ay) as f64 * f).round() as i32;
686                self.translate_sector(world, s, dx, dy, t == sector_type::SLIDE_MARKED);
687                if t == sector_type::SLIDE {
688                    self.carry(
689                        world,
690                        s,
691                        Xform {
692                            dx: dx as f64,
693                            dy: dy as f64,
694                            ang: 0.0,
695                            cx: 0.0,
696                            cy: 0.0,
697                        },
698                    );
699                }
700            }
701            sector_type::ROTATE | sector_type::ROTATE_MARKED | sector_type::ROTATE_STEP => {
702                let m0 = x.marker0 as usize;
703                if m0 >= world.sprites.len() {
704                    return;
705                }
706                let (cx, cy, _) = world.base_sprite_xy[m0];
707                let ang = world.sprites[m0].ang as f64;
708                let a = ob_engine::geom::ang_to_rad(ang * (f - self.initial_state(world, s)));
709                self.rotate_sector(world, s, cx, cy, a, t == sector_type::ROTATE_MARKED);
710                if t != sector_type::ROTATE_MARKED {
711                    self.carry(
712                        world,
713                        s,
714                        Xform {
715                            dx: 0.0,
716                            dy: 0.0,
717                            ang: a,
718                            cx: cx as f64,
719                            cy: cy as f64,
720                        },
721                    );
722                }
723            }
724            _ => {}
725        }
726    }
727
728    /// Interpolates floor/ceiling between the x-sector's off and on heights, carrying
729    /// sprites that rest on the floor.
730    fn apply_z(world: &mut World, s: usize, x: &ob_engine::map::XSector, f: f64) {
731        if x.on_floor_z == x.off_floor_z && x.on_ceil_z == x.off_ceil_z {
732            return;
733        }
734        let old_floor = world.sectors[s].floor.z;
735        let nf = x.off_floor_z as f64 + (x.on_floor_z - x.off_floor_z) as f64 * f;
736        let nc = x.off_ceil_z as f64 + (x.on_ceil_z - x.off_ceil_z) as f64 * f;
737        world.sectors[s].floor.z = nf.round() as i32;
738        world.sectors[s].ceiling.z = nc.round() as i32;
739        // Carry sprites resting on the floor.
740        let dz = world.sectors[s].floor.z - old_floor;
741        if dz != 0 {
742            for sp in world.sprites.iter_mut() {
743                if sp.sectnum as usize == s && sp.statnum != crate::world::stat::FREE && (sp.z - old_floor).abs() <= 256
744                {
745                    sp.z += dz;
746                }
747            }
748        }
749    }
750
751    fn moved_walls(world: &World, s: usize, marked: bool) -> Vec<(usize, i32)> {
752        let mut out = Vec::new();
753        let range = world.sector_walls(s);
754        let any_flag = range
755            .clone()
756            .any(|w| world.walls[w].cstat & (WALL_MOVE_FORWARD | WALL_MOVE_REVERSE) != 0);
757        for w in range {
758            let cs = world.walls[w].cstat;
759            if cs & WALL_MOVE_FORWARD != 0 {
760                out.push((w, 1));
761            } else if cs & WALL_MOVE_REVERSE != 0 {
762                out.push((w, -1));
763            } else if !marked && !any_flag {
764                out.push((w, 1));
765            }
766        }
767        out
768    }
769
770    fn initial_state(&mut self, world: &World, s: usize) -> f64 {
771        *self
772            .init_state
773            .entry(s)
774            .or_insert_with(|| world.xsector(s).map_or(0.0, |x| x.state as f64))
775    }
776
777    /// Moves sprites standing in a moving sector by the change from its previous transform,
778    /// and records the change so the game can carry the player too.
779    fn carry(&mut self, world: &mut World, s: usize, new: Xform) {
780        let old = self.xforms.insert(s, new).unwrap_or(Xform {
781            cx: new.cx,
782            cy: new.cy,
783            ..Default::default()
784        });
785        let d = Carry { sector: s, old, new };
786        if d.is_identity() {
787            return;
788        }
789        for sp in world.sprites.iter_mut() {
790            if sp.sectnum as usize != s
791                || sp.statnum == crate::world::stat::FREE
792                || sp.statnum == crate::world::stat::MARKER
793            {
794                continue;
795            }
796            let (nx, ny) = d.apply(sp.x as f64, sp.y as f64);
797            sp.x = nx.round() as i32;
798            sp.y = ny.round() as i32;
799            sp.ang =
800                ((sp.ang as f64 + d.dang() * 2048.0 / std::f64::consts::TAU).round() as i32).rem_euclid(2048) as i16;
801        }
802        self.carries.push(d);
803    }
804
805    fn translate_sector(&mut self, world: &mut World, s: usize, dx: i32, dy: i32, marked: bool) {
806        if self.frozen_slides.contains(&s) {
807            return;
808        }
809        for (w, sign) in Self::moved_walls(world, s, marked) {
810            let (bx, by) = world.base_wall_xy[w];
811            for &g in &self.vertex_group[w] {
812                world.walls[g].x = bx + dx * sign;
813                world.walls[g].y = by + dy * sign;
814            }
815        }
816    }
817
818    fn rotate_sector(&mut self, world: &mut World, s: usize, cx: i32, cy: i32, a: f64, marked: bool) {
819        let (c, sn) = (a.cos(), a.sin());
820        for (w, sign) in Self::moved_walls(world, s, marked) {
821            let (bx, by) = world.base_wall_xy[w];
822            let (rx, ry) = ((bx - cx) as f64, (by - cy) as f64);
823            let sn = sn * sign as f64;
824            let nx = cx as f64 + rx * c - ry * sn;
825            let ny = cy as f64 + rx * sn + ry * c;
826            for &g in &self.vertex_group[w] {
827                world.walls[g].x = nx.round() as i32;
828                world.walls[g].y = ny.round() as i32;
829            }
830        }
831    }
832
833    /// Player pressed "use" on a wall (and possibly the sector behind it).
834    pub fn push_wall(&mut self, world: &mut World, w: usize) -> bool {
835        let mut done = false;
836        if let Some(x) = world.xwall(w).cloned() {
837            if x.trigger_push || x.tx_id > 0 || world.walls[w].lotag >= 20 {
838                self.trigger(world, Obj::Wall(w), cmd::WALL_PUSH);
839                done = true;
840            }
841        }
842        let ns = world.walls[w].nextsector;
843        if ns >= 0 {
844            if let Some(x) = world.xsector(ns as usize).cloned() {
845                if x.push || x.wallpush {
846                    self.trigger(world, Obj::Sector(ns as usize), cmd::SECTOR_PUSH);
847                    done = true;
848                }
849            }
850        }
851        done
852    }
853
854    pub fn push_sprite(&mut self, world: &mut World, s: usize) -> bool {
855        if let Some(x) = world.xsprite(s).cloned() {
856            if x.push || x.tx_id > 0 {
857                self.trigger(world, Obj::Sprite(s), cmd::SPRITE_PUSH);
858                return true;
859            }
860        }
861        false
862    }
863
864    pub fn push_sector(&mut self, world: &mut World, s: usize) -> bool {
865        if let Some(x) = world.xsector(s).cloned() {
866            if x.push {
867                self.trigger(world, Obj::Sector(s), cmd::SECTOR_PUSH);
868                return true;
869            }
870        }
871        false
872    }
873
874    pub fn enter_sector(&mut self, world: &mut World, s: usize) {
875        if let Some(x) = world.xsector(s).cloned() {
876            if x.enter {
877                self.trigger(world, Obj::Sector(s), cmd::SECTOR_ENTER);
878            }
879            let t = world.sectors[s].lotag;
880            if t == sector_type::TELEPORT || t == sector_type::WARP {
881                self.notices.push(Notice::Teleport { sector: s });
882            }
883        }
884    }
885
886    pub fn exit_sector(&mut self, world: &mut World, s: usize) {
887        if let Some(x) = world.xsector(s).cloned() {
888            if x.exit {
889                self.trigger(world, Obj::Sector(s), cmd::SECTOR_EXIT);
890            }
891        }
892    }
893}
894
895/// True when two non-adjacent edges of sector `s` cross, using wall positions `pos`.
896fn sector_folds(world: &World, s: usize, pos: &[(i32, i32)]) -> bool {
897    let edges: Vec<((f64, f64), (f64, f64))> = world
898        .sector_walls(s)
899        .map(|w| {
900            let a = pos[w];
901            let b = pos[world.walls[w].point2 as usize];
902            ((a.0 as f64, a.1 as f64), (b.0 as f64, b.1 as f64))
903        })
904        .collect();
905    let cross = |o: (f64, f64), a: (f64, f64), b: (f64, f64)| (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0);
906    for i in 0..edges.len() {
907        for j in i + 1..edges.len() {
908            let (p1, p2) = edges[i];
909            let (q1, q2) = edges[j];
910            if p1 == q1 || p1 == q2 || p2 == q1 || p2 == q2 {
911                continue;
912            }
913            let d1 = cross(q1, q2, p1);
914            let d2 = cross(q1, q2, p2);
915            let d3 = cross(p1, p2, q1);
916            let d4 = cross(p1, p2, q2);
917            if d1 * d2 < 0.0 && d3 * d4 < 0.0 {
918                return true;
919            }
920        }
921    }
922    false
923}
924
925#[cfg(test)]
926mod tests {
927    use super::*;
928    use ob_engine::map::{Map, Sector, Wall, XSector};
929
930    fn door_world() -> World {
931        let mut m = Map::default();
932        let pts = [(0, 0), (512, 0), (512, 512), (0, 512)];
933        for (i, &(x, y)) in pts.iter().enumerate() {
934            m.walls.push(Wall {
935                x,
936                y,
937                point2: ((i + 1) % 4) as i16,
938                nextwall: -1,
939                nextsector: -1,
940                ..Default::default()
941            });
942        }
943        let mut s = Sector {
944            wallptr: 0,
945            wallnum: 4,
946            lotag: sector_type::Z_MOTION,
947            extra: 1,
948            ..Default::default()
949        };
950        s.ceiling.z = 0;
951        s.floor.z = 0;
952        m.sectors.push(s);
953        m.xsectors.push(XSector::default());
954        m.xsectors.push(XSector {
955            rx_id: 100,
956            busy_time_a: 10,
957            wait_time_a: 20,
958            off_ceil_z: 0,
959            on_ceil_z: -8192,
960            push: true,
961            ..Default::default()
962        });
963        m.xwalls.push(Default::default());
964        m.xsprites.push(Default::default());
965        World::from_map("TEST", m)
966    }
967
968    #[test]
969    fn door_opens_waits_and_closes() {
970        let mut w = door_world();
971        let mut t = Triggers::new(&w);
972        t.init_level(&mut w);
973        t.send(&mut w, 100, cmd::TOGGLE);
974        // busy 10 = half a second (60 ticks)
975        for _ in 0..30 {
976            t.update(&mut w);
977        }
978        assert!(
979            w.sectors[0].ceiling.z < -1000 && w.sectors[0].ceiling.z > -8192,
980            "half open"
981        );
982        for _ in 0..35 {
983            t.update(&mut w);
984        }
985        assert_eq!(w.sectors[0].ceiling.z, -8192, "fully open");
986        assert_eq!(w.xsector(0).unwrap().state, 1);
987        // waits 1 s (wait 20, 120 ticks) then closes over half a second
988        for _ in 0..200 {
989            t.update(&mut w);
990        }
991        assert_eq!(w.sectors[0].ceiling.z, 0, "closed again");
992        assert_eq!(w.xsector(0).unwrap().state, 0);
993    }
994
995    #[test]
996    fn toggling_busy_door_reverses() {
997        let mut w = door_world();
998        let mut t = Triggers::new(&w);
999        t.push_sector(&mut w, 0);
1000        for _ in 0..30 {
1001            t.update(&mut w);
1002        }
1003        let mid = w.sectors[0].ceiling.z;
1004        t.push_sector(&mut w, 0);
1005        t.update(&mut w);
1006        assert!(w.sectors[0].ceiling.z > mid, "moving back down");
1007    }
1008
1009    #[test]
1010    fn carry_translates_and_rotates() {
1011        let c = Carry {
1012            sector: 0,
1013            old: Xform::default(),
1014            new: Xform {
1015                dx: 10.0,
1016                dy: 0.0,
1017                ..Default::default()
1018            },
1019        };
1020        assert_eq!(c.apply(5.0, 5.0), (15.0, 5.0));
1021        let r = Carry {
1022            sector: 0,
1023            old: Xform::default(),
1024            new: Xform {
1025                ang: std::f64::consts::FRAC_PI_2,
1026                ..Default::default()
1027            },
1028        };
1029        let (x, y) = r.apply(10.0, 0.0);
1030        assert!((x - 0.0).abs() < 1e-9 && (y - 10.0).abs() < 1e-9);
1031    }
1032
1033    #[test]
1034    fn waves_are_bounded() {
1035        for k in 0..5 {
1036            assert_eq!(wave(0.0, k), 0.0);
1037            assert!((wave(1.0, k) - 1.0).abs() < 1e-9);
1038        }
1039    }
1040}