issun-bevy 0.10.0

ISSUN plugins for Bevy ECS
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
//! Unit tests for contagion propagation

#[cfg(test)]
#[allow(clippy::module_inception)]
mod tests {
    use bevy::prelude::*;

    use super::super::{components::*, events::*, plugin::ContagionPlugin, resources::*};
    use crate::IssunCorePlugin;

    // ==================== Test Setup Helpers ====================

    fn create_test_app() -> App {
        let mut app = App::new();
        app.add_plugins((
            MinimalPlugins,
            IssunCorePlugin,
            ContagionPlugin::default().with_seed(42),
        ));
        app
    }

    fn create_test_app_with_config(config: ContagionConfig) -> App {
        let mut app = App::new();
        app.add_plugins((
            MinimalPlugins,
            IssunCorePlugin,
            ContagionPlugin::default().with_seed(42).with_config(config),
        ));
        app
    }

    fn setup_basic_network(app: &mut App) -> (Entity, Entity, Entity) {
        let node_a = app
            .world_mut()
            .spawn(ContagionNode::new("node_a", NodeType::City, 10000))
            .id();

        let node_b = app
            .world_mut()
            .spawn(ContagionNode::new("node_b", NodeType::City, 8000))
            .id();

        let edge = app
            .world_mut()
            .spawn(PropagationEdge::new("edge_ab", node_a, node_b, 1.0))
            .id();

        // Register nodes
        {
            let mut registry = app.world_mut().resource_mut::<NodeRegistry>();
            registry.register("node_a", node_a);
            registry.register("node_b", node_b);
        }

        (node_a, node_b, edge)
    }

    // ==================== Test: Spawn Contagion ====================

    #[test]
    fn test_spawn_contagion() {
        let mut app = create_test_app();
        let (node_a, _node_b, _edge) = setup_basic_network(&mut app);

        // Spawn contagion
        app.world_mut().write_message(ContagionSpawnRequested {
            contagion_id: "disease_1".to_string(),
            content: ContagionContent::Disease {
                severity: DiseaseLevel::Moderate,
                location: "node_a".to_string(),
            },
            origin_node: node_a,
            mutation_rate: 0.1,
        });

        app.update();

        // Verify contagion entity created
        let mut query = app.world_mut().query::<&Contagion>();
        let contagions = query.iter(app.world()).count();
        assert_eq!(contagions, 1, "Should spawn 1 contagion");

        // Verify initial infection created
        let mut query = app.world_mut().query::<&ContagionInfection>();
        let infections = query.iter(app.world()).count();
        assert_eq!(infections, 1, "Should create initial infection");

        // Verify infection is in Incubating state
        let mut query = app.world_mut().query::<&ContagionInfection>();
        let infection = query.iter(app.world()).next().unwrap();
        assert!(
            matches!(infection.state, InfectionState::Incubating { .. }),
            "Initial infection should be Incubating"
        );

        // Verify spawned event
        let messages = app.world().resource::<Messages<ContagionSpawnedEvent>>();
        let mut cursor = messages.get_cursor();
        let spawned_events: Vec<_> = cursor.read(messages).cloned().collect();
        assert_eq!(spawned_events.len(), 1, "Should emit ContagionSpawnedEvent");
    }

    // ==================== Test: State Progression ====================

