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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
//! Core reusable gameplay logic — state machines, combat, AI, weapons.
//!
//! Free functions taking `&mut World` + `&MapData`. Any [`GameRules`](crate::rules::GameRules)
//! implementation can use these as building blocks without reimplementing
//! collision, hitscan, projectile spawning, AI pathfinding, etc.

// Per-entity-per-tick hot path. Map indices come from the loader (which
// validates during LOAD) and entity-local state. See the global policy
// in src/render/mod.rs.
#![allow(clippy::indexing_slicing)]

use core::ops::ControlFlow;

use crate::game_data::{ActionId, EntityType, MobjFlag, StateNum};
use crate::map::MapData;
use crate::math::*;
use crate::rules::PlayerAction;
use crate::specials;
// Prefer the `finesine()` / `finecosine()` helpers over raw
// `FINESINE[idx]` — they mask the index to FINEMASK, which lets the
// compiler prove the access is in-bounds and matches our indexing policy.
use crate::types::AmmoType;
use crate::world::{Entity, EntityId, World};

// --- State Machine ---

/// Advance the state machine by one tick. Returns the action to dispatch
/// only when entering a new state (matching Doom's P_SetMobjState behavior).
pub fn advance_state(entity: &mut Entity) -> ActionId {
    if entity.tics == -1 {
        return ActionId::NONE; // infinite duration
    }
    entity.tics -= 1;
    if entity.tics > 0 {
        return ActionId::NONE;
    }
    let Some(cur) = entity.state.get() else { return ActionId::NONE };
    set_entity_state(entity, cur.next_state)
}

/// Transition entity to a new state. Returns the new state's action.
pub fn set_entity_state(entity: &mut Entity, state_num: StateNum) -> ActionId {
    let Some(state) = state_num.get() else {
        entity.state = StateNum::NULL;
        return ActionId::NONE;
    };
    entity.state = state_num;
    entity.tics = state.tics;
    entity.sprite = state.sprite;
    entity.frame = state.frame;
    state.action
}

// --- Geometry Helpers ---

/// Rough check: do two line segments cross?
#[inline]
#[allow(clippy::too_many_arguments)]
pub fn segments_cross(
    ax1: Fixed, ay1: Fixed, ax2: Fixed, ay2: Fixed,
    bx1: Fixed, by1: Fixed, bx2: Fixed, by2: Fixed,
) -> bool {
    let d1 = cross2d(bx2 - bx1, by2 - by1, ax1 - bx1, ay1 - by1);
    let d2 = cross2d(bx2 - bx1, by2 - by1, ax2 - bx1, ay2 - by1);
    if (d1 > 0 && d2 > 0) || (d1 < 0 && d2 < 0) { return false; }
    let d3 = cross2d(ax2 - ax1, ay2 - ay1, bx1 - ax1, by1 - ay1);
    let d4 = cross2d(ax2 - ax1, ay2 - ay1, bx2 - ax1, by2 - ay1);
    if (d3 > 0 && d4 > 0) || (d3 < 0 && d4 < 0) { return false; }
    true
}

#[inline]
pub fn cross2d(ax: Fixed, ay: Fixed, bx: Fixed, by: Fixed) -> i64 {
    ax as i64 * by as i64 - ay as i64 * bx as i64
}

/// Check whether an angular difference (wrapping u32) is within ±tolerance.
#[inline]
fn within_angle(angle_diff: u32, tolerance: u32) -> bool {
    angle_diff <= tolerance || angle_diff >= 0u32.wrapping_sub(tolerance)
}

// --- Blockmap Traversal ---

/// Iterate special lines in the blockmap near `(x, y)`, calling `f` for each.
/// `f` receives the line index and line reference. Return `ControlFlow::Break(())`
/// from `f` to stop early.
fn for_each_special_line(
    map: &MapData,
    x: Fixed,
    y: Fixed,
    mut f: impl FnMut(usize, &crate::map::Line) -> ControlFlow<()>,
) {
    let bm = &map.blockmap;
    let bx = (x - bm.origin_x) >> crate::map::MAPBLOCKSHIFT;
    let by = (y - bm.origin_y) >> crate::map::MAPBLOCKSHIFT;

    for dx in -1..=1 {
        for dy in -1..=1 {
            let cx = bx + dx;
            let cy = by + dy;
            if cx < 0 || cy < 0 || cx as usize >= bm.width || cy as usize >= bm.height {
                continue;
            }
            let block_idx = cy as usize * bm.width + cx as usize;
            if block_idx >= bm.offsets.len() { continue; }
            let mut offset = bm.offsets[block_idx] as usize;
            if offset < bm.lists.len() && bm.lists[offset] == 0 {
                offset += 1;
            }
            while offset < bm.lists.len() {
                let val = bm.lists[offset];
                if val == 0xFFFF { break; }
                let line_idx = val as usize;
                if line_idx < map.lines.len() {
                    let line = &map.lines[line_idx];
                    if line.special != 0
                        && f(line_idx, line).is_break()
                    {
                        return;
                    }
                }
                offset += 1;
            }
        }
    }
}

/// Test whether a line segment (x1,y1)→(x2,y2) crosses a map line.
#[inline]
fn line_crosses(map: &MapData, line: &crate::map::Line, x1: Fixed, y1: Fixed, x2: Fixed, y2: Fixed) -> bool {
    let v1 = &map.vertexes[line.v1 as usize];
    let v2 = &map.vertexes[line.v2 as usize];
    segments_cross(x1, y1, x2, y2, v1.x, v1.y, v2.x, v2.y)
}

// --- Player Input ---

