omg_core/generation/attributes/
modify.rs

1use crate::data::map::{get_attribute, get_attribute_mut, Map2d};
2
3/// Modifies one [`Attribute`](crate::data::map::attribute::Attribute) with another transformed one.
4#[derive(new, Debug, PartialEq, Eq, Clone)]
5pub struct ModifyWithAttributeStep {
6    source_id: usize,
7    target_id: usize,
8    percentage: i32,
9    minimum: u8,
10}
11
12impl ModifyWithAttributeStep {
13    pub fn source_id(&self) -> usize {
14        self.source_id
15    }
16
17    pub fn target_id(&self) -> usize {
18        self.target_id
19    }
20
21    pub fn percentage(&self) -> i32 {
22        self.percentage
23    }
24
25    pub fn minimum(&self) -> u8 {
26        self.minimum
27    }
28
29    // Runs the step.
30    pub fn run(&self, map: &mut Map2d) {
31        let factor = self.percentage as f32 / 100.0;
32        info!(
33            "{} attribute '{}' with attribute '{}' of map '{}'",
34            if factor < 0.0 { "Decrease" } else { "Increase" },
35            get_attribute(map, self.target_id).name(),
36            get_attribute(map, self.source_id).name(),
37            map.name()
38        );
39
40        let values = self.calculate_values(map, factor);
41        let attribute = get_attribute_mut(map, self.target_id);
42
43        attribute.replace_all(values);
44    }
45
46    fn calculate_values(&self, map: &mut Map2d, factor: f32) -> Vec<u8> {
47        let length = map.size().get_area();
48        let source_attribute = get_attribute(map, self.source_id);
49        let target_attribute = get_attribute(map, self.target_id);
50        let mut values = Vec::with_capacity(length);
51
52        for index in 0..length {
53            let source = source_attribute[index];
54            let target = target_attribute[index];
55            values.push(self.calculate_value(source, target, factor));
56        }
57
58        values
59    }
60
61    fn calculate_value(&self, source: u8, target: u8, factor: f32) -> u8 {
62        (target as f32 + (source.max(self.minimum) - self.minimum) as f32 * factor) as u8
63    }
64}