tiger_lib/data/
on_actions.rs

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
use std::path::PathBuf;

use crate::block::Block;
use crate::context::ScopeContext;
use crate::effect::validate_effect;
use crate::everything::Everything;
use crate::fileset::{FileEntry, FileHandler};
use crate::game::Game;
use crate::helpers::TigerHashMap;
use crate::item::Item;
use crate::on_action::on_action_scopecontext;
use crate::parse::ParserMemory;
use crate::pdxfile::PdxFile;
#[cfg(feature = "ck3")]
use crate::report::{err, warn, ErrorKey};
use crate::scopes::Scopes;
use crate::token::Token;
use crate::tooltipped::Tooltipped;
use crate::trigger::validate_trigger;
use crate::validate::{validate_duration, validate_modifiers_with_base};
use crate::validator::Validator;

#[derive(Clone, Debug, Default)]
pub struct OnActions {
    on_actions: TigerHashMap<&'static str, OnAction>,
}

impl OnActions {
    fn load_item(&mut self, key: Token, block: Block) {
        if let Some(other) = self.on_actions.get_mut(key.as_str()) {
            other.add(key, block);
        } else {
            self.on_actions.insert(key.as_str(), OnAction::new(key, block));
        }
    }

    pub fn exists(&self, key: &str) -> bool {
        self.on_actions.contains_key(key)
    }

    pub fn iter_keys(&self) -> impl Iterator<Item = &Token> {
        // SAFETY: The item's constructor guarantees at least one element in `actions`.
        self.on_actions.values().map(|item| &item.actions[0].0)
    }

    pub fn validate(&self, data: &Everything) {
        for item in self.on_actions.values() {
            item.validate(data);
        }
    }

    pub fn validate_call(&self, key: &Token, data: &Everything, sc: &mut ScopeContext) {
        if let Some(action) = self.on_actions.get(key.as_str()) {
            action.validate_call(data, sc);
        }
    }
}

impl FileHandler<Block> for OnActions {
    fn subpath(&self) -> PathBuf {
        match Game::game() {
            #[cfg(feature = "ck3")]
            Game::Ck3 => PathBuf::from("common/on_action"),
            #[cfg(feature = "imperator")]
            Game::Imperator => PathBuf::from("common/on_action"),
            #[cfg(feature = "vic3")]
            Game::Vic3 => PathBuf::from("common/on_actions"),
        }
    }

    fn load_file(&self, entry: &FileEntry, parser: &ParserMemory) -> Option<Block> {
        if !entry.filename().to_string_lossy().ends_with(".txt") {
            return None;
        }

        PdxFile::read(entry, parser)
    }

    fn handle_file(&mut self, _entry: &FileEntry, mut block: Block) {
        for (key, block) in block.drain_definitions_warn() {
            self.load_item(key, block);
        }
    }
}

#[derive(Clone, Debug)]
/// Actions override in a special way, which is why this struct contains all actions defined under
/// the same name, rather than each new one replacing the prior one.
pub struct OnAction {
    actions: Vec<(Token, Block)>,
}

impl OnAction {
    pub fn new(key: Token, block: Block) -> Self {
        Self { actions: vec![(key, block)] }
    }

    pub fn add(&mut self, key: Token, block: Block) {
        self.actions.push((key, block));
    }

    pub fn validate(&self, data: &Everything) {
        let mut seen_trigger = false;
        let mut seen_effect = false;
        for (key, block) in self.actions.iter().rev() {
            // Make an sc for each array entry, to make use it uses the local `key`.
            // This is important to distinguish between vanilla errors and mod errors.
            let mut sc = if let Some(builtin_sc) = on_action_scopecontext(key, data) {
                builtin_sc
            } else {
                let mut generated_sc = ScopeContext::new(Scopes::non_primitive(), key);
                generated_sc.set_strict_scopes(false);
                generated_sc
            };
            validate_on_action_internal(block, data, &mut sc, &mut seen_trigger, &mut seen_effect);
        }
    }

    /// Revalidate an `on_action` under the given scope context.
    /// It is not necessary to validate anything non scope related,
    /// but in this case it is easier to just call the full function because
    /// everything in an action is scope related.
    pub fn validate_call(&self, data: &Everything, sc: &mut ScopeContext) {
        let mut seen_trigger = false;
        let mut seen_effect = false;
        for (_, block) in self.actions.iter().rev() {
            validate_on_action_internal(block, data, sc, &mut seen_trigger, &mut seen_effect);
        }
    }
}