pub fn apply_player_input(world: &mut World, map: &MapData, player_id: EntityId, action: &PlayerAction) {
    let Some(entity) = world.get_mut(player_id) else { return };

    // Turn
    entity.angle = entity.angle.wrapping_add((action.angle_turn as u32) << 16);

    // Thrust
    if action.forward_move != 0 {
        let move_amt = (action.forward_move as Fixed) * 2048;
        let fine = (entity.angle >> ANGLETOFINESHIFT) as usize;
        entity.momx += fixed_mul(move_amt, finecosine(fine));
        entity.momy += fixed_mul(move_amt, finesine(fine));
    }
    if action.side_move != 0 {
        let move_amt = (action.side_move as Fixed) * 2048;
        let fine = (entity.angle.wrapping_sub(ANG90) >> ANGLETOFINESHIFT) as usize;
        entity.momx += fixed_mul(move_amt, finecosine(fine & FINEMASK));
        entity.momy += fixed_mul(move_amt, finesine(fine));
    }

    // Snapshot position before physics
    let old_x = entity.x;
    let old_y = entity.y;

    // Apply physics with collision detection
    crate::physics::xy_movement(entity, map);
    crate::physics::z_movement(entity);

    let new_x = entity.x;
    let new_y = entity.y;

    // Check for walk-over line triggers
    check_crossed_lines(world, map, old_x, old_y, new_x, new_y);
}

// --- Line Interaction ---

/// Check for walk-over line triggers between old and new position.
pub fn check_crossed_lines(world: &mut World, map: &MapData, old_x: Fixed, old_y: Fixed, new_x: Fixed, new_y: Fixed) {
    if old_x == new_x && old_y == new_y { return; }

    let mut exit_hit: Option<crate::world::LevelExit> = None;
    for_each_special_line(map, new_x, new_y, |line_idx, line| {
        if line_crosses(map, line, old_x, old_y, new_x, new_y) {
            if specials::is_exit_line(line.special) {
                exit_hit = Some(crate::world::exit_kind(line.special));
            } else {
                specials::cross_special_line(map, &mut world.specials, line_idx);
            }
        }
        ControlFlow::Continue(())
    });
    if let Some(kind) = exit_hit {
        world.level_exit = kind;
    }
}

/// Activate special lines in front of the player (doors, switches, exits).
pub fn use_lines(world: &mut World, map: &MapData, player_id: EntityId) {
    let Some(entity) = world.get(player_id) else { return };
    let fine = (entity.angle >> ANGLETOFINESHIFT) as usize;
    let use_range = 64 * FRACUNIT;
    let px = entity.x;
    let py = entity.y;
    let x2 = px + fixed_mul(use_range, finecosine(fine));
    let y2 = py + fixed_mul(use_range, finesine(fine));

    let mut exit_hit: Option<crate::world::LevelExit> = None;
    for_each_special_line(map, px, py, |line_idx, line| {
        if line_crosses(map, line, px, py, x2, y2) {
            if specials::is_exit_line(line.special) {
                exit_hit = Some(crate::world::exit_kind(line.special));
                return ControlFlow::Break(());
            }
            specials::use_special_line(map, &mut world.specials, line_idx);
        }
        ControlFlow::Continue(())
    });
    if let Some(kind) = exit_hit {
        world.level_exit = kind;
    }
}

// --- Combat ---

/// Fire a hitscan from an entity toward the nearest shootable target in a cone.
/// `puff_type` controls the visual effect spawned on impact (e.g. `MT_PUFF`).
pub fn hitscan_attack(
    world: &mut World,
    map: &MapData,
    shooter_id: EntityId,
    damage: i32,
    angle_spread: i32,
    puff_type: EntityType,
) {
    let Some(shooter) = world.get(shooter_id) else { return };
    let sx = shooter.x;
    let sy = shooter.y;
    let sz = shooter.z;
    let s_height = shooter.height;
    let angle = shooter.angle.wrapping_add(angle_spread as u32);

    let range = 2048 * FRACUNIT;
    let tolerance = ANG90 / 18;
    let mut best_dist = i64::MAX;
    let mut best_id = None;

    for e in world.iter() {
        if e.id == shooter_id || !e.flags.contains(MobjFlag::Shootable) { continue; }
        let dx = e.x - sx;
        let dy = e.y - sy;
        let dist = dx.abs() as i64 + dy.abs() as i64;
        if dist <= 0 || dist > range as i64 { continue; }

        let to_angle = crate::map::point_to_angle(dx, dy);
        if !within_angle(to_angle.wrapping_sub(angle), tolerance) {
            continue;
        }
        if dist < best_dist {
            let eye_z = sz + s_height - (s_height >> 2);
            if crate::physics::check_sight(map, sx, sy, eye_z, e.x, e.y, e.z, e.height) {
                best_dist = dist;
                best_id = Some(e.id);
            }
        }
    }

    if let Some(target_id) = best_id {
        if let Some(target) = world.get(target_id) {
            spawn_puff(world, puff_type, target.x, target.y, target.z + (target.height >> 1));
        }
        apply_damage_to(world, target_id, damage, Some(shooter_id));
    } else {
        // No enemy hit — trace ray to find wall impact point for puff.
        let fine = (angle >> ANGLETOFINESHIFT) as usize & FINEMASK;
        let cos = finecosine(fine);
        let sin = finesine(fine);
        let eye_z = sz + s_height - (s_height >> 2);
        let step = 64 * FRACUNIT;
        let max_steps = (range / step).min(32);
        for i in 1..=max_steps {
            let px = sx + fixed_mul(step * i, cos);
            let py = sy + fixed_mul(step * i, sin);
            if !crate::physics::check_sight(map, sx, sy, eye_z, px, py, eye_z, 0) {
                let half = step / 2;
                let px = sx + fixed_mul(step * i - half, cos);
                let py = sy + fixed_mul(step * i - half, sin);
                spawn_puff(world, puff_type, px, py, eye_z);
                break;
            }
        }
    }
}

