souprune 0.5.1

A game framework designed specifically for Deltarune / Undertale fangames.
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
//! # state.rs
//!
//! # state.rs 文件
//!
//! ## Module Overview
//!
//! ## 模块概述
//!
//! This module handles UI layer transitions and navigation between menu items.
//!
//! 本模块处理 UI 层级转换和菜单项之间的导航。
//!
//! ## Source File Overview
//!
//! ## 源文件概述
//!
//! It manages state changes triggered by user input such as confirm and cancel actions.
//!
//! 管理由用户输入触发的状态变化,例如确认和取消操作。

use super::components::{
    RonUI, TransitionAction, UILayer, UILayerNavigationConfig, UILayerTransitionConfig,
};
use super::ron_ui::UIGlobalTriggerConfig;
use crate::app_state::overworld::{OverworldState, character};
use crate::core::audio;
use crate::core::input::Action;
use bevy::prelude::*;
use leafwing_input_manager::action_state::ActionState;

/// Handle transitions between overworld sub-states driven by menu actions.
///
/// 处理菜单输入驱动的 Overworld 子状态间转换。
#[cfg(all(feature = "bevy_kira_audio", not(feature = "firewheel")))]
pub(crate) fn menu_overworld_state_transitions_system(
    audio: Res<bevy_kira_audio::Audio>,
    asset_server: Res<AssetServer>,
    mut next_state: ResMut<NextState<OverworldState>>,
    current_state: Res<State<OverworldState>>,
    mut overworld_ui_query: Query<&mut RonUI>,
    query: Query<&ActionState<Action>, With<character::components::PlayerControlled>>,
    player_data: Res<crate::core::data::PlayerData>,
    transition_config: Res<UILayerTransitionConfig>,
    navigation_config: Res<UILayerNavigationConfig>,
    global_trigger_config: Res<UIGlobalTriggerConfig>,
) {
    if let Ok(action_state) = query.single() {
        // Check global triggers first
        //
        // 首先检查全局触发器
        for (action, rules) in &global_trigger_config.triggers {
            if action_state.just_pressed(action) {
                debug!(
                    "Action pressed: {:?}, current state: {:?}, rules count: {}",
                    action,
                    current_state.get(),
                    rules.len()
                );
                for rule in rules {
                    debug!(
                        "Checking rule: target={:?}, allowed={:?}",
                        rule.target_state, rule.allowed_states
                    );
                    if rule.allowed_states.contains(current_state.get()) {
                        info!(
                            "Global trigger activated: {:?} -> {:?} via {:?}",
                            current_state.get(),
                            rule.target_state,
                            action
                        );

                        if let Some(sound_path) = &rule.sound {
                            audio::play_sound(&audio, &asset_server, sound_path);
                        }

                        next_state.set(rule.target_state);
                        return;
                    }
                }
            }
        }

        match current_state.get() {
            OverworldState::Normal => {
                // Logic moved to global triggers
            }
            OverworldState::Backpack => {
                let Ok(mut overworld_ui) = overworld_ui_query.single_mut() else {
                    warn!("Backpack menu open but no RonUI entity found");
                    return;
                };

                let current_layer = overworld_ui.layer().clone();

                if let Some(transitions) = transition_config.get(&current_layer) {
                    if action_state.just_pressed(&Action::Confirm) {
                        for rule in &transitions.on_confirm {
                            if let Some(condition) = &rule.condition
                                && !evaluate_transition_condition(
                                    condition,
                                    overworld_ui.index(),
                                    &player_data,
                                )
                            {
                                continue;
                            }

                            // Play confirm sound if configured
                            //
                            // 如果已配置,播放确认声音
                            if let Some(sound_path) = &transitions.sound_on_confirm {
                                audio::play_sound(&audio, &asset_server, sound_path);
                            }

                            execute_transition_action(
                                &rule.action,
                                &mut overworld_ui,
                                &mut next_state,
                                &player_data,
                                &navigation_config,
                            );
                            return;
                        }
                    }

                    if action_state.just_pressed(&Action::Cancel)
                        && let Some(cancel_action) = &transitions.on_cancel
                    {
                        // Play cancel sound if configured
                        //
                        // 如果已配置,播放取消声音
                        if let Some(sound_path) = &transitions.sound_on_cancel {
                            audio::play_sound(&audio, &asset_server, sound_path);
                        }

                        execute_transition_action(
                            cancel_action,
                            &mut overworld_ui,
                            &mut next_state,
                            &player_data,
                            &navigation_config,
                        );
                    }
                }
            }
            OverworldState::Cutscene => {
                info!("Menu key pressed during cutscene, ignoring");
            }
            OverworldState::Chase => {
                // Chase state - menu input is disabled during chase
                // 追逐战状态 - 追逐战期间禁用菜单输入
            }
        }
    }
}