    #[test]
    fn test_state_progression_turn_based() {
        let config = ContagionConfig {
            time_mode: TimeMode::TurnBased,
            default_incubation_duration: DurationConfig::new(2.0, 0.0),
            default_active_duration: DurationConfig::new(3.0, 0.0),
            default_immunity_duration: DurationConfig::new(2.0, 0.0),
            ..Default::default()
        };

        let mut app = create_test_app_with_config(config);
        let (node_a, _node_b, _edge) = setup_basic_network(&mut app);

        // Spawn contagion
        app.world_mut().write_message(ContagionSpawnRequested {
            contagion_id: "disease_1".to_string(),
            content: ContagionContent::Disease {
                severity: DiseaseLevel::Moderate,
                location: "node_a".to_string(),
            },
            origin_node: node_a,
            mutation_rate: 0.0,
        });
        app.update();

        // Helper to get infection state
        let get_state = |app: &mut App| -> InfectionState {
            let mut query = app.world_mut().query::<&ContagionInfection>();
            query.iter(app.world()).next().unwrap().state.clone()
        };

        // Turn 0: Incubating
        assert!(matches!(
            get_state(&mut app),
            InfectionState::Incubating { .. }
        ));

        // Turn 1: Still Incubating
        app.world_mut().write_message(TurnAdvancedMessage);
        app.update();
        assert!(matches!(
            get_state(&mut app),
            InfectionState::Incubating { .. }
        ));

        // Turn 2: Transition to Active
        app.world_mut().write_message(TurnAdvancedMessage);
        app.update();
        assert!(matches!(get_state(&mut app), InfectionState::Active { .. }));

        // Turn 3-4: Still Active
        for _ in 0..2 {
            app.world_mut().write_message(TurnAdvancedMessage);
            app.update();
        }
        assert!(matches!(get_state(&mut app), InfectionState::Active { .. }));

        // Turn 5: Transition to Recovered
        app.world_mut().write_message(TurnAdvancedMessage);
        app.update();
        assert!(matches!(
            get_state(&mut app),
            InfectionState::Recovered { .. }
        ));

        // Turn 6: Still Recovered
        app.world_mut().write_message(TurnAdvancedMessage);
        app.update();
        assert!(matches!(
            get_state(&mut app),
            InfectionState::Recovered { .. }
        ));

        // Turn 7: Transition to Plain
        app.world_mut().write_message(TurnAdvancedMessage);
        app.update();
        assert!(matches!(get_state(&mut app), InfectionState::Plain));
    }

    // ==================== Test: State-Based Transmission Rates ====================

    #[test]
    fn test_state_based_transmission_rates() {
        let config = ContagionConfig {
            time_mode: TimeMode::TurnBased,
            global_propagation_rate: 1.0,
            incubation_transmission_rate: 0.2,
            active_transmission_rate: 0.8,
            recovered_transmission_rate: 0.05,
            plain_transmission_rate: 0.0,
            default_incubation_duration: DurationConfig::new(1.0, 0.0),
            default_active_duration: DurationConfig::new(1.0, 0.0),
            default_immunity_duration: DurationConfig::new(1.0, 0.0),
            ..Default::default()
        };

        let mut app = create_test_app_with_config(config);

        // Create network: A → B → C → D
        let node_a = app
            .world_mut()
            .spawn(ContagionNode::new("a", NodeType::City, 1000))
            .id();
        let node_b = app
            .world_mut()
            .spawn(ContagionNode::new("b", NodeType::City, 1000))
            .id();
        let node_c = app
            .world_mut()
            .spawn(ContagionNode::new("c", NodeType::City, 1000))
            .id();
        let node_d = app
            .world_mut()
            .spawn(ContagionNode::new("d", NodeType::City, 1000))
            .id();

        app.world_mut()
            .spawn(PropagationEdge::new("ab", node_a, node_b, 1.0));
        app.world_mut()
            .spawn(PropagationEdge::new("bc", node_b, node_c, 1.0));
        app.world_mut()
            .spawn(PropagationEdge::new("cd", node_c, node_d, 1.0));

        {
            let mut registry = app.world_mut().resource_mut::<NodeRegistry>();
            registry.register("a", node_a);
            registry.register("b", node_b);
            registry.register("c", node_c);
            registry.register("d", node_d);
        }

        // Spawn at node A
        app.world_mut().write_message(ContagionSpawnRequested {
            contagion_id: "test".to_string(),
            content: ContagionContent::Custom {
                key: "test".to_string(),
                data: "data".to_string(),
            },
            origin_node: node_a,
            mutation_rate: 0.0,
        });
        app.update();

        // Count infected nodes
        let count_infected = |app: &mut App| -> usize {
            let mut query = app.world_mut().query::<&ContagionInfection>();
            query.iter(app.world()).count()
        };

        // Initially: 1 infected (A in Incubating)
        assert_eq!(count_infected(&mut app), 1);

        // Propagation in Incubating state (rate=0.2, may not spread)
        app.world_mut().write_message(PropagationStepRequested);
        app.update();
        let count_after_incubating = count_infected(&mut app);

        // Advance to Active state
        app.world_mut().write_message(TurnAdvancedMessage);
        app.update();

        // Propagation in Active state (rate=0.8, likely spreads)
        app.world_mut().write_message(PropagationStepRequested);
        app.update();
        let count_after_active = count_infected(&mut app);

        // Active transmission should be more effective than Incubating
        assert!(
            count_after_active >= count_after_incubating,
            "Active state should transmit at least as much as Incubating"
        );
    }