/// Apply damage to an entity (shared helper for AI combat).
///
/// Thin-shell port of Doom's P_DamageMobj: armor absorption for
/// players, pain-flinch P_Random gate, death-state transition on hp
/// reaching zero, and the retaliation block that points the victim at
/// the attacker and resets its reaction_time.
///
/// Pass `Some(attacker)` as `source` when the damage has a live
/// origin (hitscan shooter, projectile owner, melee attacker). Pass
/// `None` for environmental damage (nukage floors, crushers).
pub fn apply_damage_to(
    world: &mut World,
    target_id: EntityId,
    damage: i32,
    source: Option<EntityId>,
) {
    // Snapshot a few fields so we can conditionally draw a random before
    // re-borrowing the target mutably.
    let (shootable, painchance, painstate_null, is_player, seestate_null, spawnstate, cur_state) =
        match world.get(target_id) {
            Some(t) => {
                let info = t.entity_type.info();
                (
                    t.flags.contains(MobjFlag::Shootable),
                    info.map(|i| i.painchance).unwrap_or(0),
                    info.map(|i| i.painstate.is_null()).unwrap_or(true),
                    t.entity_type == crate::world::EntityType(0),
                    info.map(|i| i.seestate.is_null()).unwrap_or(true),
                    info.map(|i| i.spawnstate).unwrap_or(crate::game_data::StateNum::NULL),
                    t.state,
                )
            }
            None => return,
        };
    if !shootable {
        return;
    }

    // Armor absorption for players — matches Doom's P_DamageMobj:
    //   green armor (type 1): absorbs 1/3 of the damage
    //   blue  armor (type 2): absorbs 1/2 of the damage
    // Absorbed damage eats armor points; once armor runs out, the
    // armor_type clears and the remaining damage falls through to hp.
    let damage = if is_player {
        absorb_with_armor(world, target_id, damage)
    } else {
        damage
    };

    // Retaliation: if damage came from someone other than the target
    // itself, the victim reorients at them (resets reaction_time,
    // switches target). Idle monsters (still in spawnstate) wake into
    // their see state. Skipped when target == source (self-damage).
    if let Some(src_id) = source
        && src_id != target_id
    {
        let src_shootable = world
            .get(src_id)
            .is_some_and(|s| s.flags.contains(MobjFlag::Shootable));
        if src_shootable
            && let Some(target) = world.get_mut(target_id)
        {
            target.target = Some(src_id);
            target.reaction_time = 0;
            let should_wake = !seestate_null && cur_state == spawnstate;
            if should_wake
                && let Some(info) = target.entity_type.info()
            {
                set_entity_state(target, info.seestate);
            }
        }
    }

    // Doom's pain check: consumed unconditionally when damage is dealt.
    let pain_roll = world.p_random();

    let Some(target) = world.get_mut(target_id) else { return };
    target.health -= damage;
    if target.health <= 0 {
        if let Some(info) = target.entity_type.info() {
            target.flags.remove(MobjFlag::Shootable | MobjFlag::Solid);
            set_entity_state(target, info.deathstate);
        }
    } else if !painstate_null
        && pain_roll < painchance
        && let Some(info) = target.entity_type.info()
    {
        set_entity_state(target, info.painstate);
    }
}

/// Apply the player's armor absorption rule to incoming damage. Returns
/// the damage that actually reaches the player's hp after armor eats
/// its share. Drops the armor type to None if armor is fully consumed.
/// Mirrors P_DamageMobj's armor block in Doom's p_inter.c.
fn absorb_with_armor(world: &mut World, pid: EntityId, damage: i32) -> i32 {
    let Some(ps) = world.player_state_mut(pid) else { return damage };
    let armor_type = ps.armor_type as u8;
    if armor_type == 0 || ps.armor_points <= 0 {
        return damage;
    }
    let saved_want = match armor_type {
        1 => damage / 3, // green
        _ => damage / 2, // blue (and anything else)
    };
    let saved = saved_want.min(ps.armor_points);
    if saved >= ps.armor_points {
        ps.armor_type = crate::types::ArmorType::None;
    }
    ps.armor_points -= saved;
    damage - saved
}

/// Deal radius damage from a point. Damage falls off linearly with chebyshev distance.
pub fn radius_damage(world: &mut World, origin: EntityId, radius: Fixed, max_damage: i32) {
    let Some(entity) = world.get(origin) else { return };
    let ox = entity.x;
    let oy = entity.y;

    let mut targets = alloc::vec::Vec::new();
    for e in world.iter() {
        if e.id == origin { continue; }
        if !e.flags.contains(MobjFlag::Shootable) { continue; }
        let dist = (e.x - ox).abs().max((e.y - oy).abs());
        if dist >= radius { continue; }
        let damage = max_damage - (dist >> FRACBITS).min(max_damage);
        if damage > 0 {
            targets.push((e.id, damage));
        }
    }

    for (tid, damage) in targets {
        apply_damage_to(world, tid, damage, Some(origin));
    }
}

/// Transition a missile to its death state (explosion), stopping all momentum.
pub fn explode_missile(world: &mut World, id: EntityId) {
    let Some(missile) = world.get_mut(id) else { return };
    missile.momx = 0;
    missile.momy = 0;
    missile.momz = 0;
    missile.flags.remove(MobjFlag::Missile); // prevent re-triggering
    if let Some(info) = missile.entity_type.info() {
        if !info.deathstate.is_null() {
            set_entity_state(missile, info.deathstate);
        } else {
            missile.state = StateNum::NULL;
        }
    } else {
        missile.state = StateNum::NULL;
    }
}

