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
use crate::hud::CraftingTab;
use common::{
    terrain::{sprite, Block, BlockKind, SpriteKind},
    vol::ReadVol,
};
use common_base::span;
use rand::prelude::*;
use rand_chacha::ChaCha8Rng;
use vek::*;

#[derive(Clone, Copy, Debug)]
pub enum Interaction {
    /// This covers mining, unlocking, and regular collectable things (e.g.
    /// twigs).
    Collect,
    Craft(CraftingTab),
    Mount,
    Read,
    LightToggle(bool),
}

pub enum FireplaceType {
    House,
    Workshop, // this also includes witch hut
}

pub struct SmokerProperties {
    pub position: Vec3<i32>,
    pub kind: FireplaceType,
}

impl SmokerProperties {
    fn new(position: Vec3<i32>, kind: FireplaceType) -> Self { Self { position, kind } }
}

#[derive(Default)]
pub struct BlocksOfInterest {
    pub leaves: Vec<Vec3<i32>>,
    pub drip: Vec<Vec3<i32>>,
    pub grass: Vec<Vec3<i32>>,
    pub slow_river: Vec<Vec3<i32>>,
    pub fast_river: Vec<Vec3<i32>>,
    pub waterfall: Vec<(Vec3<i32>, Vec3<f32>)>,
    pub lavapool: Vec<Vec3<i32>>,
    pub fires: Vec<Vec3<i32>>,
    pub smokers: Vec<SmokerProperties>,
    pub beehives: Vec<Vec3<i32>>,
    pub reeds: Vec<Vec3<i32>>,
    pub fireflies: Vec<Vec3<i32>>,
    pub flowers: Vec<Vec3<i32>>,
    pub fire_bowls: Vec<Vec3<i32>>,
    pub snow: Vec<Vec3<i32>>,
    pub spores: Vec<Vec3<i32>>,
    //This is so crickets stay in place and don't randomly change sounds
    pub cricket1: Vec<Vec3<i32>>,
    pub cricket2: Vec<Vec3<i32>>,
    pub cricket3: Vec<Vec3<i32>>,
    pub frogs: Vec<Vec3<i32>>,
    pub one_way_walls: Vec<(Vec3<i32>, Vec3<f32>)>,
    // Note: these are only needed for chunks within the iteraction range so this is a potential
    // area for optimization
    pub interactables: Vec<(Vec3<i32>, Interaction)>,
    pub lights: Vec<(Vec3<i32>, u8)>,
    // needed for biome specific smoke variations
    pub temperature: f32,
    pub humidity: f32,
}

