ascending_graphics/
lights.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
mod pipeline;
mod render;
mod uniforms;
mod vertex;

pub use pipeline::*;
pub use render::*;
pub use uniforms::*;
pub use vertex::*;

use crate::{
    CameraType, Color, DrawOrder, GpuRenderer, Index, OrderedIndex, Vec2, Vec3,
    Vec4,
};
use slotmap::SlotMap;
use std::mem;
use wgpu::util::align_to;

pub const MAX_AREA_LIGHTS: usize = 2_000;
pub const MAX_DIR_LIGHTS: usize = 1_333;

/// Area Lights rendered in the light system.
///
pub struct AreaLight {
    pub pos: Vec2,
    pub color: Color,
    pub max_distance: f32,
    pub anim_speed: f32,
    pub dither: f32,
    pub animate: bool,
    pub camera_type: CameraType,
}

impl AreaLight {
    fn to_raw(&self) -> AreaLightRaw {
        AreaLightRaw {
            pos: self.pos.to_array(),
            color: self.color.0,
            max_distance: self.max_distance,
            dither: self.dither,
            anim_speed: self.anim_speed,
            animate: u32::from(self.animate),
            camera_type: self.camera_type as u32,
        }
    }
}

/// Directional Lights rendered in the light system.
///
pub struct DirectionalLight {
    pub pos: Vec2,
    pub color: Color,
    pub max_distance: f32,
    pub max_width: f32,
    pub anim_speed: f32,
    pub angle: f32,
    pub dither: f32,
    pub fade_distance: f32,
    pub edge_fade_distance: f32,
    pub animate: bool,
    pub camera_type: CameraType,
}

impl DirectionalLight {
    fn to_raw(&self) -> DirectionalLightRaw {
        DirectionalLightRaw {
            pos: self.pos.to_array(),
            color: self.color.0,
            max_distance: self.max_distance,
            animate: u32::from(self.animate),
            max_width: self.max_width,
            anim_speed: self.anim_speed,
            dither: self.dither,
            angle: self.angle,
            fade_distance: self.fade_distance,
            edge_fade_distance: self.edge_fade_distance,
            camera_type: self.camera_type as u32,
        }
    }
}

/// Rendering data for world Light and all Lights.
pub struct Lights {
    /// Z Position of the Main Light Layer.
    pub z: f32,
    /// Color of the main light layer.
    pub world_color: Vec4,
    /// If the [`AreaLight`] and [`DirectionalLight`] are enabled.
    pub enable_lights: bool,
    /// [`Index`] of the Rendering Buffer.
    pub store_id: Index,
    /// DrawOrder of the world Lights.
    pub order: DrawOrder,
    /// Rendering Layer of the world lights used in DrawOrder.
    pub render_layer: u32,
    /// SlotMap storage of [`AreaLight`]'s.
    pub area_lights: SlotMap<Index, AreaLight>,
    /// SlotMap storage of [`DirectionalLight`]'s.
    pub directional_lights: SlotMap<Index, DirectionalLight>,
    /// Count of [`AreaLight`]'s.
    pub area_count: u32,
    /// Count of [`DirectionalLight`]'s.
    pub dir_count: u32,
    /// If Main Light layer got updated we need to update the buffers too.
    pub changed: bool,
    /// If any [`DirectionalLight`] got updated we need to update the buffers too.
    pub directionals_changed: bool,
    /// If any [`AreaLight`] got updated we need to update the buffers too.
    pub areas_changed: bool,
}

impl Lights {
    /// Creates a new [`Lights`].
    ///
    pub fn new(renderer: &mut GpuRenderer, render_layer: u32, z: f32) -> Self {
        Self {
            z,
            world_color: Vec4::new(1.0, 1.0, 1.0, 0.0),
            enable_lights: false,
            store_id: renderer.new_buffer(
                bytemuck::bytes_of(&LightsVertex::default()).len(),
                0,
            ),
            order: DrawOrder::default(),
            render_layer,
            area_lights: SlotMap::with_capacity_and_key(MAX_AREA_LIGHTS),
            directional_lights: SlotMap::with_capacity_and_key(MAX_DIR_LIGHTS),
            area_count: 0,
            dir_count: 0,
            changed: true,
            directionals_changed: true,
            areas_changed: true,
        }
    }