/// Check if a missile entity hit something. Returns the hit entity ID.
pub fn check_missile_collision(world: &World, missile_id: EntityId) -> Option<EntityId> {
    let missile = world.get(missile_id)?;
    if !missile.flags.contains(MobjFlag::Missile) { return None; }
    let mx = missile.x;
    let my = missile.y;
    let mradius = missile.radius;
    let source_id = missile.target; // who fired it

    world.iter().find_map(|e| {
        if e.id == missile_id { return None; }
        if Some(e.id) == source_id { return None; }
        if !e.flags.contains(MobjFlag::Shootable) { return None; }
        let dx = (e.x - mx).abs();
        let dy = (e.y - my).abs();
        let touch = mradius + e.radius;
        (dx < touch && dy < touch).then_some(e.id)
    })
}

/// Player melee attack: find nearest enemy in front within range.
pub fn melee_attack(world: &mut World, pid: EntityId, damage: i32, range: Fixed) {
    let Some(shooter) = world.get(pid) else { return };
    let sx = shooter.x;
    let sy = shooter.y;
    let angle = shooter.angle;
    let tolerance = ANG90 / 6; // wider cone for melee

    let mut best_dist = i64::MAX;
    let mut best_id = None;

    for e in world.iter() {
        if e.id == pid || !e.flags.contains(MobjFlag::Shootable) { continue; }
        let dx = e.x - sx;
        let dy = e.y - sy;
        let dist = dx.abs() as i64 + dy.abs() as i64;
        if dist <= 0 || dist > range as i64 { continue; }
        let to_angle = crate::map::point_to_angle(dx, dy);
        if !within_angle(to_angle.wrapping_sub(angle), tolerance) { continue; }
        if dist < best_dist {
            best_dist = dist;
            best_id = Some(e.id);
        }
    }

    if let Some(target_id) = best_id {
        apply_damage_to(world, target_id, damage, Some(pid));
    }
}

// --- Entity Tick Loop ---

/// Run one tick of entity simulation: advance states, apply physics, handle missiles,
/// and remove dead entities. The caller provides a `dispatch` callback to handle
/// game-specific action routing (e.g. mapping `ActionId` to monster attack functions).
///
/// This is the core "entity loop" that any `GameRules::tick` implementation needs.
/// Player input, pickups, and weapon logic are handled separately by the caller.
pub fn tick_entities(
    world: &mut World,
    map: &MapData,
    mut dispatch: impl FnMut(ActionId, &mut World, &MapData, EntityId),
) {
    let ids = world.take_entity_ids();
    for &id in &ids {
        // Advance state machine
        let mut action_id = if let Some(entity) = world.get_mut(id) {
            advance_state(entity)
        } else {
            ActionId::NONE
        };

        // Dispatch actions, following state transitions (actions can
        // change state via set_entity_state, producing cascading actions).
        let mut chain = 0;
        while action_id != ActionId::NONE && chain < 8 {
            let state_before = world.get(id).map(|e| e.state);
            dispatch(action_id, world, map, id);
            let state_after = world.get(id).map(|e| e.state);
            action_id = if state_after != state_before {
                state_after
                    .and_then(|s| s.get())
                    .map_or(ActionId::NONE, |st| st.action)
            } else {
                ActionId::NONE
            };
            chain += 1;
        }

        // Apply physics to non-player entities (players handled in apply_player_input)
        if !world.is_controlled(id) {
            if let Some(entity) = world.get_mut(id) {
                let old_x = entity.x;
                let old_y = entity.y;
                crate::physics::xy_movement(entity, map);
                crate::physics::z_movement(entity);
                let new_x = entity.x;
                let new_y = entity.y;
                check_crossed_lines(world, map, old_x, old_y, new_x, new_y);
            }
            // Check missile wall/floor/ceiling impact (momentum zeroed by physics)
            if let Some(entity) = world.get(id)
                && entity.flags.contains(MobjFlag::Missile)
                && entity.momx == 0 && entity.momy == 0
            {
                explode_missile(world, id);
            }
            // Check missile-entity impact
            if let Some(hit_id) = check_missile_collision(world, id) {
                // Missile carries its shooter in `target`; attribute damage there.
                let (damage, shooter) = world
                    .get(id)
                    .and_then(|e| e.entity_type.info().map(|info| (info.damage, e.target)))
                    .unwrap_or((0, None));
                if damage > 0 {
                    apply_damage_to(world, hit_id, damage, shooter);
                }
                explode_missile(world, id);
            }
        }
    }

    // Remove entities that reached S_NULL (finished death animation or expired)
    for &id in &ids {
        if world.get(id).is_some_and(|e| e.state.is_null()) {
            world.remove(id);
        }
    }
    world.return_id_scratch(ids);
}

// --- Spawning ---

/// Spawn a visual effect (puff, smoke) at a position.
pub fn spawn_puff(world: &mut World, puff_type: EntityType, x: Fixed, y: Fixed, z: Fixed) {
    let Some(info) = puff_type.info() else { return };
    let mut puff = Entity {
        entity_type: puff_type,
        x, y, z,
        flags: info.flags(),
        ..Entity::default()
    };
    if let Some(st) = info.spawnstate.get() {
        puff.sprite = st.sprite;
        puff.frame = st.frame;
        puff.state = info.spawnstate;
        puff.tics = st.tics;
    }
    world.spawn(puff);
}