fn evaluate_transition_condition(
    condition: &str,
    index: usize,
    player_data: &crate::core::data::PlayerData,
) -> bool {
    let condition = condition.trim();

    if condition.starts_with("index == ")
        && let Some(num_str) = condition.strip_prefix("index == ")
    {
        let parts: Vec<&str> = num_str.split("&&").map(|s| s.trim()).collect();
        let index_part = parts[0];
        if let Ok(target_index) = index_part.parse::<usize>() {
            if index != target_index {
                return false;
            }
            for part in parts.iter().skip(1) {
                if *part == "!player.inventory.is_empty" && player_data.inventory.is_empty() {
                    return false;
                }
            }
            return true;
        }
    }

    true
}

fn execute_transition_action(
    action: &TransitionAction,
    overworld_ui: &mut RonUI,
    next_state: &mut ResMut<NextState<OverworldState>>,
    player_data: &crate::core::data::PlayerData,
    navigation_config: &UILayerNavigationConfig,
) {
    match action {
        TransitionAction::GotoLayer(target_layer) => {
            let max_index = navigation_config
                .get(target_layer)
                .and_then(|rule| {
                    rule.max_index()
                        .as_ref()
                        .map(|bound| super::ron_ui::evaluate_index_bound(bound, player_data))
                })
                .unwrap_or_else(|| calculate_max_index_for_layer(target_layer, player_data));
            info!(
                "Transitioning to layer {} with max_index {}",
                target_layer, max_index
            );
            overworld_ui.set_layer(target_layer.clone(), max_index);
        }
        TransitionAction::PopState => {
            info!("Popping state, returning to Normal");
            next_state.set(OverworldState::Normal);
        }
        TransitionAction::PushState(state_name) => {
            info!("TODO: Push state {}", state_name);
        }
    }
}

fn calculate_max_index_for_layer(
    layer: &UILayer,
    _player_data: &crate::core::data::PlayerData,
) -> usize {
    warn!(
        "Max index for layer {:?} not found in RON configuration! Defaulting to 1.",
        layer
    );
    1
}

/// Update UI focus navigation while the overworld backpack is active.
///
/// 在背包界面激活时更新 UI 焦点导航。
#[cfg(all(feature = "bevy_kira_audio", not(feature = "firewheel")))]
pub(crate) fn update_overworld_ui_navigation_system(
    audio: Res<bevy_kira_audio::Audio>,
    asset_server: Res<AssetServer>,
    overworld_state: Res<State<OverworldState>>,
    navigation: Res<UILayerNavigationConfig>,
    mut ui_query: Query<&mut RonUI>,
    query: Query<&ActionState<Action>, With<character::components::PlayerControlled>>,
    player_data: Res<crate::core::data::PlayerData>,
) {
    if overworld_state.get() != &OverworldState::Backpack {
        return;
    }

    let Ok(action_state) = query.single() else {
        return;
    };

    for mut overworld_ui in ui_query.iter_mut() {
        let Some(rule) = navigation.get(overworld_ui.layer()) else {
            continue;
        };

        let mut delta: isize = 0;
        for action in [Action::Up, Action::Down, Action::Left, Action::Right] {
            if action_state.just_pressed(&action)
                && let Some(change) = rule.delta_for(action)
            {
                delta += change;
            }
        }

        if delta != 0 {
            let min_index = rule
                .min_index()
                .as_ref()
                .map(|bound| super::ron_ui::evaluate_index_bound(bound, &player_data))
                .unwrap_or(0);

            let max_index = rule
                .max_index()
                .as_ref()
                .map(|bound| super::ron_ui::evaluate_index_bound(bound, &player_data))
                .unwrap_or_else(|| {
                    calculate_max_index_for_layer(overworld_ui.layer(), &player_data)
                });

            let mut next_index = overworld_ui.index() as isize + delta;

            if rule.looping() {
                // With looping enabled, wrap around
                //
                // 启用循环时,进行环绕
                if next_index < min_index as isize {
                    next_index = max_index as isize - 1;
                } else if next_index >= max_index as isize {
                    next_index = min_index as isize;
                }
            } else {
                // Without looping, clamp to bounds
                //
                // 未启用循环时,限制在边界内
                next_index = next_index.clamp(min_index as isize, (max_index - 1) as isize);
            }

            // Only update and play sound if index actually changed
            //
            // 仅当索引实际改变时更新并播放声音
            if overworld_ui.index() != next_index as usize {
                // Play navigation sound if configured
                //
                // 如果已配置,播放导航声音
                if let Some(sound_path) = rule.sound_on_navigate() {
                    audio::play_sound(&audio, &asset_server, sound_path);
                }

                overworld_ui.set_index(next_index as usize);
            }
        }
    }
}

// ============================================================================
// Experimental Seedling Audio Backend Systems
// ============================================================================

