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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
use rinecs::{
    Read, Write, Not, ReadOption, Entities, Resources,
    EntitiesThreadLocal, ResourcesThreadLocal, Has, system, system_thread_local
};
use crate::{
    components::Visible,
    light::shadow,

};
use rin_material::{MaterialRef, MaterialMultiRef};
#[cfg(feature="debug_geometry")]
use crate::geometry::DebugGeometryRef;
use super::resources;
use super::geometry::{ SubmeshBuffers, GpuGeometryRef };
#[cfg(feature="debug_geometry")]
use super::geometry::GpuDebugGeometryRef;
use super::material::MaterialCache;
use rin_graphics::{Node, node::DynamicTransformation};
use rin_gl as gl;

// For each geometry from the opaque and translucent sorted geometry
// indexes, put it's model and normal matrices into a vector to later
// upload it into a buffer to be use as per instance attributes
#[system(name = "model matrices")]
#[needs(
    "MaterialCache",
    "Node",
    "MaterialRef",
    "MaterialMultiRef",
    "Visible",
    "GpuGeometryRef",
    "resources::OpaqueSortedGeometry",
    "resources::TranslucentSortedGeometry"
)]
#[cfg_attr(feature="debug_geometry", needs(
    "DebugGeometryRef",
    "GpuDebugGeometryRef",
    "resources::DebugSortedGeometry"
))]
#[updates("resources::ModelMatricesData")]
pub fn generate_model_matrices_data(entities: Entities, resources: Resources) {
    let materials_cache = resources.get::<MaterialCache>().unwrap();
    let any_model_changed = entities.changed_iter_for::<(
        Read<Node>,
        Read<GpuGeometryRef>,
        ReadOption<MaterialRef>,
        ReadOption<MaterialMultiRef>,
        Read<Visible>)>()
        .any(|(_, _, materials, multimaterials, visible)| {
            visible.is_visible() && if let Some(materials) = materials {
                materials.iter().any(|m| materials_cache[*m].visible)
            }else if let Some(multimaterials) = multimaterials {
                multimaterials.iter()
                    .any(|materials| materials.iter().any(|m| materials_cache[*m].visible))
            }else{
                false
            }
        });

    #[cfg(feature="debug_geometry")]
    let any_debug_model_changed = entities.changed_iter_for::<(
            Read<Node>,
            Read<GpuDebugGeometryRef>,
            Read<DebugGeometryRef>,
        )>().any(|(_, _, debug_geom)|{
            debug_geom.is_visible() && materials_cache[*debug_geom.material()].visible
        });

    #[cfg(not(feature="debug_geometry"))]
    let any_debug_model_changed = false;

    let mut model_data = resources.get_mut::<resources::ModelMatricesData>().unwrap();

    let opaque_geometry_sorted = resources
        .get::<resources::OpaqueSortedGeometry>()
        .unwrap();
    let translucent_geometry_sorted = resources
        .get::<resources::TranslucentSortedGeometry>()
        .unwrap();
    #[cfg(feature="debug_geometry")]
    let debug_geometry_sorted = resources
        .get::<resources::DebugSortedGeometry>()
        .unwrap();
    let opaque_changed = opaque_geometry_sorted.has_changed();
    let translucent_changed = translucent_geometry_sorted.has_changed();
    #[cfg(feature="debug_geometry")]
    let debug_changed = debug_geometry_sorted.has_changed();
    #[cfg(not(feature="debug_geometry"))]
    let debug_changed = false;
    let was_empty = model_data.is_empty();

    if any_model_changed
        || any_debug_model_changed
        || opaque_changed
        || translucent_changed
        || debug_changed
        || model_data.is_empty()
    {
        let geometries = opaque_geometry_sorted.iter().chain(translucent_geometry_sorted.iter());
        #[cfg(feature="debug_geometry")]
        let geometries = geometries.chain(debug_geometry_sorted.iter());
        model_data.clear();
        let geom_entities = geometries.flat_map(|geom| geom.entities.iter());
        let models = entities.iter_for_entities::<Read<Node>,_>(geom_entities)
            .map(|trafo| {
                    let model = trafo.global_transformation();
                    let normal = trafo.inv_global_transformation().transpose();
                    (model, normal)
                });
        model_data.extend(models);

        if !(was_empty && model_data.is_empty()){
            model_data.has_changed = true;
        }
    }
}


