issun 0.10.0

A mini game engine for logic-focused games - Build games in ISSUN (一寸) of time
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
//! MOD Bridge System
//!
//! This system bridges MOD events to Plugin configurations, enabling runtime control
//! of plugins through MOD scripts.

use crate::context::ResourceContext;
use crate::event::EventBus;
use crate::modding::events::*;
use crate::system::System;
use async_trait::async_trait;
use std::any::Any;

/// System that bridges MOD events to Plugin configurations
///
/// This system listens to MOD-issued events (PluginEnabledEvent, PluginDisabledEvent,
/// PluginParameterChangedEvent) and updates plugin configurations accordingly.
///
/// # Supported Plugins
///
/// Currently supports:
/// - `combat` / `issun:combat` - Combat system
/// - `inventory` / `issun:inventory` - Inventory system
///
/// # Example
///
/// ```ignore
/// use issun::engine::ModBridgeSystem;
///
/// // Register in GameBuilder
/// builder.with_system(ModBridgeSystem::new());
/// ```
///
/// # MOD Usage
///
/// ```rhai
/// // In a MOD script
/// enable_plugin("combat");
/// set_plugin_param("combat", "max_hp", 150);
/// ```
pub struct ModBridgeSystem;

impl ModBridgeSystem {
    /// Create a new ModBridgeSystem
    pub fn new() -> Self {
        Self
    }

    /// Update method using ResourceContext (Modern pattern)
    ///
    /// This method is the recommended way to update the system.
    pub async fn update_resources(&mut self, resources: &mut ResourceContext) {
        // Step 1: Collect all MOD events
        let enabled_events: Vec<PluginEnabledEvent> = {
            if let Some(mut event_bus) = resources.get_mut::<EventBus>().await {
                event_bus
                    .reader::<PluginEnabledEvent>()
                    .iter()
                    .cloned()
                    .collect()
            } else {
                Vec::new()
            }
        };

        let disabled_events: Vec<PluginDisabledEvent> = {
            if let Some(mut event_bus) = resources.get_mut::<EventBus>().await {
                event_bus
                    .reader::<PluginDisabledEvent>()
                    .iter()
                    .cloned()
                    .collect()
            } else {
                Vec::new()
            }
        };

        let param_events: Vec<PluginParameterChangedEvent> = {
            if let Some(mut event_bus) = resources.get_mut::<EventBus>().await {
                event_bus
                    .reader::<PluginParameterChangedEvent>()
                    .iter()
                    .cloned()
                    .collect()
            } else {
                Vec::new()
            }
        };

        // Step 2: Process enable events
        for event in enabled_events {
            Self::handle_enable_resources(resources, &event).await;
        }

        // Step 3: Process disable events
        for event in disabled_events {
            Self::handle_disable_resources(resources, &event).await;
        }

        // Step 4: Process parameter changes
        for event in param_events {
            Self::handle_parameter_change_resources(resources, &event).await;
        }
    }

    /// Handle plugin enable event (ResourceContext version)
    async fn handle_enable_resources(resources: &mut ResourceContext, event: &PluginEnabledEvent) {
        match Self::normalize_plugin_name(&event.plugin_name) {
            "combat" => {
                if let Some(mut config) = resources.get_mut::<crate::plugin::CombatConfig>().await {
                    config.enabled = true;
                    println!("[MOD Bridge] Enabled plugin: combat");
                } else {
                    eprintln!("[MOD Bridge] Combat config not found");
                }
            }
            "inventory" => {
                if let Some(mut config) =
                    resources.get_mut::<crate::plugin::InventoryConfig>().await
                {
                    config.enabled = true;
                    println!("[MOD Bridge] Enabled plugin: inventory");
                } else {
                    eprintln!("[MOD Bridge] Inventory config not found");
                }
            }
            name => {
                eprintln!("[MOD Bridge] Plugin '{}' is not MOD-controllable yet", name);
            }
        }
    }