#[cfg(feature = "firewheel")]
pub(crate) fn menu_overworld_state_transitions_system(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    mut next_state: ResMut<NextState<OverworldState>>,
    current_state: Res<State<OverworldState>>,
    mut overworld_ui_query: Query<&mut RonUI>,
    query: Query<&ActionState<Action>, With<character::components::PlayerControlled>>,
    player_data: Res<crate::core::data::PlayerData>,
    transition_config: Res<UILayerTransitionConfig>,
    navigation_config: Res<UILayerNavigationConfig>,
    global_trigger_config: Res<UIGlobalTriggerConfig>,
) {
    if let Ok(action_state) = query.single() {
        // Check global triggers first
        for (action, rules) in &global_trigger_config.triggers {
            if action_state.just_pressed(action) {
                debug!(
                    "Action pressed: {:?}, current state: {:?}, rules count: {}",
                    action,
                    current_state.get(),
                    rules.len()
                );
                for rule in rules {
                    debug!(
                        "Checking rule: target={:?}, allowed={:?}",
                        rule.target_state, rule.allowed_states
                    );
                    if rule.allowed_states.contains(current_state.get()) {
                        info!(
                            "Global trigger activated: {:?} -> {:?} via {:?}",
                            current_state.get(),
                            rule.target_state,
                            action
                        );

                        if let Some(sound_path) = &rule.sound {
                            audio::play_sound(&mut commands, &asset_server, sound_path);
                        }

                        next_state.set(rule.target_state);
                        return;
                    }
                }
            }
        }

        match current_state.get() {
            OverworldState::Normal => {
                // Logic moved to global triggers
            }
            OverworldState::Backpack => {
                let Ok(mut overworld_ui) = overworld_ui_query.single_mut() else {
                    warn!("Backpack menu open but no RonUI entity found");
                    return;
                };

                let current_layer = overworld_ui.layer().clone();

                if let Some(transitions) = transition_config.get(&current_layer) {
                    if action_state.just_pressed(&Action::Confirm) {
                        for rule in &transitions.on_confirm {
                            if let Some(condition) = &rule.condition
                                && !evaluate_transition_condition(
                                    condition,
                                    overworld_ui.index(),
                                    &player_data,
                                )
                            {
                                continue;
                            }

                            if let Some(sound_path) = &transitions.sound_on_confirm {
                                audio::play_sound(&mut commands, &asset_server, sound_path);
                            }

                            execute_transition_action(
                                &rule.action,
                                &mut overworld_ui,
                                &mut next_state,
                                &player_data,
                                &navigation_config,
                            );
                            return;
                        }
                    }

                    if action_state.just_pressed(&Action::Cancel)
                        && let Some(cancel_action) = &transitions.on_cancel
                    {
                        if let Some(sound_path) = &transitions.sound_on_cancel {
                            audio::play_sound(&mut commands, &asset_server, sound_path);
                        }

                        execute_transition_action(
                            cancel_action,
                            &mut overworld_ui,
                            &mut next_state,
                            &player_data,
                            &navigation_config,
                        );
                    }
                }
            }
            OverworldState::Cutscene => {
                info!("Menu key pressed during cutscene, ignoring");
            }
        }
    }
}

#[cfg(feature = "firewheel")]
pub(crate) fn update_overworld_ui_navigation_system(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    overworld_state: Res<State<OverworldState>>,
    navigation: Res<UILayerNavigationConfig>,
    mut ui_query: Query<&mut RonUI>,
    query: Query<&ActionState<Action>, With<character::components::PlayerControlled>>,
    player_data: Res<crate::core::data::PlayerData>,
) {
    if overworld_state.get() != &OverworldState::Backpack {
        return;
    }

    let Ok(action_state) = query.single() else {
        return;
    };

    for mut overworld_ui in ui_query.iter_mut() {
        let Some(rule) = navigation.get(overworld_ui.layer()) else {
            continue;
        };

        let mut delta: isize = 0;
        for action in [Action::Up, Action::Down, Action::Left, Action::Right] {
            if action_state.just_pressed(&action)
                && let Some(change) = rule.delta_for(action)
            {
                delta += change;
            }
        }

        if delta != 0 {
            let min_index = rule
                .min_index()
                .as_ref()
                .map(|bound| super::ron_ui::evaluate_index_bound(bound, &player_data))
                .unwrap_or(0);

            let max_index = rule
                .max_index()
                .as_ref()
                .map(|bound| super::ron_ui::evaluate_index_bound(bound, &player_data))
                .unwrap_or_else(|| {
                    calculate_max_index_for_layer(overworld_ui.layer(), &player_data)
                });

            let mut next_index = overworld_ui.index() as isize + delta;

            if rule.looping() {
                if next_index < min_index as isize {
                    next_index = max_index as isize - 1;
                } else if next_index >= max_index as isize {
                    next_index = min_index as isize;
                }
            } else {
                next_index = next_index.clamp(min_index as isize, (max_index - 1) as isize);
            }

            if overworld_ui.index() != next_index as usize {
                if let Some(sound_path) = rule.sound_on_navigate() {
                    audio::play_sound(&mut commands, &asset_server, sound_path);
                }

                overworld_ui.set_index(next_index as usize);
            }
        }
    }
}