// For each geometry from the static shadows geometry
// index, put it's model matrices into a vector to later
// upload it into a buffer to be use as per instance attributes
#[system(name = "generate model mats static")]
#[needs(
    "MaterialCache",
    "resources::StaticShadowsSortedGeometry",
    "Node",
    "Visible",
    "GpuGeometryRef",
    "MaterialRef",
    "MaterialMultiRef",
)]
#[updates("resources::StaticModelMatricesData")]
#[cond(components(has("shadow::StaticMap")))]
pub fn generate_static_model_matrices_data(entities: Entities, resources: Resources) {
    let materials_cache = resources.get::<MaterialCache>().unwrap();
    let geometries = resources.get::<resources::StaticShadowsSortedGeometry>().unwrap();
    let mut model_data = resources.get_mut::<resources::StaticModelMatricesData>().unwrap();
    let was_empty = model_data.is_empty();
    let any_model_changed = geometries.has_changed() || entities.changed_iter_for::<(
        Read<Node>,
        Not<DynamicTransformation>,
        Read<GpuGeometryRef>,
        ReadOption<MaterialRef>,
        ReadOption<MaterialMultiRef>,
        Read<Visible>)>()
        .any(|(_, _, _, materials, multimaterials, visible)| {
            visible.is_visible() && if let Some(materials) = materials {
                materials.iter()
                    .any(|m| !materials_cache[*m].translucent && materials_cache[*m].visible)
            }else if let Some(multimaterials) = multimaterials {
                multimaterials.iter()
                    .any(|materials| materials.iter()
                        .any(|m| !materials_cache[*m].translucent && materials_cache[*m].visible))
            }else{
                false
            }
        });
    if any_model_changed || model_data.is_empty() {
        if !model_data.is_empty(){
            log::trace!("Regenerating static model data");
        }
        model_data.clear();
        let geom_entities = geometries.iter().flat_map(|geom| &geom.entities);
        let models = entities.iter_for_entities::<Read<Node>,_>(geom_entities)
            .map(|trafo| trafo.global_transformation());
        model_data.extend(models);
        if !(was_empty && model_data.is_empty()){
            model_data.has_changed = true;
        }
    }
}

// For each geometry from the dynamic shadows geometry
// index, put it's model matrices into a vector to later
// upload it into a buffer to be use as per instance attributes
#[system(name = "generate model mats dynamic")]
#[needs(
    "MaterialCache",
    "resources::DynamicShadowsSortedGeometry",
    "Node",
    "Visible",
    "GpuGeometryRef",
    "MaterialRef",
    "MaterialMultiRef",
)]
#[updates("resources::DynamicModelMatricesData")]
#[cond(components(has("shadow::Map"), has("shadow::StaticMap")))]
pub fn generate_dynamic_model_matrices_data(entities: Entities, resources: Resources) {
    let materials_cache = resources.get::<MaterialCache>().unwrap();
    let geometries = resources.get::<resources::DynamicShadowsSortedGeometry>().unwrap();
    let any_model_changed = geometries.has_changed() || entities.changed_iter_for::<(
        Read<Node>,
        Has<DynamicTransformation>,
        Read<GpuGeometryRef>,
        ReadOption<MaterialRef>,
        ReadOption<MaterialMultiRef>,
        Read<Visible>)>()
        .any(|(_, _, _, materials, multimaterials, visible)| {
            visible.is_visible() && if let Some(materials) = materials {
                materials.iter()
                    .any(|m| !materials_cache[*m].translucent && materials_cache[*m].visible)
            }else if let Some(multimaterials) = multimaterials {
                multimaterials.iter()
                    .any(|materials| materials.iter()
                        .any(|m| !materials_cache[*m].translucent && materials_cache[*m].visible))
            }else{
                false
            }
        });
    let mut model_data = resources.get_mut::<resources::DynamicModelMatricesData>().unwrap();
    let was_empty = model_data.is_empty();
    if any_model_changed || model_data.is_empty() {
        model_data.clear();
        let geom_entities = geometries.iter().flat_map(|geom| &geom.entities);
        let models = entities.iter_for_entities::<Read<Node>,_>(geom_entities)
            .map(|trafo| trafo.global_transformation());
        model_data.extend(models);
        if !(was_empty && model_data.is_empty()){
            model_data.has_changed = true;
        }
    }
}

