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
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use dashmap::DashMap;

use crate::draw::{draw_blocked_rects_mut, draw_resource_rects_mut};
use crate::factorio::util::{add_to_rect, rect_fields};
use crate::factorio::world::FactorioWorld;
use crate::graph::entity_graph::EntityGraph;
use crate::types::{
    Direction, EntityName, FactorioItemPrototype, FactorioRecipe, FactorioTile, Position, Rect,
};
use crate::types::{FactorioEntity, FactorioEntityPrototype};
use image::RgbaImage;
use imageproc::drawing::draw_hollow_rect_mut;
use miette::Result;

pub fn entity_graph_from(entities: Vec<FactorioEntity>) -> Result<EntityGraph> {
    let prototypes = fixture_entity_prototypes();
    let graph = EntityGraph::new(Arc::new(prototypes), Arc::new(DashMap::new()));
    graph.add(entities, None)?;
    graph.connect()?;
    Ok(graph)
}

pub fn fixture_entity_prototypes() -> DashMap<String, FactorioEntityPrototype> {
    let prototypes: DashMap<String, FactorioEntityPrototype> =
        serde_json::from_str(include_str!("../tests/entity-prototype-fixtures.json"))
            .expect("failed to parse fixture");
    prototypes
}

pub fn fixture_item_prototypes() -> DashMap<String, FactorioItemPrototype> {
    let prototypes: HashMap<String, FactorioItemPrototype> =
        serde_json::from_str(include_str!("../tests/item-prototype-fixtures.json"))
            .expect("failed to parse fixture");
    let dashmap: DashMap<String, FactorioItemPrototype> = DashMap::new();
    for prototype in prototypes {
        dashmap.insert(prototype.0, prototype.1);
    }
    dashmap
}
pub fn fixture_recipes() -> DashMap<String, FactorioRecipe> {
    let recipes: HashMap<String, FactorioRecipe> =
        serde_json::from_str(include_str!("../tests/recipes-fixtures.json"))
            .expect("failed to parse fixture");
    let dashmap: DashMap<String, FactorioRecipe> = DashMap::new();
    for prototype in recipes {
        dashmap.insert(prototype.0, prototype.1);
    }
    dashmap
}

pub fn spawn_trees(entities: &mut Vec<FactorioEntity>, count: u32, around: Position) {
    let a_x = around.x() as i32;
    let a_y = around.y() as i32;
    let mut x = 0;
    let mut y = 0;
    let mut t;
    let mut dx = 0;
    let mut dy = -1;
    for _ in 0..count * 100 {
        entities.push(FactorioEntity::new_tree(&Position::new(
            (a_x + x) as f64,
            (a_y + y) as f64,
        )));
        if entities.len() >= count as usize {
            break;
        }
        if (x == y) || ((x < 0) && (x == -y)) || ((x > 0) && (x == 1 - y)) {
            t = dx;
            dx = -dy;
            dy = t;
        }
        x += dx;
        y += dy;
    }
}
pub fn spawn_rocks(entities: &mut Vec<FactorioEntity>, count: u32, around: Position, name: &str) {
    let a_x = around.x() as i32;
    let a_y = around.y() as i32;
    let mut x = 0;
    let mut y = 0;
    let mut t;
    let mut dx = 0;
    let mut dy = -1;
    for _ in 0..count * 100 {
        entities.push(FactorioEntity::new_rock(
            &Position::new((a_x + x) as f64, (a_y + y) as f64),
            name,
        ));
        if entities.len() >= count as usize {
            break;
        }
        if (x == y) || ((x < 0) && (x == -y)) || ((x > 0) && (x == 1 - y)) {
            t = dx;
            dx = -dy;
            dy = t;
        }
        x += dx;
        y += dy;
    }
}

pub fn spawn_ore(entities: &mut Vec<FactorioEntity>, rect: Rect, resource_name: &str) {
    for pos in rect_fields(&rect) {
        entities.push(FactorioEntity::new_resource(
            &pos,
            Direction::North,
            resource_name,
        ));
    }
}

pub fn spawn_water(tiles: &mut Vec<FactorioTile>, rect: Rect) {
    for pos in rect_fields(&rect) {
        tiles.push(FactorioTile {
            position: pos,
            name: EntityName::Water.to_string(),
            player_collidable: true,
            color: None,
        });
    }
}