/// Spawn a projectile from a source entity aimed at a target.
pub fn spawn_projectile(world: &mut World, source_id: EntityId, target_id: EntityId, missile_type: EntityType) {
    let Some(source) = world.get(source_id) else { return };
    let Some(target) = world.get(target_id) else { return };
    let Some(info) = missile_type.info() else { return };

    let sx = source.x;
    let sy = source.y;
    let sz = source.z + (source.height >> 1);
    let dx = target.x - sx;
    let dy = target.y - sy;
    let dz = (target.z + (target.height >> 1)) - sz;
    let dist = ((dx.abs() as i64 + dy.abs() as i64) >> FRACBITS).max(1) as i32;
    let speed = info.speed;
    let angle = crate::map::point_to_angle(dx, dy);

    let mut missile = Entity {
        entity_type: missile_type,
        x: sx, y: sy, z: sz,
        angle,
        radius: info.radius,
        height: info.height,
        health: info.spawnhealth,
        flags: info.flags(),
        target: Some(source_id),
        momx: fixed_div(fixed_mul(dx >> FRACBITS, speed), dist),
        momy: fixed_div(fixed_mul(dy >> FRACBITS, speed), dist),
        momz: fixed_div(fixed_mul(dz >> FRACBITS, speed), dist),
        ..Entity::default()
    };
    if let Some(st) = info.spawnstate.get() {
        missile.sprite = st.sprite;
        missile.frame = st.frame;
        missile.state = info.spawnstate;
        missile.tics = st.tics;
    }
    world.spawn(missile);
}

/// Fire a player projectile aimed at the crosshair direction.
pub fn fire_player_projectile(world: &mut World, pid: EntityId, missile_type: EntityType) {
    let Some(shooter) = world.get(pid) else { return };
    let Some(info) = missile_type.info() else { return };

    let sx = shooter.x;
    let sy = shooter.y;
    let sz = shooter.z + (shooter.height >> 1) + 8 * FRACUNIT;
    let angle = shooter.angle;
    let fine = (angle >> ANGLETOFINESHIFT) as usize & FINEMASK;
    let speed = info.speed;

    let mut missile = Entity {
        entity_type: missile_type,
        x: sx, y: sy, z: sz,
        angle,
        radius: info.radius,
        height: info.height,
        health: info.spawnhealth,
        flags: info.flags(),
        target: Some(pid),
        momx: fixed_mul(speed, finecosine(fine)),
        momy: fixed_mul(speed, finesine(fine)),
        momz: 0,
        ..Entity::default()
    };
    if let Some(st) = info.spawnstate.get() {
        missile.sprite = st.sprite;
        missile.frame = st.frame;
        missile.state = info.spawnstate;
        missile.tics = st.tics;
    }
    world.spawn(missile);
}

// --- AI ---

/// Movement direction speed table (8 cardinal + diagonal directions).
/// Index matches Doom's `dirtype_t` (E / NE / N / NW / W / SW / S / SE).
pub const DIR_SPEED: [(Fixed, Fixed); 8] = [
    (FRACUNIT, 0),
    (47000, 47000),
    (0, FRACUNIT),
    (-47000, 47000),
    (-FRACUNIT, 0),
    (-47000, -47000),
    (0, -FRACUNIT),
    (47000, -47000),
];

// Doom `dirtype_t` values — used by `P_NewChaseDir`.
const DI_EAST: u8 = 0;
const DI_SOUTHEAST: u8 = 7;
const DI_NODIR: u8 = 8;

/// For each direction, the direction 180° away (entries 0..7); index 8
/// maps to NODIR as a sentinel.
const OPPOSITE_DIR: [u8; 9] = [4, 5, 6, 7, 0, 1, 2, 3, 8];

/// `diags[ ((deltay<0) << 1) | (deltax>0) ]` → which diagonal direction
/// to prefer when both an X axis and a Y axis are preferred. Matches
/// Doom's `diags` lookup in `p_enemy.c`.
const DIAG_DIRS: [u8; 4] = [3, 1, 5, 7]; // NW, NE, SW, SE

/// Doom's A_Chase snaps the angle to the nearest 45° and rotates by
/// ±ANG45 per tic toward the current movement direction. Subtle but
/// the right behaviour for sprite facing (attacks still call
/// A_FaceTarget right before firing, so the attack angle is correct).
fn gradual_turn_to_movedir(world: &mut World, id: EntityId) {
    if let Some(e) = world.get_mut(id) {
        if e.move_dir >= 8 {
            return;
        }
        // Snap angle to the nearest 45° (top 3 bits).
        e.angle &= 7u32 << 29;
        let target = (e.move_dir as u32) << 29;
        let delta = e.angle.wrapping_sub(target) as i32;
        if delta > 0 {
            e.angle = e.angle.wrapping_sub(ANG90 / 2);
        } else if delta < 0 {
            e.angle = e.angle.wrapping_add(ANG90 / 2);
        }
    }
}

/// Try to move an entity one step in its current `move_dir`. Returns
/// whether the try_move succeeded. Equivalent to Doom's `P_Move` for
/// the parts we care about (spec-line use by floaters is TODO).
fn monster_move(world: &mut World, map: &MapData, id: EntityId) -> bool {
    let (dir, speed, x, y) = {
        let Some(e) = world.get(id) else { return false };
        if e.move_dir >= 8 {
            return false;
        }
        let Some(info) = e.entity_type.info() else {
            return false;
        };
        (e.move_dir as usize, info.speed, e.x, e.y)
    };
    let (sx, sy) = DIR_SPEED[dir];
    let tryx = x + speed * sx;
    let tryy = y + speed * sy;
    match world.get_mut(id) {
        Some(e) => crate::physics::try_move(e, map, tryx, tryy),
        None => false,
    }
}