    // ==================== Test: Time Modes ====================

    #[test]
    fn test_tick_based_time_mode() {
        let config = ContagionConfig {
            time_mode: TimeMode::TickBased,
            default_incubation_duration: DurationConfig::new(2.0, 0.0), // 120 ticks
            default_active_duration: DurationConfig::new(1.0, 0.0),     // 60 ticks
            default_immunity_duration: DurationConfig::new(1.0, 0.0),   // 60 ticks
            ..Default::default()
        };

        let mut app = create_test_app_with_config(config);
        let (node_a, _node_b, _edge) = setup_basic_network(&mut app);

        app.world_mut().write_message(ContagionSpawnRequested {
            contagion_id: "test".to_string(),
            content: ContagionContent::Custom {
                key: "test".to_string(),
                data: "data".to_string(),
            },
            origin_node: node_a,
            mutation_rate: 0.0,
        });
        app.update();

        // Should start in Incubating
        let infection = {
            let mut query = app.world_mut().query::<&ContagionInfection>();
            query.iter(app.world()).next().unwrap().clone()
        };
        assert!(matches!(infection.state, InfectionState::Incubating { .. }));

        // Progress through ticks (120 ticks for incubation)
        for _ in 0..120 {
            app.update();
        }

        // Should now be Active
        let infection = {
            let mut query = app.world_mut().query::<&ContagionInfection>();
            query.iter(app.world()).next().unwrap().clone()
        };
        assert!(matches!(infection.state, InfectionState::Active { .. }));
    }

    // ==================== Test: Mutation ====================

    #[test]
    fn test_mutation() {
        let config = ContagionConfig {
            time_mode: TimeMode::TurnBased,
            global_propagation_rate: 1.0,
            active_transmission_rate: 1.0,
            default_incubation_duration: DurationConfig::new(0.0, 0.0),
            default_active_duration: DurationConfig::new(10.0, 0.0),
            ..Default::default()
        };

        let mut app = create_test_app_with_config(config);
        let (node_a, _node_b, edge) = setup_basic_network(&mut app);

        // Set edge noise level to enable mutations
        {
            let mut edge_mut = app.world_mut().entity_mut(edge);
            edge_mut.insert(PropagationEdge {
                edge_id: "edge_ab".to_string(),
                from_node: node_a,
                to_node: _node_b,
                transmission_rate: 1.0,
                noise_level: 1.0, // Enable mutations
            });
        }

        // Spawn with high mutation rate
        app.world_mut().write_message(ContagionSpawnRequested {
            contagion_id: "disease_1".to_string(),
            content: ContagionContent::Disease {
                severity: DiseaseLevel::Mild,
                location: "node_a".to_string(),
            },
            origin_node: node_a,
            mutation_rate: 1.0, // 100% mutation
        });
        app.update();

        // Advance turn to get disease into Active state for higher transmission rate
        app.world_mut().write_message(TurnAdvancedMessage);
        app.update();

        // Trigger propagation multiple times to increase mutation chance
        for _ in 0..50 {
            app.world_mut().write_message(PropagationStepRequested);
            app.update();
        }

        // Check if mutation occurred
        let messages = app.world().resource::<Messages<ContagionSpreadEvent>>();
        let mut cursor = messages.get_cursor();
        let spread_events: Vec<_> = cursor
            .read(messages)
            .filter(|e| e.is_mutation)
            .cloned()
            .collect();

        assert!(
            !spread_events.is_empty(),
            "Should have at least one mutation event"
        );

        // Check that mutated contagion has different ID
        let mutations_with_original = spread_events
            .iter()
            .filter(|e| e.original_id.is_some())
            .count();
        assert!(
            mutations_with_original > 0,
            "Mutations should reference original ID"
        );
    }