    pub fn unload(&self, renderer: &mut GpuRenderer) {
        renderer.remove_buffer(self.store_id);
    }

    /// Updates the [`Lights`]'s Buffers to prepare them for rendering.
    ///
    pub fn create_quad(&mut self, renderer: &mut GpuRenderer) {
        let instance = LightsVertex {
            world_color: self.world_color.to_array(),
            enable_lights: u32::from(self.enable_lights),
            dir_count: self.directional_lights.len() as u32,
            area_count: self.area_lights.len() as u32,
            z: self.z,
        };

        if let Some(store) = renderer.get_buffer_mut(self.store_id) {
            let bytes = bytemuck::bytes_of(&instance);
            store.store.resize_with(bytes.len(), || 0);
            store.store.copy_from_slice(bytes);
            store.changed = true;
        }

        self.order = DrawOrder::new(
            self.world_color.w < 1.0,
            &Vec3::default(),
            self.render_layer,
        );
        self.changed = false;
    }

    /// Inserts a [`AreaLight`] into [`Lights`].
    /// Returns the [`AreaLight`]'s [`Index`].
    ///
    pub fn insert_area_light(&mut self, light: AreaLight) -> Option<Index> {
        if self.area_lights.len() + 1 >= MAX_AREA_LIGHTS {
            return None;
        }

        self.areas_changed = true;
        self.changed = true;
        Some(self.area_lights.insert(light))
    }

    /// Removes a [`AreaLight`] by its [`Index`].
    ///
    pub fn remove_area_light(&mut self, key: Index) {
        self.areas_changed = true;
        self.changed = true;
        self.area_lights.remove(key);
    }

    /// Gets a Optional mutable reference of a [`Index`]ed [`AreaLight`].
    ///
    pub fn get_mut_area_light(&mut self, key: Index) -> Option<&mut AreaLight> {
        self.areas_changed = true;
        self.area_lights.get_mut(key)
    }

    /// Inserts a [`DirectionalLight`] into [`Lights`].
    /// Returns the [`DirectionalLight`]'s [`Index`].
    ///
    pub fn insert_directional_light(
        &mut self,
        light: DirectionalLight,
    ) -> Option<Index> {
        if self.directional_lights.len() + 1 >= MAX_DIR_LIGHTS {
            return None;
        }

        self.directionals_changed = true;
        self.changed = true;
        Some(self.directional_lights.insert(light))
    }

    /// Removes a [`DirectionalLight`] by its [`Index`].
    ///
    pub fn remove_directional_light(&mut self, key: Index) {
        self.directionals_changed = true;
        self.changed = true;
        self.directional_lights.remove(key);
    }

    /// Gets a Optional mutable reference of a [`Index`]ed [`DirectionalLight`].
    ///
    pub fn get_mut_directional_light(
        &mut self,
        key: Index,
    ) -> Option<&mut DirectionalLight> {
        self.directionals_changed = true;
        self.directional_lights.get_mut(key)
    }

    /// Used to check and update the vertex array.
    /// Returns a [`OrderedIndex`] used in Rendering.
    ///
    pub fn update(
        &mut self,
        renderer: &mut GpuRenderer,
        areas: &mut wgpu::Buffer,
        dirs: &mut wgpu::Buffer,
    ) -> OrderedIndex {
        // if pos or tex_pos or color changed.
        if self.changed {
            self.create_quad(renderer);
        }

        if self.areas_changed {
            let area_alignment: usize =
                align_to(mem::size_of::<AreaLightRaw>(), 32) as usize;
            for (i, (_key, light)) in self.area_lights.iter().enumerate() {
                renderer.queue().write_buffer(
                    areas,
                    (i * area_alignment) as wgpu::BufferAddress,
                    bytemuck::bytes_of(&light.to_raw()),
                );
            }

            self.areas_changed = false;
        }

        if self.directionals_changed {
            let dir_alignment: usize =
                align_to(mem::size_of::<DirectionalLightRaw>(), 48) as usize;
            for (i, (_key, dir)) in self.directional_lights.iter().enumerate() {
                renderer.queue().write_buffer(
                    dirs,
                    (i * dir_alignment) as wgpu::BufferAddress,
                    bytemuck::bytes_of(&dir.to_raw()),
                );
            }

            self.directionals_changed = false;
        }

        OrderedIndex::new(self.order, self.store_id, 0)
    }
}