/// Doom's `P_TryWalk`: attempt a move in the current direction; on
/// success, reset `move_count` from a P_Random draw.
fn monster_try_walk(world: &mut World, map: &MapData, id: EntityId) -> bool {
    if !monster_move(world, map, id) {
        return false;
    }
    let r = world.p_random();
    if let Some(e) = world.get_mut(id) {
        e.move_count = r & 15;
    }
    true
}

/// Port of Doom's `P_NewChaseDir`. Picks a new `move_dir` for the
/// monster, trying: direct diagonal -> preferred axes -> keep going ->
/// exhaustive scan -> turn around -> give up (NODIR). Each
/// `monster_try_walk` attempt consumes a P_Random on success; there
/// are two extra `P_Random` gates (axis-swap and scan-direction)
/// whose consumption order matches the reference engine.
fn monster_new_chase_dir(world: &mut World, map: &MapData, id: EntityId) {
    let Some(target_id) = world.get(id).and_then(|e| e.target) else {
        return;
    };
    let (olddir, sx, sy) = match world.get(id) {
        Some(e) => (e.move_dir, e.x, e.y),
        None => return,
    };
    let turnaround = OPPOSITE_DIR[olddir.min(8) as usize];

    let (tx, ty) = match world.get(target_id) {
        Some(t) => (t.x, t.y),
        None => return,
    };
    let deltax = tx - sx;
    let deltay = ty - sy;

    let mut d1 = if deltax > 10 * FRACUNIT {
        0 // DI_EAST
    } else if deltax < -10 * FRACUNIT {
        4 // DI_WEST
    } else {
        DI_NODIR
    };
    let mut d2 = if deltay < -10 * FRACUNIT {
        6 // DI_SOUTH
    } else if deltay > 10 * FRACUNIT {
        2 // DI_NORTH
    } else {
        DI_NODIR
    };

    // Direct diagonal route when both axes are preferred.
    if d1 != DI_NODIR && d2 != DI_NODIR {
        let idx = ((deltay < 0) as usize) << 1 | ((deltax > 0) as usize);
        let diag = DIAG_DIRS[idx];
        if diag != turnaround {
            if let Some(e) = world.get_mut(id) {
                e.move_dir = diag;
            }
            if monster_try_walk(world, map, id) {
                return;
            }
        }
    }

    // Swap preferred axes under Doom's `P_Random() > 200` gate.
    if world.p_random() > 200 || deltay.abs() > deltax.abs() {
        (d1, d2) = (d2, d1);
    }
    if d1 == turnaround {
        d1 = DI_NODIR;
    }
    if d2 == turnaround {
        d2 = DI_NODIR;
    }

    if d1 != DI_NODIR {
        if let Some(e) = world.get_mut(id) {
            e.move_dir = d1;
        }
        if monster_try_walk(world, map, id) {
            return;
        }
    }
    if d2 != DI_NODIR {
        if let Some(e) = world.get_mut(id) {
            e.move_dir = d2;
        }
        if monster_try_walk(world, map, id) {
            return;
        }
    }

    // No direct path — keep going the old way, then exhaustive search.
    if olddir != DI_NODIR {
        if let Some(e) = world.get_mut(id) {
            e.move_dir = olddir;
        }
        if monster_try_walk(world, map, id) {
            return;
        }
    }

    // Randomly pick search direction (CCW vs CW).
    if world.p_random() & 1 != 0 {
        for tdir in DI_EAST..=DI_SOUTHEAST {
            if tdir == turnaround {
                continue;
            }
            if let Some(e) = world.get_mut(id) {
                e.move_dir = tdir;
            }
            if monster_try_walk(world, map, id) {
                return;
            }
        }
    } else {
        for tdir in (DI_EAST..=DI_SOUTHEAST).rev() {
            if tdir == turnaround {
                continue;
            }
            if let Some(e) = world.get_mut(id) {
                e.move_dir = tdir;
            }
            if monster_try_walk(world, map, id) {
                return;
            }
        }
    }

    // Last resort: turn around.
    if turnaround != DI_NODIR {
        if let Some(e) = world.get_mut(id) {
            e.move_dir = turnaround;
        }
        if monster_try_walk(world, map, id) {
            return;
        }
    }

    // Can't move at all.
    if let Some(e) = world.get_mut(id) {
        e.move_dir = DI_NODIR;
    }
}

/// Check line of sight between two entities.
pub fn check_entity_sight(world: &World, map: &MapData, id: EntityId, target_id: EntityId) -> bool {
    let Some(entity) = world.get(id) else { return false };
    let Some(target) = world.get(target_id) else { return false };
    let eye_z = entity.z + entity.height - (entity.height >> 2);
    crate::physics::check_sight(
        map,
        entity.x, entity.y, eye_z,
        target.x, target.y, target.z, target.height,
    )
}