    // ==================== Test: Credibility Decay ====================

    #[test]
    fn test_credibility_decay() {
        let config = ContagionConfig {
            lifetime_turns: 10,
            min_credibility: 0.2,
            ..Default::default()
        };

        let mut app = create_test_app_with_config(config);
        let (node_a, _node_b, _edge) = setup_basic_network(&mut app);

        app.world_mut().write_message(ContagionSpawnRequested {
            contagion_id: "rumor_1".to_string(),
            content: ContagionContent::Political {
                faction: "FactionA".to_string(),
                claim: "Test claim".to_string(),
            },
            origin_node: node_a,
            mutation_rate: 0.0,
        });
        app.update();

        // Initial credibility should be 1.0
        let initial_credibility = {
            let mut query = app.world_mut().query::<&Contagion>();
            query.iter(app.world()).next().unwrap().credibility
        };
        assert_eq!(initial_credibility, 1.0);

        // Apply decay over 5 turns
        app.world_mut()
            .write_message(CredibilityDecayRequested { elapsed_turns: 5 });
        app.update();

        let after_decay = {
            let mut query = app.world_mut().query::<&Contagion>();
            query.iter(app.world()).next().unwrap().credibility
        };
        assert!(after_decay < 1.0, "Credibility should decay");
        assert!(after_decay > 0.0, "Credibility should not reach zero yet");

        // Apply decay to expire contagion
        app.world_mut()
            .write_message(CredibilityDecayRequested { elapsed_turns: 10 });
        app.update();

        // Contagion should be removed
        let contagions = {
            let mut query = app.world_mut().query::<&Contagion>();
            query.iter(app.world()).count()
        };
        assert_eq!(
            contagions, 0,
            "Contagion should be removed after full decay"
        );

        // Check removal event
        let messages = app.world().resource::<Messages<ContagionRemovedEvent>>();
        let mut cursor = messages.get_cursor();
        let removal_events: Vec<_> = cursor.read(messages).cloned().collect();
        assert_eq!(removal_events.len(), 1, "Should emit removal event");
    }

    // ==================== Test: Reinfection ====================

    #[test]
    fn test_reinfection_disabled() {
        let config = ContagionConfig {
            time_mode: TimeMode::TurnBased,
            default_incubation_duration: DurationConfig::new(0.0, 0.0),
            default_active_duration: DurationConfig::new(0.0, 0.0),
            default_immunity_duration: DurationConfig::new(0.0, 0.0),
            default_reinfection_enabled: false,
            ..Default::default()
        };

        let mut app = create_test_app_with_config(config);
        let (node_a, _node_b, _edge) = setup_basic_network(&mut app);

        // Spawn contagion
        app.world_mut().write_message(ContagionSpawnRequested {
            contagion_id: "disease_1".to_string(),
            content: ContagionContent::Disease {
                severity: DiseaseLevel::Moderate,
                location: "node_a".to_string(),
            },
            origin_node: node_a,
            mutation_rate: 0.0,
        });
        app.update();

        // Progress to Plain state
        for _ in 0..5 {
            app.world_mut().write_message(TurnAdvancedMessage);
            app.update();
        }

        // Verify in Plain state
        let infection = {
            let mut query = app.world_mut().query::<&ContagionInfection>();
            query.iter(app.world()).next().unwrap().clone()
        };
        assert!(matches!(infection.state, InfectionState::Plain));

        // Verify reinfection is disabled
        let contagion = {
            let mut query = app.world_mut().query::<&Contagion>();
            query.iter(app.world()).next().unwrap().clone()
        };
        assert!(!contagion.reinfection_enabled);
    }

    // ==================== Test: Deterministic RNG ====================

