bevy_mortar_bond 0.4.0

Bevy integration plug-in for mortar language
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
//! Variable state management for Mortar runtime.
//!
//! Mortar 运行时的变量状态管理。

use bevy::prelude::*;
use mortar_compiler::{Constant, Enum, IfCondition, Variable};
use std::collections::HashMap;

/// Runtime value for a Mortar variable.
///
/// Mortar 变量的运行时值。
#[derive(Debug, Clone, PartialEq)]
pub enum MortarVariableValue {
    String(String),
    Number(f64),
    Boolean(bool),
}

impl MortarVariableValue {
    /// Parse a value from JSON.
    ///
    /// 从 JSON 解析值。
    pub fn from_json(value: &serde_json::Value) -> Option<Self> {
        match value {
            serde_json::Value::String(s) => Some(MortarVariableValue::String(s.clone())),
            serde_json::Value::Number(n) => n.as_f64().map(MortarVariableValue::Number),
            serde_json::Value::Bool(b) => Some(MortarVariableValue::Boolean(*b)),
            _ => None,
        }
    }

    /// Convert to display string.
    ///
    /// 转换为显示字符串。
    pub fn to_display_string(&self) -> String {
        match self {
            MortarVariableValue::String(s) => s.clone(),
            MortarVariableValue::Number(n) => n.to_string(),
            MortarVariableValue::Boolean(b) => b.to_string(),
        }
    }
}

/// Branch definition for branch interpolation.
///
/// 用于分支插值的分支定义。
#[derive(Debug, Clone)]
struct BranchDef {
    enum_type: Option<String>,
    cases: Vec<BranchCase>,
}

#[derive(Debug, Clone)]
struct BranchCase {
    condition: String,
    text: String,
}

/// Component that manages variable state for a Mortar dialogue runtime.
///
/// 管理 Mortar 对话运行时变量状态的组件。
#[derive(Component, Debug, Clone)]
pub struct MortarVariableState {
    variables: HashMap<String, MortarVariableValue>,
    branches: HashMap<String, BranchDef>,
}

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

/// Parse a Branch variable definition from its JSON value.
fn parse_branch_variable(var: &Variable) -> Option<(String, BranchDef)> {
    let obj = var.value.as_ref()?.as_object()?;

    let enum_type = obj
        .get("enum_type")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let mut cases = Vec::new();

    if let Some(cases_array) = obj.get("cases").and_then(|v| v.as_array()) {
        for case in cases_array {
            if let Some(case_obj) = case.as_object() {
                let condition = case_obj
                    .get("condition")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();

                let text = case_obj
                    .get("text")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();

                cases.push(BranchCase { condition, text });
            }
        }
    }

    Some((var.name.clone(), BranchDef { enum_type, cases }))
}

/// Resolve default variable value based on type name.
fn default_variable_value(var_type: &str, enums: &[Enum]) -> Option<MortarVariableValue> {
    match var_type {
        "String" => Some(MortarVariableValue::String(String::new())),
        "Number" => Some(MortarVariableValue::Number(0.0)),
        "Boolean" | "Bool" => Some(MortarVariableValue::Boolean(false)),
        enum_type_name => {
            let enum_def = enums.iter().find(|e| e.name == enum_type_name)?;
            let first_member = enum_def.variants.first()?;
            Some(MortarVariableValue::String(format!(
                "{}.{}",
                enum_def.name, first_member
            )))
        }
    }
}

/// Find the matching case from a JSON cases array based on enum or boolean conditions.
fn find_matching_case<'a>(
    state: &MortarVariableState,
    enum_type: Option<&str>,
    cases: &'a [serde_json::Value],
) -> Option<&'a serde_json::Value> {
    if let Some(enum_var_name) = enum_type {
        let enum_value = state.get(enum_var_name)?;
        let enum_member = enum_value.to_display_string();
        let member_name = enum_member
            .rfind('.')
            .map_or(&*enum_member, |pos| &enum_member[pos + 1..]);
        cases.iter().find(|case| {
            case.get("condition")
                .and_then(|c| c.as_str())
                .map(|c| c == member_name)
                .unwrap_or(false)
        })
    } else {
        cases.iter().find(|case| {
            case.get("condition")
                .and_then(|c| c.as_str())
                .and_then(|cond_name| state.get(cond_name))
                .map(|v| matches!(v, MortarVariableValue::Boolean(true)))
                .unwrap_or(false)
        })
    }
}