/// A_Look: scan for players. If found and visible, set target and switch to seestate.
pub fn a_look(world: &mut World, map: &MapData, id: EntityId) {
    let Some(entity) = world.get(id) else { return };
    let my_x = entity.x;
    let my_y = entity.y;
    let my_angle = entity.angle;
    let eye_z = entity.z + entity.height - (entity.height >> 2);
    let etype = entity.entity_type;

    // Doom's P_LookForPlayers: only wakes up on players in the front
    // 180° cone unless they're within melee range. Exiting A_Look too
    // eagerly (what we did before) makes every monster in a room
    // instantly turn at the player, which is more aggressive than the
    // demos expect.
    const MELEE_CONE_RANGE: Fixed = 64 * FRACUNIT; // Doom's MELEERANGE

    let mut best_id = None;
    let mut best_dist = i64::MAX;
    for pid in world.controlled_entities() {
        let Some(player) = world.get(pid) else { continue };
        let dx = player.x - my_x;
        let dy = player.y - my_y;
        let manhattan = dx.abs() as i64 + dy.abs() as i64;
        if manhattan >= best_dist {
            continue;
        }

        // Frontal-cone gate (skipped at melee range).
        let approx_dist = dx.abs().max(dy.abs()) + (dx.abs().min(dy.abs()) >> 1);
        if approx_dist > MELEE_CONE_RANGE {
            let to_angle = crate::map::point_to_angle(dx, dy);
            let diff = to_angle.wrapping_sub(my_angle);
            // "Behind me" = angle diff in (ANG90, ANG270).
            if diff > ANG90 && diff < ANG90.wrapping_mul(3) {
                continue;
            }
        }

        if crate::physics::check_sight(
            map,
            my_x, my_y, eye_z,
            player.x, player.y, player.z, player.height,
        ) {
            best_dist = manhattan;
            best_id = Some(pid);
        }
    }

    if let Some(target_id) = best_id {
        let Some(info) = etype.info() else { return };
        if let Some(entity) = world.get_mut(id) {
            entity.target = Some(target_id);
            if !info.seestate.is_null() {
                set_entity_state(entity, info.seestate);
            }
        }
    }
}

/// A_FaceTarget: turn to face the current target.
///
/// Matches Doom's P_FaceTarget: clears MF_AMBUSH, snaps the angle to
/// point at the target, and — if the target is `MF_SHADOW` (spectre or
/// invisibility power-up) — adds a random angle perturbation. The two
/// extra P_Random draws for shadow targets are load-bearing for PRNG
/// alignment even though they're behaviourally near-invisible.
pub fn a_face_target(world: &mut World, id: EntityId) {
    let (target_x, target_y, target_shadow) = {
        let Some(entity) = world.get(id) else { return };
        let Some(tid) = entity.target else { return };
        let Some(target) = world.get(tid) else { return };
        (
            target.x,
            target.y,
            target.flags.contains(MobjFlag::Shadow),
        )
    };
    let (sx, sy) = match world.get(id) {
        Some(e) => (e.x, e.y),
        None => return,
    };
    let base_angle = crate::map::point_to_angle(target_x - sx, target_y - sy);
    let shadow_offset: i32 = if target_shadow {
        (world.p_random() - world.p_random()) << 21
    } else {
        0
    };
    if let Some(entity) = world.get_mut(id) {
        entity.flags.remove(MobjFlag::Ambush);
        entity.angle = base_angle.wrapping_add(shadow_offset as u32);
    }
}

/// A_Chase: move toward target, attack if in range.
pub fn a_chase(world: &mut World, map: &MapData, id: EntityId) {
    let (etype, target, reaction, move_count, just_attacked) = {
        let Some(e) = world.get(id) else { return };
        (
            e.entity_type,
            e.target,
            e.reaction_time,
            e.move_count,
            e.flags.contains(MobjFlag::JustAttacked),
        )
    };

    // Doom A_Chase's first branch: skip everything else for one tic after
    // the monster transitioned into its missile state. Without this the
    // monster attacks every tic; with it, it gets one tic of "breather",
    // which matches the reference engine's attack cadence.
    if just_attacked {
        if let Some(e) = world.get_mut(id) {
            e.flags.remove(MobjFlag::JustAttacked);
        }
        return;
    }

    // Decrease reaction time
    if reaction > 0
        && let Some(e) = world.get_mut(id)
    {
        e.reaction_time -= 1;
    }

    // No target? Go back to looking.
    let Some(target_id) = target else {
        let Some(info) = etype.info() else { return };
        if let Some(e) = world.get_mut(id) { set_entity_state(e, info.spawnstate); }
        return;
    };

    // Doom's A_Chase does *not* call A_FaceTarget here — it only turns
    // the monster's angle gradually toward its `movedir` (ANG45/tic).
    // Attack actions (A_PosAttack, A_TroopAttack, ...) call A_FaceTarget
    // themselves right before firing, so the sprite still ends up
    // aimed at the player when an attack fires.
    gradual_turn_to_movedir(world, id);

    let Some(info) = etype.info() else { return };

    // Check melee range
    if !info.meleestate.is_null() && check_melee_range(world, id, target_id) {
        if let Some(e) = world.get_mut(id) { set_entity_state(e, info.meleestate); }
        return;
    }

    // Check missile range (requires line of sight). Doom gates this on
    // the movecount too: while the monster is mid-move_count on skills
    // below Nightmare, it doesn't enter missilestate.
    let missile_ready = !info.missilestate.is_null()
        && reaction <= 0
        && move_count == 0
        && check_missile_range(world, map, id, target_id);
    if missile_ready {
        if let Some(e) = world.get_mut(id) {
            set_entity_state(e, info.missilestate);
            // Doom sets MF_JUSTATTACKED here; next A_Chase's first
            // branch clears it and returns early (one-tic pause).
            e.flags.insert(MobjFlag::JustAttacked);
        }
        return;
    }

    // Chase towards target. Matches Doom's
    //   `if (--actor->movecount < 0 || !P_Move(actor)) P_NewChaseDir(actor);`
    //
    // movecount is decremented unconditionally; if it goes negative OR
    // the step was blocked, we pick a new heading.
    let expired = match world.get_mut(id) {
        Some(e) => {
            e.move_count -= 1;
            e.move_count < 0
        }
        None => return,
    };
    if expired || !monster_move(world, map, id) {
        monster_new_chase_dir(world, map, id);
    }

    // Doom's A_Chase ends with `if (info->activesound && P_Random() < 3)
    // S_StartSound`. We don't play sound but we still consume the random
    // so the global PRNG index stays aligned with the reference engine.
    if etype.info().is_some_and(|i| i.activesound != 0) {
        let _ = world.p_random();
    }
}