impl BlocksOfInterest {
    pub fn from_blocks(
        blocks: impl Iterator<Item = (Vec3<i32>, Block)>,
        river_velocity: Vec3<f32>,
        temperature: f32,
        humidity: f32,
        chunk: &impl ReadVol<Vox = Block>,
    ) -> Self {
        span!(_guard, "from_chunk", "BlocksOfInterest::from_chunk");
        let mut leaves = Vec::new();
        let mut drip = Vec::new();
        let mut grass = Vec::new();
        let mut slow_river = Vec::new();
        let mut fast_river = Vec::new();
        let mut waterfall = Vec::new();
        let mut lavapool = Vec::new();
        let mut fires = Vec::new();
        let mut smokers = Vec::new();
        let mut beehives = Vec::new();
        let mut reeds = Vec::new();
        let mut fireflies = Vec::new();
        let mut flowers = Vec::new();
        let mut interactables = Vec::new();
        let mut lights = Vec::new();
        // Lights that can be omitted at random if we have too many and need to cull
        // some of them
        let mut minor_lights = Vec::new();
        let mut fire_bowls = Vec::new();
        let mut snow = Vec::new();
        let mut cricket1 = Vec::new();
        let mut cricket2 = Vec::new();
        let mut cricket3 = Vec::new();
        let mut frogs = Vec::new();
        let mut one_way_walls = Vec::new();
        let mut spores = Vec::new();

        let mut rng = ChaCha8Rng::from_seed(thread_rng().gen());

        blocks.for_each(|(pos, block)| {
            match block.kind() {
                BlockKind::Leaves
                    if rng.gen_range(0..16) == 0
                        && chunk
                            .get(pos - Vec3::unit_z())
                            .map_or(true, |b| !b.is_filled()) =>
                {
                    leaves.push(pos)
                },
                BlockKind::WeakRock if rng.gen_range(0..6) == 0 => drip.push(pos),
                BlockKind::Grass => {
                    if rng.gen_range(0..16) == 0 {
                        grass.push(pos);
                    }
                    match rng.gen_range(0..8192) {
                        1 => cricket1.push(pos),
                        2 => cricket2.push(pos),
                        3 => cricket3.push(pos),
                        _ => {},
                    }
                },
                BlockKind::Water => {
                    let is_waterfall = chunk
                        .get(pos + vek::Vec3::unit_z())
                        .is_ok_and(|b| b.is_air())
                        && [
                            vek::Vec2::new(0, 1),
                            vek::Vec2::new(1, 0),
                            vek::Vec2::new(0, -1),
                            vek::Vec2::new(-1, 0),
                        ]
                        .iter()
                        .map(|p| {
                            (1..=2)
                                .take_while(|i| {
                                    chunk.get(pos + p.with_z(*i)).is_ok_and(|b| b.is_liquid())
                                })
                                .count()
                        })
                        .any(|s| s >= 2);

                    if is_waterfall {
                        waterfall.push((pos, river_velocity));
                    }

                    let river_speed_sq = river_velocity.magnitude_squared();
                    // Assign a river speed to water blocks depending on river velocity
                    if is_waterfall || river_speed_sq > 0.9_f32.powi(2) {
                        fast_river.push(pos)
                    } else if river_speed_sq > 0.3_f32.powi(2) {
                        slow_river.push(pos)
                    }
                },
                BlockKind::Snow if rng.gen_range(0..16) == 0 => snow.push(pos),
                BlockKind::Lava
                    if chunk
                        .get(pos + Vec3::unit_z())
                        .map_or(true, |b| !b.is_filled()) =>
                {
                    if rng.gen_range(0..5) == 0 {
                        fires.push(pos + Vec3::unit_z())
                    }
                    if rng.gen_range(0..16) == 0 {
                        lavapool.push(pos)
                    }
                },
                BlockKind::GlowingMushroom if rng.gen_range(0..8) == 0 => spores.push(pos),
                BlockKind::Snow | BlockKind::Ice if rng.gen_range(0..16) == 0 => snow.push(pos),
                _ => {
                    if let Some(sprite) = block.get_sprite() {
                        if sprite.category() == sprite::Category::Lamp {
                            if let Ok(sprite::LightEnabled(enabled)) = block.get_attr() {
                                interactables.push((pos, Interaction::LightToggle(!enabled)));
                            }
                        }

                        if block.is_mountable() {
                            interactables.push((pos, Interaction::Mount));
                        }

                        match sprite {
                            SpriteKind::Ember => {
                                fires.push(pos);
                                smokers.push(SmokerProperties::new(pos, FireplaceType::House));
                            },
                            SpriteKind::FireBlock => {
                                fire_bowls.push(pos);
                            },
                            // Offset positions to account for block height.
                            // TODO: Is this a good idea?
                            SpriteKind::StreetLamp => fire_bowls.push(pos + Vec3::unit_z() * 2),
                            SpriteKind::FireBowlGround => fire_bowls.push(pos + Vec3::unit_z()),
                            SpriteKind::StreetLampTall => fire_bowls.push(pos + Vec3::unit_z() * 4),
                            SpriteKind::WallSconce => fire_bowls.push(pos + Vec3::unit_z()),
                            SpriteKind::Beehive => beehives.push(pos),
                            SpriteKind::Reed => {
                                reeds.push(pos);
                                fireflies.push(pos);
                                if rng.gen_range(0..12) == 0 {
                                    frogs.push(pos);
                                }
                            },
                            SpriteKind::CaveMushroom => fireflies.push(pos),
                            SpriteKind::PinkFlower => flowers.push(pos),
                            SpriteKind::PurpleFlower => flowers.push(pos),
                            SpriteKind::RedFlower => flowers.push(pos),
                            SpriteKind::WhiteFlower => flowers.push(pos),
                            SpriteKind::YellowFlower => flowers.push(pos),
                            SpriteKind::Sunflower => flowers.push(pos),
                            SpriteKind::CraftingBench => {
                                interactables.push((pos, Interaction::Craft(CraftingTab::All)))
                            },
                            SpriteKind::SmokeDummy => {
                                smokers.push(SmokerProperties::new(pos, FireplaceType::Workshop));
                            },
                            SpriteKind::Forge => interactables
                                .push((pos, Interaction::Craft(CraftingTab::ProcessedMaterial))),
                            SpriteKind::TanningRack => interactables
                                .push((pos, Interaction::Craft(CraftingTab::ProcessedMaterial))),
                            SpriteKind::SpinningWheel => {
                                interactables.push((pos, Interaction::Craft(CraftingTab::All)))
                            },
                            SpriteKind::Loom => {
                                interactables.push((pos, Interaction::Craft(CraftingTab::All)))
                            },
                            SpriteKind::Cauldron => {
                                fires.push(pos);
                                interactables.push((pos, Interaction::Craft(CraftingTab::Potion)))
                            },
                            SpriteKind::Anvil => {
                                interactables.push((pos, Interaction::Craft(CraftingTab::Weapon)))
                            },
                            SpriteKind::CookingPot => {
                                fires.push(pos);
                                interactables.push((pos, Interaction::Craft(CraftingTab::Food)))
                            },
                            SpriteKind::DismantlingBench => {
                                fires.push(pos);
                                interactables
                                    .push((pos, Interaction::Craft(CraftingTab::Dismantle)))
                            },
                            SpriteKind::RepairBench => {
                                interactables.push((pos, Interaction::Craft(CraftingTab::All)))
                            },
                            SpriteKind::OneWayWall => one_way_walls.push((
                                pos,
                                Vec2::unit_y()
                                    .rotated_z(
                                        std::f32::consts::PI
                                            * 0.25
                                            * block.get_ori().unwrap_or(0) as f32,
                                    )
                                    .with_z(0.0),
                            )),
                            SpriteKind::Sign | SpriteKind::HangingSign => {
                                interactables.push((pos, Interaction::Read))
                            },
                            SpriteKind::MycelBlue => spores.push(pos),
                            SpriteKind::Mold => spores.push(pos),
                            _ => {},
                        }
                    }
                },
            }
            if block.collectible_id().is_some() {
                interactables.push((pos, Interaction::Collect));
            }
            if let Some(glow) = block.get_glow() {
                // Currently, we count filled blocks as 'minor' lights, and sprites as
                // non-minor.
                if block.get_sprite().is_none() {
                    minor_lights.push((pos, glow));
                } else {
                    lights.push((pos, glow));
                }
            }
        });

        // TODO: Come up with a better way to prune many light sources: grouping them
        // into larger lights with k-means clustering, perhaps?
        const MAX_MINOR_LIGHTS: usize = 64;
        lights.extend(
            minor_lights
                .choose_multiple(&mut rng, MAX_MINOR_LIGHTS)
                .copied(),
        );

        Self {
            leaves,
            drip,
            grass,
            slow_river,
            fast_river,
            waterfall,
            lavapool,
            fires,
            smokers,
            beehives,
            reeds,
            fireflies,
            flowers,
            fire_bowls,
            snow,
            spores,
            cricket1,
            cricket2,
            cricket3,
            frogs,
            one_way_walls,
            interactables,
            lights,
            temperature,
            humidity,
        }
    }
}