/// Resolve branch text by evaluating enum or boolean conditions.
fn resolve_branch_text(state: &MortarVariableState, branch: &BranchDef) -> Option<String> {
    let Some(enum_var_name) = &branch.enum_type else {
        // Boolean-based branch: check each condition.
        for case in &branch.cases {
            if let Some(MortarVariableValue::Boolean(true)) = state.get(&case.condition) {
                return Some(case.text.clone());
            }
        }
        return None;
    };

    // Get the enum variable value (stored as "EnumName.member").
    let enum_value = state.get(enum_var_name)?;
    let enum_member = enum_value.to_display_string();
    // Extract the member name after the dot.
    let member_name = enum_member
        .rfind('.')
        .map_or(&*enum_member, |pos| &enum_member[pos + 1..]);

    // Find the case that matches the enum member.
    branch
        .cases
        .iter()
        .find(|case| case.condition == member_name)
        .map(|case| case.text.clone())
}

impl MortarVariableState {
    /// Create a new empty variable state.
    ///
    /// 创建一个新的空变量状态。
    pub fn new() -> Self {
        Self {
            variables: HashMap::new(),
            branches: HashMap::new(),
        }
    }

    /// Initialize from a list of variable declarations and constants.
    ///
    /// 从变量声明列表和常量初始化。
    pub fn from_variables(variables: &[Variable], constants: &[Constant], enums: &[Enum]) -> Self {
        let mut state = Self::new();

        // Initialize constants first
        for constant in constants {
            if let Some(parsed_value) = MortarVariableValue::from_json(&constant.value) {
                state.set(&constant.name, parsed_value);
            } else {
                // Fallback for constants if json parsing fails, though unlikely for compiled output
                warn!("Failed to parse value for constant: {}", constant.name);
            }
        }

        for var in variables {
            // Handle Branch type specially.
            if var.var_type == "Branch" {
                state.branches.extend(parse_branch_variable(var));
                continue;
            }

            // Try to parse the value.
            if let Some(parsed) = var.value.as_ref().and_then(MortarVariableValue::from_json) {
                state.set(&var.name, parsed);
                continue;
            }

            // Value exists but couldn't be parsed, skip.
            if var.value.is_some() {
                continue;
            }

            // Set default value based on type.
            let Some(default_value) = default_variable_value(&var.var_type, enums) else {
                continue;
            };
            state.set(&var.name, default_value);
        }

        state
    }

    /// Set a variable value.
    ///
    /// 设置变量值。
    pub fn set(&mut self, name: &str, value: MortarVariableValue) {
        self.variables.insert(name.to_string(), value);
    }

    /// Get a variable value.
    ///
    /// 获取变量值。
    pub fn get(&self, name: &str) -> Option<&MortarVariableValue> {
        self.variables.get(name)
    }

    /// Execute an assignment statement.
    ///
    /// 执行赋值语句。
    pub fn execute_assignment(&mut self, var_name: &str, value_str: &str) {
        // Parse the value string.
        //
        // 解析值字符串。
        if value_str.contains('.') {
            // Enum member: "EnumName.member".
            //
            // 枚举成员格式:"EnumName.member"。
            self.set(var_name, MortarVariableValue::String(value_str.to_string()));
        } else if value_str == "true" {
            self.set(var_name, MortarVariableValue::Boolean(true));
        } else if value_str == "false" {
            self.set(var_name, MortarVariableValue::Boolean(false));
        } else if let Ok(num) = value_str.parse::<f64>() {
            self.set(var_name, MortarVariableValue::Number(num));
        } else {
            // String or identifier.
            //
            // 字符串或标识符。
            self.set(var_name, MortarVariableValue::String(value_str.to_string()));
        }
    }

    /// Set a branch variable's text directly (for testing).
    ///
    /// 直接设置分支变量的文本(用于测试)。
    pub fn set_branch_text(&mut self, name: String, text: String) {
        let branch_def = BranchDef {
            enum_type: None,
            cases: vec![BranchCase {
                condition: "default".to_string(),
                text: text.clone(),
            }],
        };
        self.branches.insert(name.clone(), branch_def);
        // Also set a variable to make the condition true.
        //
        // 同时设置变量以确保条件为真。
        self.set("default", MortarVariableValue::Boolean(true));
    }