#[inline]
pub fn check_melee_range(world: &World, id: EntityId, target_id: EntityId) -> bool {
    let Some(entity) = world.get(id) else { return false };
    let Some(target) = world.get(target_id) else { return false };
    let dist = (target.x - entity.x).abs() + (target.y - entity.y).abs();
    dist < 64 * FRACUNIT + target.radius
}

/// Port of Doom's `P_CheckMissileRange` for the classic zombie / imp /
/// demon set. Calls P_Random once per invocation (Doom does the same),
/// also requires line of sight. Returns whether the monster should fire
/// on this tic.
pub fn check_missile_range(
    world: &mut World,
    map: &MapData,
    id: EntityId,
    target_id: EntityId,
) -> bool {
    // Sight gate first.
    if !check_entity_sight(world, map, id, target_id) {
        return false;
    }

    let (ex, ey, has_melee, just_hit) = {
        let Some(e) = world.get(id) else { return false };
        let Some(info) = e.entity_type.info() else {
            return false;
        };
        (
            e.x,
            e.y,
            !info.meleestate.is_null(),
            e.flags.contains(MobjFlag::JustHit),
        )
    };
    let (tx, ty) = match world.get(target_id) {
        Some(t) => (t.x, t.y),
        None => return false,
    };

    // MF_JUSTHIT forces an immediate return fire in Doom.
    if just_hit {
        if let Some(e) = world.get_mut(id) {
            e.flags.remove(MobjFlag::JustHit);
        }
        return true;
    }

    // Approximate distance (Doom uses P_AproxDistance): max(|dx|,|dy|) +
    // 0.5*min. We use Chebyshev which is already close enough for the
    // purpose of this probability gate.
    let dx = (tx - ex).abs();
    let dy = (ty - ey).abs();
    let approx = dx.max(dy) + (dx.min(dy) >> 1);
    // Drop the 64-unit melee buffer; Doom also penalizes non-melee
    // monsters so they fire from further away.
    let mut dist = (approx - 64 * FRACUNIT).max(0);
    if !has_melee {
        dist = (dist - 128 * FRACUNIT).max(0);
    }
    let dist = (dist >> FRACBITS).min(200);

    // Doom's final gate: `if (P_Random() < dist) return false;`
    // Closer target -> smaller dist -> less likely to reject -> fires more.
    world.p_random() >= dist
}

// --- Weapon Framework ---

/// Maximum bob amplitude.
pub const MAXBOB: Fixed = 0x10_0000; // 16.0 in fixed-point
/// Weapon "ready" Y position.
pub const WEAPONTOP: Fixed = 32 * FRACUNIT;
/// Weapon lowered Y position.
pub const WEAPONBOTTOM: Fixed = 128 * FRACUNIT;
/// Raise/lower speed per tic.
pub const RAISESPEED: Fixed = 6 * FRACUNIT;

/// Calculate weapon bob magnitude from player momentum.
pub fn update_weapon_bob(world: &mut World, pid: EntityId) {
    let Some(entity) = world.get(pid) else { return };
    let momx = entity.momx;
    let momy = entity.momy;
    let bob = ((fixed_mul(momx, momx) + fixed_mul(momy, momy)) >> 2).min(MAXBOB);
    if let Some(ps) = world.player_state_mut(pid) {
        ps.bob = bob;
    }
}

/// Set weapon psprite to a given state.
pub fn psp_set_state(world: &mut World, pid: EntityId, state: StateNum) {
    if let Some(ps) = world.player_state_mut(pid) {
        ps.psp_state = state;
        if let Some(st) = state.get() {
            ps.psp_tics = st.tics;
        }
    }
}

/// Try to consume ammo. Returns false if not enough.
pub fn use_ammo(world: &mut World, pid: EntityId, ammo: AmmoType, count: i32) -> bool {
    let Some(ps) = world.player_state_mut(pid) else { return false };
    let idx = ammo as usize;
    if ps.ammo[idx] < count { return false; }
    ps.ammo[idx] -= count;
    true
}

// --- Sector ---

/// Check if the player is in a special sector (secrets, damage floors, etc).
pub fn check_player_sector(world: &mut World, map: &MapData, pid: EntityId) {
    let Some(entity) = world.get(pid) else { return };
    // Only trigger when on the ground
    if entity.z != entity.floor_z { return; }
    let ssect = crate::physics::find_subsector(map, entity.x, entity.y);
    if ssect >= map.subsectors.len() { return; }
    let sector_idx = map.subsectors[ssect].sector as usize;
    if sector_idx >= map.sectors.len() { return; }
    let special = map.sectors[sector_idx].special;

    match special {
        9 => {
            // Secret sector — increment count and clear special
            if let Some(ps) = world.player_state_mut(pid) {
                ps.secret_count += 1;
            }
            // Clear the special so it only triggers once
            if sector_idx < world.sectors.len() {
                world.sectors[sector_idx].special = 0;
            }
        }
        5 => {
            // 10 damage per second (nukage)
            if world.tick.is_multiple_of(32) {
                apply_damage_to(world, pid, 10, None);
            }
        }
        7 => {
            // 5 damage per second (slime)
            if world.tick.is_multiple_of(32) {
                apply_damage_to(world, pid, 5, None);
            }
        }
        16 => {
            // 20 damage per second (super hellslime)
            if world.tick.is_multiple_of(32) {
                apply_damage_to(world, pid, 20, None);
            }
        }
        _ => {}
    }
}