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
use std::collections::VecDeque;

use log::info;

use crate::{
    utils::{light_utils::LightColor, ndarray::Ndarray, vec::Vec3},
    world::block::Block,
};

use super::{registry::Registry, space::Space, WorldConfig};

pub const VOXEL_NEIGHBORS: [[i32; 3]; 6] = [
    [1, 0, 0],
    [-1, 0, 0],
    [0, 0, 1],
    [0, 0, -1],
    [0, 1, 0],
    [0, -1, 0],
];

/// Node of a light propagation queue.
#[derive(Debug)]
pub struct LightNode {
    pub voxel: [i32; 3],
    pub level: u32,
}

/// A set of utility functions to simulate global illumination in a Voxelize world.
pub struct Lights;

impl Lights {
    /// Propagate a specific queue of `LightNode`s in a depth-first-search fashion. If the propagation
    /// is for sunlight, light value does not decrease going downwards to simulate sunshine.
    pub fn flood_light(
        mut queue: VecDeque<LightNode>,
        is_sunlight: bool,
        color: &LightColor,
        space: &mut Space,
        registry: &Registry,
        config: &WorldConfig,
    ) {
        let &WorldConfig { max_height, .. } = config;

        let Vec3(shape0, _, shape2) = space.shape;
        let Vec3(start_x, _, start_z) = space.min;

        let shape0 = shape0 as i32;
        let shape2 = shape2 as i32;

        let max_height = max_height as i32;

        while !queue.is_empty() {
            let LightNode { voxel, level } = queue.pop_front().unwrap();
            let [vx, vy, vz] = voxel;

            if level == 0 {
                break;
            }

            for [ox, oy, oz] in VOXEL_NEIGHBORS.iter() {
                let nvy = vy + oy;

                if nvy < 0 || nvy >= max_height {
                    continue;
                }

                let nvx = vx + ox;
                let nvz = vz + oz;

                if nvx < start_x
                    || nvz < start_z
                    || nvx >= start_x + shape0
                    || nvz >= start_z + shape2
                {
                    continue;
                }

                let next_level = level - 1;
                let next_voxel = [nvx, nvy, nvz];
                let block_type = registry.get_block_by_id(space.get_voxel(nvx, nvy, nvz));

                if !block_type.is_transparent
                    || (if is_sunlight {
                        space.get_sunlight(nvx, nvy, nvz)
                    } else {
                        space.get_torch_light(nvx, nvy, nvz, &color)
                    } >= next_level)
                {
                    continue;
                }

                if is_sunlight {
                    space.set_sunlight(nvx, nvy, nvz, next_level);
                } else {
                    space.set_torch_light(nvx, nvy, nvz, next_level, &color);
                }

                queue.push_back(LightNode {
                    voxel: next_voxel,
                    level: next_level,
                });
            }
        }
    }

    /// Propagate a space and return the light data of the center chunk.
    pub fn propagate(space: &mut Space, registry: &Registry, config: &WorldConfig) -> Ndarray<u32> {
        let Space { width, min, .. } = space;
        let &WorldConfig {
            max_height,
            max_light_level,
            ..
        } = config;

        let mut red_light_queue = VecDeque::<LightNode>::new();
        let mut green_light_queue = VecDeque::<LightNode>::new();
        let mut blue_light_queue = VecDeque::<LightNode>::new();
        let mut sunlight_queue = VecDeque::<LightNode>::new();

        const RED: LightColor = LightColor::Red;
        const GREEN: LightColor = LightColor::Green;
        const BLUE: LightColor = LightColor::Blue;
        const SUNLIGHT: LightColor = LightColor::Sunlight;

        let &mut Vec3(start_x, _, start_z) = min;

        let width = *width as i32;

        let mut mask = vec![];
        for _ in 0..(width * width) {
            mask.push(max_light_level);
        }

        for y in (0..max_height as i32).rev() {
            for x in 0..width {
                for z in 0..width {
                    let index = (x + z * width) as usize;

                    let id = space.get_voxel(x + start_x, y, z + start_z);
                    let &Block {
                        is_transparent,
                        is_light,
                        red_light_level,
                        green_light_level,
                        blue_light_level,
                        ..
                    } = registry.get_block_by_id(id);

                    if is_transparent {
                        space.set_sunlight(x + start_x, y, z + start_z, mask[index]);

                        if mask[index] == 0 {
                            if (x > 0 && mask[(x - 1 + z * width) as usize] == max_light_level)
                                || (x < width - 1
                                    && mask[(x + 1 + z * width) as usize] == max_light_level)
                                || (z > 0
                                    && mask[(x + (z - 1) * width) as usize] == max_light_level)
                                || (z < width - 1
                                    && mask[(x + (z + 1) * width) as usize] == max_light_level)
                            {
                                space.set_sunlight(
                                    x + start_x,
                                    y,
                                    z + start_z,
                                    max_light_level - 1,
                                );
                                sunlight_queue.push_back(LightNode {
                                    level: max_light_level - 1,
                                    voxel: [start_x + x, y, start_z + z],
                                });
                            }
                        }
                    } else {
                        mask[index] = 0;
                    }

                    if is_light {
                        if red_light_level > 0 {
                            space.set_red_light(x + start_x, y, z + start_z, red_light_level);
                            red_light_queue.push_back(LightNode {
                                voxel: [x + start_x, y, z + start_z],
                                level: red_light_level,
                            });
                        }
                        if green_light_level > 0 {
                            space.set_green_light(x + start_x, y, z + start_z, green_light_level);
                            green_light_queue.push_back(LightNode {
                                voxel: [x + start_x, y, z + start_z],
                                level: green_light_level,
                            });
                        }
                        if blue_light_level > 0 {
                            space.set_blue_light(x + start_x, y, z + start_z, blue_light_level);
                            blue_light_queue.push_back(LightNode {
                                voxel: [x + start_x, y, z + start_z],
                                level: blue_light_level,
                            });
                        }
                    }
                }
            }
        }

        if !red_light_queue.is_empty() {
            Lights::flood_light(red_light_queue, false, &RED, space, registry, config);
        }

        if !green_light_queue.is_empty() {
            Lights::flood_light(green_light_queue, false, &GREEN, space, registry, config);
        }

        if !blue_light_queue.is_empty() {
            Lights::flood_light(blue_light_queue, false, &BLUE, space, registry, config);
        }

        if !sunlight_queue.is_empty() {
            Lights::flood_light(sunlight_queue, true, &SUNLIGHT, space, registry, config);
        }

        space
            .get_lights(space.coords.0, space.coords.1)
            .unwrap()
            .to_owned()
    }
}