pub fn fixture_world() -> FactorioWorld {
    let world = FactorioWorld::new();
    let entity_prototypes: Vec<FactorioEntityPrototype> = fixture_entity_prototypes()
        .iter()
        .map(|v| v.clone())
        .collect();
    let item_prototypes: Vec<FactorioItemPrototype> = fixture_item_prototypes()
        .iter()
        .map(|v| v.clone())
        .collect();
    let recipes: Vec<FactorioRecipe> = fixture_recipes().iter().map(|v| v.clone()).collect();
    world.update_entity_prototypes(entity_prototypes).unwrap();
    world.update_item_prototypes(item_prototypes).unwrap();
    world.update_recipes(recipes).unwrap();

    let mut entities: Vec<FactorioEntity> = vec![];
    let mut tiles: Vec<FactorioTile> = vec![];

    spawn_rocks(&mut entities, 3, Position::new(20., 20.), "rock-huge");
    spawn_rocks(&mut entities, 2, Position::new(40., 30.), "rock-big");
    spawn_trees(&mut entities, 100, Position::new(-20., -20.));
    spawn_ore(
        &mut entities,
        add_to_rect(&Rect::from_wh(10., 10.), &Position::new(-40., 40.)),
        &EntityName::IronOre.to_string(),
    );
    spawn_ore(
        &mut entities,
        add_to_rect(&Rect::from_wh(10., 10.), &Position::new(-40., 0.)),
        &EntityName::CopperOre.to_string(),
    );
    spawn_ore(
        &mut entities,
        add_to_rect(&Rect::from_wh(10., 10.), &Position::new(-60., 0.)),
        &EntityName::Coal.to_string(),
    );
    spawn_ore(
        &mut entities,
        add_to_rect(&Rect::from_wh(10., 10.), &Position::new(-80., 0.)),
        &EntityName::Stone.to_string(),
    );

    spawn_water(
        &mut tiles,
        add_to_rect(&Rect::from_wh(4., 4.), &Position::new(40., 40.)),
    );
    world.update_chunk_tiles(tiles).unwrap();
    world.update_chunk_entities(entities).unwrap();
    world
}

pub fn draw_world(world: Arc<FactorioWorld>, cwd: PathBuf, save_path: &str) {
    let image_width = 500.;
    let image_height = 500.;
    let bb_width = 200.;
    let bb_height = 200.;
    let mut buffer: RgbaImage = image::ImageBuffer::new(image_width as u32, image_height as u32);
    for (_x, _y, pixel) in buffer.enumerate_pixels_mut() {
        *pixel = image::Rgba([255, 255, 255, 255u8]); // white
    }
    let bounding_box = Rect::from_wh(bb_width, bb_height);
    let scaling_factor = image_width / bb_width;
    let resource_colors: HashMap<&str, image::Rgba<_>> = [
        ("iron-ore", image::Rgba([0u8, 110u8, 255u8, 255u8])), // blue
        ("copper-ore", image::Rgba([255u8, 55u8, 0u8, 255u8])), // orange
        ("coal", image::Rgba([0u8, 0u8, 0u8, 255u8])),         // black
        ("stone", image::Rgba([150u8, 100u8, 80u8, 255u8])),   // brown
        ("uranium-ore", image::Rgba([100u8, 180u8, 0u8, 255u8])), // fancy green
        ("crude-oil", image::Rgba([255u8, 0u8, 255u8, 255u8])), // magenta
    ]
    .iter()
    .cloned()
    .collect();
    // draw resources
    draw_resource_rects_mut(
        &mut buffer,
        world.entity_graph.resource_tree(),
        &bounding_box,
        scaling_factor,
        resource_colors,
        image::Rgba([255u8, 0u8, 255u8, 255u8]), // magenta
    );
    // draw blocked
    draw_blocked_rects_mut(
        &mut buffer,
        world.entity_graph.blocked_tree(),
        &bounding_box,
        scaling_factor,
        image::Rgba([76u8, 175u8, 80u8, 255u8]),  // green
        image::Rgba([93u8, 247u8, 255u8, 255u8]), // cyan
    );
    // draw thick vertical black line through the center
    draw_hollow_rect_mut(
        &mut buffer,
        imageproc::rect::Rect::at((image_width / 2. - 1.) as i32, 0)
            .of_size(2, image_height as u32),
        image::Rgba([0u8, 0u8, 0u8, 255u8]), // black
    );
    // draw thick horizontal black line through the center
    draw_hollow_rect_mut(
        &mut buffer,
        imageproc::rect::Rect::at(0, (image_height / 2. - 1.) as i32)
            .of_size(image_width as u32, 2),
        image::Rgba([0u8, 0u8, 0u8, 255u8]), // black
    );
    buffer.save(cwd.join(save_path)).unwrap();
}