    /// Get a branch variable's events by evaluating its conditions.
    ///
    /// 通过评估条件获取分支变量的事件。
    pub fn get_branch_events(
        &self,
        name: &str,
        variables: &[Variable],
    ) -> Option<Vec<mortar_compiler::Event>> {
        // Find the branch variable definition.
        //
        // 查找分支变量的定义。
        let branch_var = variables
            .iter()
            .find(|v| v.name == name && v.var_type == "Branch")?;

        // Parse the branch definition.
        //
        // 解析分支定义。
        let value = branch_var.value.as_ref()?;
        let cases = value.get("cases")?.as_array()?;

        // Get enum type if exists.
        //
        // 获取枚举类型(若存在)。
        let enum_type = value.get("enum_type").and_then(|v| v.as_str());

        // Determine which case matches.
        let matching_case = find_matching_case(self, enum_type, cases)?;

        // Extract events from the matching case.
        //
        // 从匹配的分支中提取事件。
        let events_array = matching_case.get("events")?.as_array()?;
        let mut result = Vec::new();

        for event_json in events_array {
            if let Ok(event) = serde_json::from_value::<mortar_compiler::Event>(event_json.clone())
            {
                result.push(event);
            }
        }

        if result.is_empty() {
            None
        } else {
            Some(result)
        }
    }

    /// Get a branch variable's text by evaluating its conditions.
    ///
    /// 通过评估条件获取分支变量的文本。
    pub fn get_branch_text(&self, name: &str) -> Option<String> {
        let branch = self.branches.get(name)?;
        resolve_branch_text(self, branch)
    }

    /// Evaluate a condition.
    ///
    /// 评估条件。
    pub fn evaluate_condition(&self, condition: &IfCondition) -> bool {
        match condition.cond_type.as_str() {
            "binary" => self.evaluate_binary_condition(condition),
            "unary" => self.evaluate_unary_condition(condition),
            "identifier" => self.evaluate_identifier_condition(condition),
            "literal" => self.evaluate_literal_condition(condition),
            "func_call" => self.evaluate_func_call_condition(condition),
            _ => {
                warn!("Unknown condition type: {}", condition.cond_type);
                false
            }
        }
    }

    fn evaluate_binary_condition(&self, condition: &IfCondition) -> bool {
        let left = condition.left.as_ref().unwrap();
        let right = condition.right.as_ref().unwrap();
        let operator = condition.operator.as_ref().unwrap();

        match operator.as_str() {
            "&&" | "||" => {
                // For logical operators, recursively evaluate both sides as boolean.
                //
                // 对逻辑运算符递归地计算两侧布尔值。
                let left_value = self.evaluate_condition(left);
                let right_value = self.evaluate_condition(right);
                match operator.as_str() {
                    "&&" => left_value && right_value,
                    "||" => left_value || right_value,
                    _ => unreachable!(),
                }
            }
            ">" => self.compare_values(left, right, |a, b| a > b),
            "<" => self.compare_values(left, right, |a, b| a < b),
            ">=" => self.compare_values(left, right, |a, b| a >= b),
            "<=" => self.compare_values(left, right, |a, b| a <= b),
            "==" => self.compare_values_eq(left, right, true),
            "!=" => self.compare_values_eq(left, right, false),
            _ => {
                warn!("Unknown binary operator: {}", operator);
                false
            }
        }
    }

    fn evaluate_unary_condition(&self, condition: &IfCondition) -> bool {
        let operand = condition.operand.as_ref().unwrap();
        let operator = condition.operator.as_ref().unwrap();

        match operator.as_str() {
            "!" => !self.evaluate_condition(operand),
            _ => {
                warn!("Unknown unary operator: {}", operator);
                false
            }
        }
    }

    fn evaluate_identifier_condition(&self, condition: &IfCondition) -> bool {
        let identifier = condition.value.as_ref().unwrap();
        match self.get(identifier) {
            Some(MortarVariableValue::Boolean(b)) => *b,
            Some(_) => {
                warn!(
                    "Variable '{}' is not a boolean, cannot evaluate as condition",
                    identifier
                );
                false
            }
            None => {
                warn!("Variable '{}' not found", identifier);
                false
            }
        }
    }

    fn evaluate_literal_condition(&self, condition: &IfCondition) -> bool {
        let value = condition.value.as_ref().unwrap();
        match value.as_str() {
            "true" => true,
            "false" => false,
            _ => {
                warn!("Unknown literal value: {}", value);
                false
            }
        }
    }

    fn evaluate_func_call_condition(&self, _condition: &IfCondition) -> bool {
        // Function calls in conditions require access to MortarFunctionRegistry,
        // which is not available in MortarVariableState.
        // This should be handled at a higher level where both variable_state and functions are available.
        // For now, we return false and log an info message.
        //
        // 条件中的函数调用需要访问 MortarFunctionRegistry,
        // 而 MortarVariableState 无法获取。
        // 这部分应由同时拥有 variable_state 与函数注册表的上层逻辑处理。
        // 当前返回 false 并输出提示日志。
        dev_info!("Function call in condition requires runtime function evaluation");
        false
    }