    #[test]
    fn test_deterministic_rng() {
        // Run simulation twice with same seed
        let run_simulation = || -> Vec<String> {
            let mut app = App::new();
            app.add_plugins((
                MinimalPlugins,
                IssunCorePlugin,
                ContagionPlugin::default().with_seed(12345),
            ));

            let (node_a, _node_b, _edge) = setup_basic_network(&mut app);

            app.world_mut().write_message(ContagionSpawnRequested {
                contagion_id: "test".to_string(),
                content: ContagionContent::Disease {
                    severity: DiseaseLevel::Moderate,
                    location: "node_a".to_string(),
                },
                origin_node: node_a,
                mutation_rate: 0.5,
            });
            app.update();

            // Run multiple propagation steps
            for _ in 0..5 {
                app.world_mut().write_message(PropagationStepRequested);
                app.update();
            }

            // Collect event IDs
            let messages = app.world().resource::<Messages<ContagionSpreadEvent>>();
            let mut cursor = messages.get_cursor();
            cursor
                .read(messages)
                .map(|e| e.contagion_id.clone())
                .collect()
        };

        let results1 = run_simulation();
        let results2 = run_simulation();

        assert_eq!(
            results1, results2,
            "Same seed should produce identical results"
        );
    }

    // ==================== Test: Entity Deletion Handling ====================

    #[test]
    fn test_entity_deletion_handling() {
        let mut app = create_test_app();
        let (node_a, _node_b, _edge) = setup_basic_network(&mut app);

        // Spawn contagion
        app.world_mut().write_message(ContagionSpawnRequested {
            contagion_id: "disease_1".to_string(),
            content: ContagionContent::Disease {
                severity: DiseaseLevel::Moderate,
                location: "node_a".to_string(),
            },
            origin_node: node_a,
            mutation_rate: 0.0,
        });
        app.update();

        let contagion_entity = {
            let mut query = app.world_mut().query::<(Entity, &Contagion)>();
            query.iter(app.world()).next().unwrap().0
        };

        // Delete contagion entity
        app.world_mut().despawn(contagion_entity);

        // Run systems - should not panic
        app.world_mut().write_message(PropagationStepRequested);
        app.update();
        app.world_mut().write_message(TurnAdvancedMessage);
        app.update();

        // Systems should handle missing entities gracefully
        // (no assertions needed - test passes if no panic)
    }

    // ==================== Test: State Change Events ====================

    #[test]
    fn test_state_change_events() {
        let config = ContagionConfig {
            time_mode: TimeMode::TurnBased,
            default_incubation_duration: DurationConfig::new(1.0, 0.0),
            default_active_duration: DurationConfig::new(1.0, 0.0),
            default_immunity_duration: DurationConfig::new(1.0, 0.0),
            ..Default::default()
        };

        let mut app = create_test_app_with_config(config);
        let (node_a, _node_b, _edge) = setup_basic_network(&mut app);

        app.world_mut().write_message(ContagionSpawnRequested {
            contagion_id: "disease_1".to_string(),
            content: ContagionContent::Disease {
                severity: DiseaseLevel::Moderate,
                location: "node_a".to_string(),
            },
            origin_node: node_a,
            mutation_rate: 0.0,
        });
        app.update();

        // Clear initial events
        let messages = app
            .world()
            .resource::<Messages<InfectionStateChangedEvent>>();
        let mut cursor = messages.get_cursor();
        let _: Vec<_> = cursor.read(messages).cloned().collect();

        // Trigger state transitions
        for _ in 0..3 {
            app.world_mut().write_message(TurnAdvancedMessage);
            app.update();
        }

        // Collect state change events
        let messages = app
            .world()
            .resource::<Messages<InfectionStateChangedEvent>>();
        let mut cursor = messages.get_cursor();
        let state_changes: Vec<_> = cursor.read(messages).cloned().collect();

        // Should have transitions: Incubating→Active, Active→Recovered, Recovered→Plain
        assert_eq!(state_changes.len(), 3, "Should emit 3 state change events");

        // Verify transition sequence
        assert_eq!(state_changes[0].old_state, InfectionStateType::Incubating);
        assert_eq!(state_changes[0].new_state, InfectionStateType::Active);
        assert_eq!(state_changes[1].old_state, InfectionStateType::Active);
        assert_eq!(state_changes[1].new_state, InfectionStateType::Recovered);
        assert_eq!(state_changes[2].old_state, InfectionStateType::Recovered);
        assert_eq!(state_changes[2].new_state, InfectionStateType::Plain);
    }
}