    /// Handle plugin disable event (ResourceContext version)
    async fn handle_disable_resources(
        resources: &mut ResourceContext,
        event: &PluginDisabledEvent,
    ) {
        match Self::normalize_plugin_name(&event.plugin_name) {
            "combat" => {
                if let Some(mut config) = resources.get_mut::<crate::plugin::CombatConfig>().await {
                    config.enabled = false;
                    println!("[MOD Bridge] Disabled plugin: combat");
                } else {
                    eprintln!("[MOD Bridge] Combat config not found");
                }
            }
            "inventory" => {
                if let Some(mut config) =
                    resources.get_mut::<crate::plugin::InventoryConfig>().await
                {
                    config.enabled = false;
                    println!("[MOD Bridge] Disabled plugin: inventory");
                } else {
                    eprintln!("[MOD Bridge] Inventory config not found");
                }
            }
            name => {
                eprintln!("[MOD Bridge] Plugin '{}' is not MOD-controllable yet", name);
            }
        }
    }

    /// Handle parameter change event (ResourceContext version)
    async fn handle_parameter_change_resources(
        resources: &mut ResourceContext,
        event: &PluginParameterChangedEvent,
    ) {
        match Self::normalize_plugin_name(&event.plugin_name) {
            "combat" => {
                Self::apply_combat_param_resources(resources, &event.key, &event.value).await
            }
            "inventory" => {
                Self::apply_inventory_param_resources(resources, &event.key, &event.value).await
            }
            name => {
                eprintln!("[MOD Bridge] Plugin '{}' is not MOD-controllable yet", name);
            }
        }
    }

    /// Apply parameter to combat config (ResourceContext version)
    async fn apply_combat_param_resources(
        resources: &mut ResourceContext,
        key: &str,
        value: &serde_json::Value,
    ) {
        if let Some(mut config) = resources.get_mut::<crate::plugin::CombatConfig>().await {
            match key {
                "enabled" => {
                    if let Some(enabled) = value.as_bool() {
                        config.enabled = enabled;
                        println!("[MOD Bridge] Combat.enabled = {}", enabled);
                    }
                }
                "max_hp" => {
                    if let Some(hp) = value.as_i64() {
                        config.default_max_hp = hp as u32;
                        println!("[MOD Bridge] Combat.max_hp = {}", hp);
                    }
                }
                "difficulty" => {
                    if let Some(diff) = value.as_f64() {
                        config.difficulty_multiplier = diff as f32;
                        println!("[MOD Bridge] Combat.difficulty = {}", diff);
                    }
                }
                _ => {
                    eprintln!("[MOD Bridge] Unknown combat parameter: {}", key);
                }
            }
        } else {
            eprintln!("[MOD Bridge] Combat config not found");
        }
    }

    /// Apply parameter to inventory config (ResourceContext version)
    async fn apply_inventory_param_resources(
        resources: &mut ResourceContext,
        key: &str,
        value: &serde_json::Value,
    ) {
        if let Some(mut config) = resources.get_mut::<crate::plugin::InventoryConfig>().await {
            match key {
                "enabled" => {
                    if let Some(enabled) = value.as_bool() {
                        config.enabled = enabled;
                        println!("[MOD Bridge] Inventory.enabled = {}", enabled);
                    }
                }
                "max_slots" => {
                    if let Some(slots) = value.as_i64() {
                        config.default_capacity = slots as usize;
                        println!("[MOD Bridge] Inventory.max_slots = {}", slots);
                    }
                }
                "allow_stacking" => {
                    if let Some(allow) = value.as_bool() {
                        config.allow_stacking = allow;
                        println!("[MOD Bridge] Inventory.allow_stacking = {}", allow);
                    }
                }
                _ => {
                    eprintln!("[MOD Bridge] Unknown inventory parameter: {}", key);
                }
            }
        } else {
            eprintln!("[MOD Bridge] Inventory config not found");
        }
    }