fn validate_on_action_internal(
    block: &Block,
    data: &Everything,
    sc: &mut ScopeContext,
    seen_trigger: &mut bool,
    seen_effect: &mut bool,
) {
    let mut vd = Validator::new(block, data);
    vd.field_validated_block("trigger", |block, data| {
        if !*seen_trigger {
            *seen_trigger = true;
            validate_trigger(block, data, sc, Tooltipped::No);
        }
    });
    vd.field_validated_block_sc("weight_multiplier", sc, validate_modifiers_with_base);

    vd.field_validated_block("effect", |block, data| {
        if !*seen_effect {
            *seen_effect = true;
            validate_effect(block, data, sc, Tooltipped::No);
        }
    });

    // TODO: multiple random_events blocks in one on_action aren't outright bugged on Vic3,
    // but they might still get merged together into one big event pool. Verify.

    let mut count = 0;
    #[allow(unused_variables)] // vic3 doesn't use `key`
    vd.multi_field_validated_key_block("events", |key, b, data| {
        let mut vd = Validator::new(b, data);
        vd.multi_field_validated_block_sc("delay", sc, validate_duration);
        for token in vd.values() {
            data.verify_exists(Item::Event, token);
            data.events.check_scope(token, sc);
            if let Some(mut event_sc) = sc.root_for_event(token) {
                data.events.validate_call(token, data, &mut event_sc);
            }
        }
        count += 1;
        #[cfg(feature = "ck3")] // Verified: this is only a problem in CK3
        if Game::is_ck3() && count == 2 {
            // TODO: verify
            let msg = format!("not sure if multiple `{key}` blocks in one on_action work");
            let info = "try combining them into one block";
            warn(ErrorKey::Validation).msg(msg).info(info).loc(key).push();
        }
    });
    count = 0;
    #[allow(unused_variables)] // vic3 doesn't use `key`
    vd.multi_field_validated_key_block("random_events", |key, b, data| {
        let mut vd = Validator::new(b, data);
        vd.field_numeric("chance_to_happen"); // TODO: 0 - 100
        vd.field_script_value("chance_of_no_event", sc);
        vd.multi_field_validated_block_sc("delay", sc, validate_duration); // undocumented
        for (_key, token) in vd.integer_values() {
            if token.is("0") {
                continue;
            }
            data.verify_exists(Item::Event, token);
            data.events.check_scope(token, sc);
            if let Some(mut event_sc) = sc.root_for_event(token) {
                data.events.validate_call(token, data, &mut event_sc);
            }
        }
        count += 1;
        #[cfg(feature = "ck3")] // Verified: this is only a problem in CK3
        if Game::is_ck3() && count == 2 {
            let msg = format!("multiple `{key}` blocks in one on_action do not work");
            let info = "try putting each into its own on_action and firing those separately";
            err(ErrorKey::Validation).msg(msg).info(info).loc(key).push();
        }
    });
    count = 0;
    #[allow(unused_variables)] // vic3 doesn't use `key`
    vd.multi_field_validated_key_block("first_valid", |key, b, data| {
        let mut vd = Validator::new(b, data);
        for token in vd.values() {
            data.verify_exists(Item::Event, token);
            data.events.check_scope(token, sc);
            if let Some(mut event_sc) = sc.root_for_event(token) {
                data.events.validate_call(token, data, &mut event_sc);
            }
        }
        count += 1;
        #[cfg(feature = "ck3")] // Verified: this is only a problem in CK3
        if Game::is_ck3() && count == 2 {
            // TODO: verify
            let msg = format!("not sure if multiple `{key}` blocks in one on_action work");
            let info = "try putting each into its own on_action and firing those separately";
            warn(ErrorKey::Validation).msg(msg).info(info).loc(key).push();
        }
    });
    count = 0;
    #[allow(unused_variables)] // vic3 doesn't use `key`
    vd.multi_field_validated_key_block("on_actions", |key, b, data| {
        let mut vd = Validator::new(b, data);
        vd.multi_field_validated_block_sc("delay", sc, validate_duration);
        for token in vd.values() {
            data.verify_exists(Item::OnAction, token);
            if let Some(mut action_sc) = sc.root_for_action(token) {
                data.on_actions.validate_call(token, data, &mut action_sc);
            }
        }
        count += 1;
        #[cfg(feature = "ck3")] // Verified: this is only a problem in CK3
        if Game::is_ck3() && count == 2 {
            // TODO: verify
            let msg = format!("not sure if multiple `{key}` blocks in one on_action work");
            let info = "try combining them into one block";
            warn(ErrorKey::Validation).msg(msg).info(info).loc(key).push();
        }
    });
    count = 0;
    #[allow(unused_variables)] // vic3 doesn't use `key`
    vd.multi_field_validated_key_block("random_on_action", |key, b, data| {
        let mut vd = Validator::new(b, data);
        vd.field_numeric("chance_to_happen"); // TODO: 0 - 100
        vd.field_script_value("chance_of_no_event", sc);
        for (_key, token) in vd.integer_values() {
            if token.is("0") {
                continue;
            }
            data.verify_exists(Item::OnAction, token);
            if let Some(mut action_sc) = sc.root_for_action(token) {
                data.on_actions.validate_call(token, data, &mut action_sc);
            }
        }
        count += 1;
        #[cfg(feature = "ck3")] // Verified: this is only a problem in CK3
        if Game::is_ck3() && count == 2 {
            // TODO: verify
            let msg = format!("not sure if multiple `{key}` blocks in one on_action work");
            let info = "try putting each into its own on_action and firing those separately";
            warn(ErrorKey::Validation).msg(msg).info(info).loc(key).push();
        }
    });
    count = 0;
    #[allow(unused_variables)] // vic3 doesn't use `key`
    vd.multi_field_validated_key_block("first_valid_on_action", |key, b, data| {
        let mut vd = Validator::new(b, data);
        for token in vd.values() {
            data.verify_exists(Item::OnAction, token);
            if let Some(mut action_sc) = sc.root_for_action(token) {
                data.on_actions.validate_call(token, data, &mut action_sc);
            }
        }
        count += 1;
        #[cfg(feature = "ck3")] // Verified: this is only a problem in CK3
        if Game::is_ck3() && count == 2 {
            // TODO: verify
            let msg = format!("not sure if multiple `{key}` blocks in one on_action work");
            let info = "try putting each into its own on_action and firing those separately";
            warn(ErrorKey::Validation).msg(msg).info(info).loc(key).push();
        }
    });
    // TODO: check for infinite fallback loops?
    vd.field_action("fallback", sc);
}

#[cfg(feature = "vic3")]
pub fn validate_on_action(block: &Block, data: &Everything, sc: &mut ScopeContext) {
    let mut seen_trigger = false;
    let mut seen_effect = false;
    validate_on_action_internal(block, data, sc, &mut seen_trigger, &mut seen_effect);
}