// For each geometry from the all shadows geometry
// index, put it's model matrices into a vector to later
// upload it into a buffer to be use as per instance attributes
#[system(name = "generate model mats all")]
#[needs(
    "MaterialCache",
    "resources::AllShadowsSortedGeometry",
    "Node",
    "Visible",
    "GpuGeometryRef",
    "MaterialRef",
    "MaterialMultiRef",
)]
#[updates("resources::AllModelMatricesData")]
#[cond(any(
    components(has_not("shadow::Map", "shadow::StaticMap")),
    has_resource("resources::DepthPrepass")
))]
#[reads("shadow::Map", "shadow::StaticMap")]
pub fn generate_all_model_matrices_data(entities: Entities, resources: Resources) {
    //TODO: Isn't this covered by the cond attribute?
    let any_has_only_dynamic_shadows = entities.iter_for::<(
        Read<shadow::Map>,
        ReadOption<shadow::StaticMap>)>().any(|(_, ss)| ss.is_none());
    let depth_prepass = resources.get::<resources::DepthPrepass>().is_some();

    // Recreate index for static shadows
    if !(any_has_only_dynamic_shadows || depth_prepass) {
        return;
    }

    let materials_cache = resources.get::<MaterialCache>().unwrap();
    let geometries = resources.get::<resources::AllShadowsSortedGeometry>().unwrap();
    let any_model_changed = geometries.has_changed() || entities.changed_iter_for::<(
        Read<Node>,
        Read<GpuGeometryRef>,
        ReadOption<MaterialRef>,
        ReadOption<MaterialMultiRef>,
        Read<Visible>)>()
        .any(|(_, _, materials, multimaterials, visible)| {
            let changed = visible.is_visible();
            changed && if let Some(materials) = materials {
                materials.iter()
                    .any(|m| !materials_cache[*m].translucent && materials_cache[*m].visible)
            }else if let Some(multimaterials) = multimaterials {
                multimaterials.iter()
                    .any(|materials| materials.iter()
                        .any(|m| !materials_cache[*m].translucent && materials_cache[*m].visible))
            }else{
                false
            }
        });
    let mut model_data = resources.get_mut::<resources::AllModelMatricesData>().unwrap();
    let was_empty = model_data.is_empty();
    if any_model_changed || model_data.is_empty() {
        model_data.clear();
        let geom_entities = geometries.iter().flat_map(|geom| &geom.entities);
        let models = entities.iter_for_entities::<Read<Node>,_>(geom_entities)
            .map(|trafo| trafo.global_transformation());
        model_data.extend(models);
        if !(was_empty && model_data.is_empty()){
            model_data.has_changed = true;
        }
    }
}