    /// Normalize plugin name (handle both "combat" and "issun:combat")
    fn normalize_plugin_name(name: &str) -> &str {
        name.strip_prefix("issun:").unwrap_or(name)
    }
}

impl Default for ModBridgeSystem {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl System for ModBridgeSystem {
    fn name(&self) -> &'static str {
        "mod_bridge_system"
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context::ResourceContext;

    #[test]
    fn test_normalize_plugin_name() {
        assert_eq!(ModBridgeSystem::normalize_plugin_name("combat"), "combat");
        assert_eq!(
            ModBridgeSystem::normalize_plugin_name("issun:combat"),
            "combat"
        );
        assert_eq!(
            ModBridgeSystem::normalize_plugin_name("inventory"),
            "inventory"
        );
        assert_eq!(
            ModBridgeSystem::normalize_plugin_name("issun:inventory"),
            "inventory"
        );
    }

    #[tokio::test]
    async fn test_mod_bridge_system_creation() {
        let system = ModBridgeSystem::new();
        assert_eq!(system.name(), "mod_bridge_system");
    }

    #[tokio::test]
    async fn test_combat_plugin_enable() {
        let mut resources = ResourceContext::new();
        resources.insert(EventBus::new());
        resources.insert(crate::plugin::CombatConfig::default());

        // Publish enable event
        {
            let mut event_bus = resources.get_mut::<EventBus>().await.unwrap();
            event_bus.publish(PluginEnabledEvent {
                plugin_name: "combat".to_string(),
            });
            event_bus.dispatch();
        }

        // Run system
        let mut system = ModBridgeSystem::new();
        system.update_resources(&mut resources).await;

        // Check config was enabled
        let config = resources
            .get::<crate::plugin::CombatConfig>()
            .await
            .unwrap();
        assert!(config.enabled);
    }

    #[tokio::test]
    async fn test_combat_plugin_disable() {
        let mut resources = ResourceContext::new();
        resources.insert(EventBus::new());
        resources.insert(crate::plugin::CombatConfig::default());

        // Publish disable event
        {
            let mut event_bus = resources.get_mut::<EventBus>().await.unwrap();
            event_bus.publish(PluginDisabledEvent {
                plugin_name: "combat".to_string(),
            });
            event_bus.dispatch();
        }

        // Run system
        let mut system = ModBridgeSystem::new();
        system.update_resources(&mut resources).await;

        // Check config was disabled
        let config = resources
            .get::<crate::plugin::CombatConfig>()
            .await
            .unwrap();
        assert!(!config.enabled);
    }

    #[tokio::test]
    async fn test_combat_parameter_change() {
        let mut resources = ResourceContext::new();
        resources.insert(EventBus::new());
        resources.insert(crate::plugin::CombatConfig::default());

        // Publish parameter change event
        {
            let mut event_bus = resources.get_mut::<EventBus>().await.unwrap();
            event_bus.publish(PluginParameterChangedEvent {
                plugin_name: "combat".to_string(),
                key: "max_hp".to_string(),
                value: serde_json::json!(150),
            });
            event_bus.dispatch();
        }

        // Run system
        let mut system = ModBridgeSystem::new();
        system.update_resources(&mut resources).await;

        // Check config was updated
        let config = resources
            .get::<crate::plugin::CombatConfig>()
            .await
            .unwrap();
        assert_eq!(config.default_max_hp, 150);
    }

    #[tokio::test]
    async fn test_combat_difficulty_change() {
        let mut resources = ResourceContext::new();
        resources.insert(EventBus::new());
        resources.insert(crate::plugin::CombatConfig::default());

        // Publish difficulty change event
        {
            let mut event_bus = resources.get_mut::<EventBus>().await.unwrap();
            event_bus.publish(PluginParameterChangedEvent {
                plugin_name: "combat".to_string(),
                key: "difficulty".to_string(),
                value: serde_json::json!(2.5),
            });
            event_bus.dispatch();
        }

        // Run system
        let mut system = ModBridgeSystem::new();
        system.update_resources(&mut resources).await;

        // Check config was updated
        let config = resources
            .get::<crate::plugin::CombatConfig>()
            .await
            .unwrap();
        assert_eq!(config.difficulty_multiplier, 2.5);
    }