    fn compare_values<F>(&self, left: &IfCondition, right: &IfCondition, cmp: F) -> bool
    where
        F: Fn(f64, f64) -> bool,
    {
        let left_num = self.get_numeric_value(left);
        let right_num = self.get_numeric_value(right);

        match (left_num, right_num) {
            (Some(l), Some(r)) => cmp(l, r),
            _ => {
                warn!("Cannot compare non-numeric values");
                false
            }
        }
    }

    fn compare_values_eq(
        &self,
        left: &IfCondition,
        right: &IfCondition,
        expect_equal: bool,
    ) -> bool {
        // Try numeric comparison first.
        //
        // 优先进行数值比较。
        let left_num = self.get_numeric_value(left);
        let right_num = self.get_numeric_value(right);

        if let (Some(l), Some(r)) = (left_num, right_num) {
            let is_equal = (l - r).abs() < f64::EPSILON;
            return if expect_equal { is_equal } else { !is_equal };
        }

        // Try string comparison (for enum members).
        //
        // 尝试执行字符串比较(适用于枚举成员)。
        let left_str = self.get_string_value(left);
        let right_str = self.get_string_value(right);

        if let (Some(l), Some(r)) = (left_str, right_str) {
            let is_equal = l == r;
            return if expect_equal { is_equal } else { !is_equal };
        }

        false
    }

    fn get_string_value(&self, condition: &IfCondition) -> Option<String> {
        match condition.cond_type.as_str() {
            "identifier" => {
                let identifier = condition.value.as_ref()?;
                self.get(identifier).map(|val| val.to_display_string())
            }
            "enum_member" => condition.value.clone(),
            "literal" => condition.value.clone(),
            _ => None,
        }
    }

    fn get_numeric_value(&self, condition: &IfCondition) -> Option<f64> {
        match condition.cond_type.as_str() {
            "identifier" => {
                let identifier = condition.value.as_ref()?;
                // First try to parse as a number literal (workaround for serializer issue).
                //
                // 优先尝试解析为数值字面量(序列化器兼容处理)。
                if let Ok(num) = identifier.parse::<f64>() {
                    return Some(num);
                }
                // Otherwise treat as a variable name.
                //
                // 否则视作变量名处理。
                match self.get(identifier) {
                    Some(MortarVariableValue::Number(n)) => Some(*n),
                    _ => None,
                }
            }
            "literal" => {
                let value = condition.value.as_ref()?;
                value.parse::<f64>().ok()
            }
            _ => None,
        }
    }
}

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

    #[test]
    fn test_variable_state_basic() {
        let mut state = MortarVariableState::new();
        state.set("score", MortarVariableValue::Number(100.0));
        state.set("name", MortarVariableValue::String("Player".to_string()));
        state.set("is_active", MortarVariableValue::Boolean(true));

        assert_eq!(
            state.get("score"),
            Some(&MortarVariableValue::Number(100.0))
        );
        assert_eq!(
            state.get("name"),
            Some(&MortarVariableValue::String("Player".to_string()))
        );
        assert_eq!(
            state.get("is_active"),
            Some(&MortarVariableValue::Boolean(true))
        );
    }

    #[test]
    fn test_evaluate_simple_condition() {
        let mut state = MortarVariableState::new();
        state.set("is_winner", MortarVariableValue::Boolean(true));

        // Test identifier condition.
        //
        // 测试标识符条件。
        let condition = IfCondition {
            cond_type: "identifier".to_string(),
            operator: None,
            left: None,
            right: None,
            operand: None,
            value: Some("is_winner".to_string()),
        };

        assert!(state.evaluate_condition(&condition));
    }

    #[test]
    fn test_evaluate_comparison() {
        let mut state = MortarVariableState::new();
        state.set("score", MortarVariableValue::Number(150.0));

        // Create condition: score > 100.
        //
        // 创建条件:score > 100。
        let condition = IfCondition {
            cond_type: "binary".to_string(),
            operator: Some(">".to_string()),
            left: Some(Box::new(IfCondition {
                cond_type: "identifier".to_string(),
                operator: None,
                left: None,
                right: None,
                operand: None,
                value: Some("score".to_string()),
            })),
            right: Some(Box::new(IfCondition {
                cond_type: "literal".to_string(),
                operator: None,
                left: None,
                right: None,
                operand: None,
                value: Some("100".to_string()),
            })),
            operand: None,
            value: None,
        };

        assert!(state.evaluate_condition(&condition));
    }
}