// TODO: With many objects and only some updating their position
// it might be worth creating a buffer with only the updated matrices
// + their indexes in the final ordered buffer and have a compute shader
// copy the aux buffer to the final buffer's correct positions
// http://on-demand.gputechconf.com/siggraph/2014/presentation/SG4117-OpenGL-Scene-Rendering-Techniques.pdf
#[system_thread_local(name = "upload m. matrices")]
#[needs(resources::ModelMatricesData, SubmeshBuffers)]
#[updates(resources::ModelMatricesBuffer)]
#[writes(SubmeshBuffers, resources::ModelMatricesData)]
#[gpu_stats]
pub fn update_model_matrices_gpu(mut entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
    let mut model_data = resources.get_mut::<resources::ModelMatricesData>().unwrap();
    // let mut vaos_index = resources.get_mut::<resources::GeometryWithModelsIndex>().unwrap();
    let vaos_changed = entities.iter_for::<Read<SubmeshBuffers>>()
        .any(|s| s.iter().any(|s| s.has_changed()));
    // TODO: Separate in static / dynamic?
    if model_data.has_changed || vaos_changed {
        let mut model_data_gpu = resources.get_mut::<resources::ModelMatricesBuffer>().unwrap();
        if model_data_gpu.capacity() >= model_data.len() {
            model_data_gpu.update(&model_data.data);
        }else{
            model_data_gpu.load(&model_data.data, gl::DYNAMIC_DRAW);
        }
        model_data.has_changed = false;
        if vaos_changed {
            for submeshes in entities.iter_for_mut::<Write<SubmeshBuffers>>(){
                for submesh in submeshes {
                    submesh.reset_has_changed();
                }
            }
        }
    }

}


#[system_thread_local(name = "upload static m. matrices")]
#[needs(resources::StaticModelMatricesData)]
#[updates(resources::StaticModelMatricesBuffer)]
#[writes(resources::StaticModelMatricesData)]
#[gpu_stats]
pub fn update_static_model_matrices_gpu(_entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
    let mut model_data = resources.get_mut::<resources::StaticModelMatricesData>().unwrap();
    if model_data.has_changed {
        log::trace!("Updating gpu model data for static geometries");
        let mut model_data_gpu = resources.get_mut::<resources::StaticModelMatricesBuffer>().unwrap();
        if model_data_gpu.capacity() >= model_data.len() {
            model_data_gpu.update(&model_data.data);
        }else{
            model_data_gpu.load(&model_data.data, gl::DYNAMIC_DRAW);
        }
        model_data.has_changed = false;
    }

}


#[system_thread_local(name = "upload dynamic m. matrices")]
#[needs(resources::DynamicModelMatricesData)]
#[updates(resources::DynamicModelMatricesBuffer)]
#[writes(resources::DynamicModelMatricesData)]
#[gpu_stats]
pub fn update_dynamic_model_matrices_gpu(_entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
    let mut model_data = resources.get_mut::<resources::DynamicModelMatricesData>().unwrap();
    if model_data.has_changed {
        let mut model_data_gpu = resources.get_mut::<resources::DynamicModelMatricesBuffer>().unwrap();
        if model_data_gpu.capacity() >= model_data.len() {
            model_data_gpu.update(&model_data.data);
        }else{
            model_data_gpu.load(&model_data.data, gl::DYNAMIC_DRAW);
        }
        model_data.has_changed = false;
    }

}


#[system_thread_local(name = "upload all m. matrices")]
#[needs(resources::AllModelMatricesData)]
#[updates(resources::AllModelMatricesBuffer)]
#[writes(resources::AllModelMatricesData)]
#[gpu_stats]
pub fn update_all_model_matrices_gpu(_entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
    let mut model_data = resources.get_mut::<resources::AllModelMatricesData>().unwrap();
    if model_data.has_changed {
        let mut model_data_gpu = resources.get_mut::<resources::AllModelMatricesBuffer>().unwrap();
        if model_data_gpu.capacity() >= model_data.len() {
            model_data_gpu.update(&model_data.data);
        }else{
            model_data_gpu.load(&model_data.data, gl::DYNAMIC_DRAW);
        }
        model_data.has_changed = false;
    }

}