    #[tokio::test]
    async fn test_inventory_plugin_enable() {
        let mut resources = ResourceContext::new();
        resources.insert(EventBus::new());
        resources.insert(crate::plugin::InventoryConfig::default());

        // Publish enable event
        {
            let mut event_bus = resources.get_mut::<EventBus>().await.unwrap();
            event_bus.publish(PluginEnabledEvent {
                plugin_name: "inventory".to_string(),
            });
            event_bus.dispatch();
        }

        // Run system
        let mut system = ModBridgeSystem::new();
        system.update_resources(&mut resources).await;

        // Check config was enabled
        let config = resources
            .get::<crate::plugin::InventoryConfig>()
            .await
            .unwrap();
        assert!(config.enabled);
    }

    #[tokio::test]
    async fn test_inventory_parameter_change() {
        let mut resources = ResourceContext::new();
        resources.insert(EventBus::new());
        resources.insert(crate::plugin::InventoryConfig::default());

        // Publish parameter change event
        {
            let mut event_bus = resources.get_mut::<EventBus>().await.unwrap();
            event_bus.publish(PluginParameterChangedEvent {
                plugin_name: "inventory".to_string(),
                key: "max_slots".to_string(),
                value: serde_json::json!(50),
            });
            event_bus.dispatch();
        }

        // Run system
        let mut system = ModBridgeSystem::new();
        system.update_resources(&mut resources).await;

        // Check config was updated
        let config = resources
            .get::<crate::plugin::InventoryConfig>()
            .await
            .unwrap();
        assert_eq!(config.default_capacity, 50);
    }

    #[tokio::test]
    async fn test_namespaced_plugin_name() {
        let mut resources = ResourceContext::new();
        resources.insert(EventBus::new());
        resources.insert(crate::plugin::CombatConfig::default());

        // Use namespaced name "issun:combat"
        {
            let mut event_bus = resources.get_mut::<EventBus>().await.unwrap();
            event_bus.publish(PluginEnabledEvent {
                plugin_name: "issun:combat".to_string(),
            });
            event_bus.dispatch();
        }

        // Run system
        let mut system = ModBridgeSystem::new();
        system.update_resources(&mut resources).await;

        // Check config was enabled
        let config = resources
            .get::<crate::plugin::CombatConfig>()
            .await
            .unwrap();
        assert!(config.enabled);
    }

    #[tokio::test]
    async fn test_multiple_events_in_one_update() {
        let mut resources = ResourceContext::new();
        resources.insert(EventBus::new());
        resources.insert(crate::plugin::CombatConfig::default());
        resources.insert(crate::plugin::InventoryConfig::default());

        // Publish multiple events
        {
            let mut event_bus = resources.get_mut::<EventBus>().await.unwrap();
            event_bus.publish(PluginEnabledEvent {
                plugin_name: "combat".to_string(),
            });
            event_bus.publish(PluginParameterChangedEvent {
                plugin_name: "combat".to_string(),
                key: "max_hp".to_string(),
                value: serde_json::json!(200),
            });
            event_bus.publish(PluginDisabledEvent {
                plugin_name: "inventory".to_string(),
            });
            event_bus.dispatch();
        }

        // Run system once
        let mut system = ModBridgeSystem::new();
        system.update_resources(&mut resources).await;

        // Check all changes were applied
        let combat_config = resources
            .get::<crate::plugin::CombatConfig>()
            .await
            .unwrap();
        assert!(combat_config.enabled);
        assert_eq!(combat_config.default_max_hp, 200);

        let inventory_config = resources
            .get::<crate::plugin::InventoryConfig>()
            .await
            .unwrap();
        assert!(!inventory_config.enabled);
    }
}