Merge branch 'master' into blender2.8
[blender.git] / source / blender / draw / engines / eevee / eevee_lights.c
1 /*
2  * Copyright 2016, Blender Foundation.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Blender Institute
19  *
20  */
21
22 /** \file eevee_lights.c
23  *  \ingroup DNA
24  */
25
26 #include "DRW_render.h"
27
28 #include "BLI_dynstr.h"
29
30 #include "BKE_object.h"
31
32 #include "eevee_engine.h"
33 #include "eevee_private.h"
34
35 /* Theses are the structs stored inside Objects.
36  * It works with even if the object is in multiple layers
37  * because we don't get the same "Object *" for each layer. */
38 typedef struct EEVEE_LightData {
39         short light_id, shadow_id;
40 } EEVEE_LightData;
41
42 typedef struct EEVEE_ShadowCubeData {
43         short light_id, shadow_id, cube_id, layer_id;
44 } EEVEE_ShadowCubeData;
45
46 typedef struct EEVEE_ShadowCascadeData {
47         short light_id, shadow_id, cascade_id, layer_id;
48         float viewprojmat[MAX_CASCADE_NUM][4][4]; /* World->Lamp->NDC : used for rendering the shadow map. */
49         float radius[MAX_CASCADE_NUM];
50 } EEVEE_ShadowCascadeData;
51
52 typedef struct ShadowCaster {
53         struct ShadowCaster *next, *prev;
54         void *ob;
55         bool prune;
56 } ShadowCaster;
57
58 static struct {
59         struct GPUShader *shadow_sh;
60         struct GPUShader *shadow_store_cube_sh[SHADOW_METHOD_MAX];
61         struct GPUShader *shadow_store_cascade_sh[SHADOW_METHOD_MAX];
62         struct GPUShader *shadow_copy_cube_sh[SHADOW_METHOD_MAX];
63         struct GPUShader *shadow_copy_cascade_sh[SHADOW_METHOD_MAX];
64 } e_data = {NULL}; /* Engine data */
65
66 extern char datatoc_shadow_vert_glsl[];
67 extern char datatoc_shadow_geom_glsl[];
68 extern char datatoc_shadow_frag_glsl[];
69 extern char datatoc_shadow_store_frag_glsl[];
70 extern char datatoc_shadow_copy_frag_glsl[];
71 extern char datatoc_concentric_samples_lib_glsl[];
72
73 /* *********** FUNCTIONS *********** */
74
75 void EEVEE_lights_init(EEVEE_SceneLayerData *sldata)
76 {
77         const unsigned int shadow_ubo_size = sizeof(EEVEE_Shadow) * MAX_SHADOW +
78                                              sizeof(EEVEE_ShadowCube) * MAX_SHADOW_CUBE +
79                                              sizeof(EEVEE_ShadowCascade) * MAX_SHADOW_CASCADE;
80
81         const DRWContextState *draw_ctx = DRW_context_state_get();
82         SceneLayer *scene_layer = draw_ctx->scene_layer;
83         IDProperty *props = BKE_scene_layer_engine_evaluated_get(scene_layer, COLLECTION_MODE_NONE, RE_engine_id_BLENDER_EEVEE);
84
85         if (!e_data.shadow_sh) {
86                 e_data.shadow_sh = DRW_shader_create(
87                         datatoc_shadow_vert_glsl, datatoc_shadow_geom_glsl, datatoc_shadow_frag_glsl, NULL);
88
89                 DynStr *ds_frag = BLI_dynstr_new();
90                 BLI_dynstr_append(ds_frag, datatoc_concentric_samples_lib_glsl);
91                 BLI_dynstr_append(ds_frag, datatoc_shadow_store_frag_glsl);
92                 char *store_shadow_shader_str = BLI_dynstr_get_cstring(ds_frag);
93                 BLI_dynstr_free(ds_frag);
94
95                 e_data.shadow_store_cube_sh[SHADOW_ESM] = DRW_shader_create_fullscreen(store_shadow_shader_str, "#define ESM\n");
96                 e_data.shadow_store_cascade_sh[SHADOW_ESM] = DRW_shader_create_fullscreen(store_shadow_shader_str, "#define ESM\n"
97                                                                                                                    "#define CSM\n");
98
99                 e_data.shadow_store_cube_sh[SHADOW_VSM] = DRW_shader_create_fullscreen(store_shadow_shader_str, "#define VSM\n");
100                 e_data.shadow_store_cascade_sh[SHADOW_VSM] = DRW_shader_create_fullscreen(store_shadow_shader_str, "#define VSM\n"
101                                                                                                                    "#define CSM\n");
102
103                 MEM_freeN(store_shadow_shader_str);
104
105                 e_data.shadow_copy_cube_sh[SHADOW_ESM] = DRW_shader_create_fullscreen(datatoc_shadow_copy_frag_glsl, "#define ESM\n"
106                                                                                                                      "#define COPY\n");
107                 e_data.shadow_copy_cascade_sh[SHADOW_ESM] = DRW_shader_create_fullscreen(datatoc_shadow_copy_frag_glsl, "#define ESM\n"
108                                                                                                                         "#define COPY\n"
109                                                                                                                         "#define CSM\n");
110
111                 e_data.shadow_copy_cube_sh[SHADOW_VSM] = DRW_shader_create_fullscreen(datatoc_shadow_copy_frag_glsl, "#define VSM\n"
112                                                                                                                      "#define COPY\n");
113                 e_data.shadow_copy_cascade_sh[SHADOW_VSM] = DRW_shader_create_fullscreen(datatoc_shadow_copy_frag_glsl, "#define VSM\n"
114                                                                                                                         "#define COPY\n"
115                                                                                                                         "#define CSM\n");
116         }
117
118         if (!sldata->lamps) {
119                 sldata->lamps              = MEM_callocN(sizeof(EEVEE_LampsInfo), "EEVEE_LampsInfo");
120                 sldata->light_ubo          = DRW_uniformbuffer_create(sizeof(EEVEE_Light) * MAX_LIGHT, NULL);
121                 sldata->shadow_ubo         = DRW_uniformbuffer_create(shadow_ubo_size, NULL);
122                 sldata->shadow_render_ubo  = DRW_uniformbuffer_create(sizeof(EEVEE_ShadowRender), NULL);
123         }
124
125         int sh_method = BKE_collection_engine_property_value_get_int(props, "shadow_method");
126         int sh_size = BKE_collection_engine_property_value_get_int(props, "shadow_size");
127         int sh_high_bitdepth = BKE_collection_engine_property_value_get_int(props, "shadow_high_bitdepth");
128
129         EEVEE_LampsInfo *linfo = sldata->lamps;
130         if ((linfo->shadow_size != sh_size) ||
131                 (linfo->shadow_method != sh_method) ||
132                 (linfo->shadow_high_bitdepth != sh_high_bitdepth))
133         {
134                 BLI_assert((sh_size > 0) && (sh_size <= 8192));
135                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_pool);
136                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cube_target);
137                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cascade_target);
138                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cube_blur);
139                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cascade_blur);
140
141                 linfo->shadow_high_bitdepth = sh_high_bitdepth;
142                 linfo->shadow_method = sh_method;
143                 linfo->shadow_size = sh_size;
144                 linfo->shadow_render_data.stored_texel_size = 1.0 / (float)linfo->shadow_size;
145
146                 /* Compute adequate size for the cubemap render target.
147                  * The 3.0f factor is here to make sure there is no under sampling between
148                  * the octahedron mapping and the cubemap. */
149                 int new_cube_target_size = (int)ceil(sqrt((float)(sh_size * sh_size) / 6.0f) * 3.0f);
150
151                 CLAMP(new_cube_target_size, 1, 4096);
152
153                 linfo->shadow_cube_target_size = new_cube_target_size;
154                 linfo->shadow_render_data.cube_texel_size = 1.0 / (float)linfo->shadow_cube_target_size;
155         }
156 }
157
158 void EEVEE_lights_cache_init(EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl)
159 {
160         EEVEE_LampsInfo *linfo = sldata->lamps;
161
162         linfo->num_light = 0;
163         linfo->num_layer = 0;
164         linfo->gpu_cube_ct = linfo->gpu_cascade_ct = linfo->gpu_shadow_ct = 0;
165         linfo->cpu_cube_ct = linfo->cpu_cascade_ct = 0;
166         memset(linfo->light_ref, 0, sizeof(linfo->light_ref));
167         memset(linfo->shadow_cube_ref, 0, sizeof(linfo->shadow_cube_ref));
168         memset(linfo->shadow_cascade_ref, 0, sizeof(linfo->shadow_cascade_ref));
169
170         {
171                 psl->shadow_cube_store_pass = DRW_pass_create("Shadow Storage Pass", DRW_STATE_WRITE_COLOR);
172
173                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.shadow_store_cube_sh[linfo->shadow_method], psl->shadow_cube_store_pass);
174                 DRW_shgroup_uniform_buffer(grp, "shadowTexture", &sldata->shadow_cube_blur);
175                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
176                 DRW_shgroup_uniform_float(grp, "shadowFilterSize", &linfo->filter_size, 1);
177                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
178         }
179
180         {
181                 psl->shadow_cascade_store_pass = DRW_pass_create("Shadow Cascade Storage Pass", DRW_STATE_WRITE_COLOR);
182
183                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.shadow_store_cascade_sh[linfo->shadow_method], psl->shadow_cascade_store_pass);
184                 DRW_shgroup_uniform_buffer(grp, "shadowTexture", &sldata->shadow_cascade_blur);
185                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
186                 DRW_shgroup_uniform_int(grp, "cascadeId", &linfo->current_shadow_cascade, 1);
187                 DRW_shgroup_uniform_float(grp, "shadowFilterSize", &linfo->filter_size, 1);
188                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
189         }
190
191         {
192                 psl->shadow_cube_copy_pass = DRW_pass_create("Shadow Copy Pass", DRW_STATE_WRITE_COLOR);
193
194                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.shadow_copy_cube_sh[linfo->shadow_method], psl->shadow_cube_copy_pass);
195                 DRW_shgroup_uniform_buffer(grp, "shadowTexture", &sldata->shadow_cube_target);
196                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
197                 DRW_shgroup_uniform_float(grp, "shadowFilterSize", &linfo->filter_size, 1);
198                 DRW_shgroup_uniform_int(grp, "faceId", &linfo->current_shadow_face, 1);
199                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
200         }
201
202         {
203                 psl->shadow_cascade_copy_pass = DRW_pass_create("Shadow Cascade Copy Pass", DRW_STATE_WRITE_COLOR);
204
205                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.shadow_copy_cascade_sh[linfo->shadow_method], psl->shadow_cascade_copy_pass);
206                 DRW_shgroup_uniform_buffer(grp, "shadowTexture", &sldata->shadow_cascade_target);
207                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
208                 DRW_shgroup_uniform_float(grp, "shadowFilterSize", &linfo->filter_size, 1);
209                 DRW_shgroup_uniform_int(grp, "cascadeId", &linfo->current_shadow_cascade, 1);
210                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
211         }
212
213         {
214                 psl->shadow_cube_pass = DRW_pass_create("Shadow Cube Pass", DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS);
215         }
216
217         {
218                 psl->shadow_cascade_pass = DRW_pass_create("Shadow Cascade Pass", DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS);
219         }
220
221         /* Reset shadow casters list */
222         BLI_freelistN(&sldata->shadow_casters);
223 }
224
225 void EEVEE_lights_cache_add(EEVEE_SceneLayerData *sldata, Object *ob)
226 {
227         EEVEE_LampsInfo *linfo = sldata->lamps;
228
229         /* Step 1 find all lamps in the scene and setup them */
230         if (linfo->num_light > MAX_LIGHT) {
231                 printf("Too much lamps in the scene !!!\n");
232                 linfo->num_light = MAX_LIGHT;
233         }
234         else {
235                 Lamp *la = (Lamp *)ob->data;
236                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
237
238                 if ((ob->deg_update_flag & DEG_RUNTIME_DATA_UPDATE) != 0) {
239                         led->need_update = true;
240                 }
241
242                 MEM_SAFE_FREE(led->storage);
243
244                 if (la->mode & (LA_SHAD_BUF | LA_SHAD_RAY)) {
245                         if (la->type == LA_SUN) {
246                                 int sh_nbr = 1; /* TODO : MSM */
247                                 int cascade_nbr = MAX_CASCADE_NUM; /* TODO : Custom cascade number */
248
249                                 if ((linfo->gpu_cascade_ct + sh_nbr) <= MAX_SHADOW_CASCADE) {
250                                         /* Save Light object. */
251                                         linfo->shadow_cascade_ref[linfo->cpu_cascade_ct] = ob;
252
253                                         /* Create storage and store indices. */
254                                         EEVEE_ShadowCascadeData *data = MEM_mallocN(sizeof(EEVEE_ShadowCascadeData), "EEVEE_ShadowCascadeData");
255                                         data->shadow_id = linfo->gpu_shadow_ct;
256                                         data->cascade_id = linfo->gpu_cascade_ct;
257                                         data->layer_id = linfo->num_layer;
258                                         led->storage = data;
259
260                                         /* Increment indices. */
261                                         linfo->gpu_shadow_ct += 1;
262                                         linfo->gpu_cascade_ct += sh_nbr;
263                                         linfo->num_layer += sh_nbr * cascade_nbr;
264
265                                         linfo->cpu_cascade_ct += 1;
266                                 }
267                         }
268                         else if (la->type == LA_SPOT || la->type == LA_LOCAL || la->type == LA_AREA) {
269                                 int sh_nbr = 1; /* TODO : MSM */
270
271                                 if ((linfo->gpu_cube_ct + sh_nbr) <= MAX_SHADOW_CUBE) {
272                                         /* Save Light object. */
273                                         linfo->shadow_cube_ref[linfo->cpu_cube_ct] = ob;
274
275                                         /* Create storage and store indices. */
276                                         EEVEE_ShadowCubeData *data = MEM_mallocN(sizeof(EEVEE_ShadowCubeData), "EEVEE_ShadowCubeData");
277                                         data->shadow_id = linfo->gpu_shadow_ct;
278                                         data->cube_id = linfo->gpu_cube_ct;
279                                         data->layer_id = linfo->num_layer;
280                                         led->storage = data;
281
282                                         /* Increment indices. */
283                                         linfo->gpu_shadow_ct += 1;
284                                         linfo->gpu_cube_ct += sh_nbr;
285                                         linfo->num_layer += sh_nbr;
286
287                                         linfo->cpu_cube_ct += 1;
288                                 }
289                         }
290                 }
291
292                 /* Default light without shadows */
293                 if (!led->storage) {
294                         led->storage = MEM_mallocN(sizeof(EEVEE_LightData), "EEVEE_LightData");
295                         ((EEVEE_LightData *)led->storage)->shadow_id = -1;
296                 }
297
298                 ((EEVEE_LightData *)led->storage)->light_id = linfo->num_light;
299                 linfo->light_ref[linfo->num_light] = ob;
300                 linfo->num_light++;
301         }
302 }
303
304 /* Add a shadow caster to the shadowpasses */
305 void EEVEE_lights_cache_shcaster_add(EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl, struct Gwn_Batch *geom, float (*obmat)[4])
306 {
307         DRWShadingGroup *grp = DRW_shgroup_instance_create(e_data.shadow_sh, psl->shadow_cube_pass, geom);
308         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
309         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
310
311         for (int i = 0; i < 6; ++i)
312                 DRW_shgroup_call_dynamic_add_empty(grp);
313
314         grp = DRW_shgroup_instance_create(e_data.shadow_sh, psl->shadow_cascade_pass, geom);
315         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
316         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
317
318         for (int i = 0; i < MAX_CASCADE_NUM; ++i)
319                 DRW_shgroup_call_dynamic_add_empty(grp);
320 }
321
322 void EEVEE_lights_cache_shcaster_material_add(
323         EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl, struct GPUMaterial *gpumat, struct Gwn_Batch *geom, float (*obmat)[4], float *alpha_threshold)
324 {
325         DRWShadingGroup *grp = DRW_shgroup_material_instance_create(gpumat, psl->shadow_cube_pass, geom);
326
327         if (grp == NULL) return;
328
329         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
330         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
331
332         if (alpha_threshold != NULL)
333                 DRW_shgroup_uniform_float(grp, "alphaThreshold", alpha_threshold, 1);
334
335         for (int i = 0; i < 6; ++i)
336                 DRW_shgroup_call_dynamic_add_empty(grp);
337
338         grp = DRW_shgroup_material_instance_create(gpumat, psl->shadow_cascade_pass, geom);
339         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
340         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
341
342         if (alpha_threshold != NULL)
343                 DRW_shgroup_uniform_float(grp, "alphaThreshold", alpha_threshold, 1);
344
345         for (int i = 0; i < MAX_CASCADE_NUM; ++i)
346                 DRW_shgroup_call_dynamic_add_empty(grp);
347 }
348
349 void EEVEE_lights_cache_finish(EEVEE_SceneLayerData *sldata)
350 {
351         EEVEE_LampsInfo *linfo = sldata->lamps;
352         DRWTextureFormat shadow_pool_format;
353
354         /* Setup enough layers. */
355         /* Free textures if number mismatch. */
356         if (linfo->num_layer != linfo->cache_num_layer) {
357                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_pool);
358                 linfo->cache_num_layer = linfo->num_layer;
359                 linfo->update_flag |= LIGHT_UPDATE_SHADOW_CUBE;
360         }
361
362         switch (linfo->shadow_method) {
363                 case SHADOW_ESM: shadow_pool_format = ((linfo->shadow_high_bitdepth) ? DRW_TEX_R_32 : DRW_TEX_R_16); break;
364                 case SHADOW_VSM: shadow_pool_format = ((linfo->shadow_high_bitdepth) ? DRW_TEX_RG_32 : DRW_TEX_RG_16); break;
365                 default:
366                         BLI_assert(!"Incorrect Shadow Method");
367                         break;
368         }
369
370         if (!sldata->shadow_cube_target) {
371                 /* TODO render everything on the same 2d render target using clip planes and no Geom Shader. */
372                 /* Cubemaps */
373                 sldata->shadow_cube_target = DRW_texture_create_cube(linfo->shadow_cube_target_size, DRW_TEX_DEPTH_24, 0, NULL);
374                 sldata->shadow_cube_blur = DRW_texture_create_cube(linfo->shadow_cube_target_size, shadow_pool_format, DRW_TEX_FILTER, NULL);
375         }
376
377         if (!sldata->shadow_cascade_target) {
378                 /* CSM */
379                 sldata->shadow_cascade_target = DRW_texture_create_2D_array(
380                         linfo->shadow_size, linfo->shadow_size, MAX_CASCADE_NUM, DRW_TEX_DEPTH_24, 0, NULL);
381                 sldata->shadow_cascade_blur = DRW_texture_create_2D_array(
382                         linfo->shadow_size, linfo->shadow_size, MAX_CASCADE_NUM, shadow_pool_format, DRW_TEX_FILTER, NULL);
383         }
384
385         /* Initialize Textures Array first so DRW_framebuffer_init just bind them. */
386         if (!sldata->shadow_pool) {
387                 /* All shadows fit in this array */
388                 sldata->shadow_pool = DRW_texture_create_2D_array(
389                         linfo->shadow_size, linfo->shadow_size, max_ff(1, linfo->num_layer),
390                         shadow_pool_format, DRW_TEX_FILTER, NULL);
391         }
392
393         /* Render FB */
394         DRWFboTexture tex_cascade = {&sldata->shadow_cube_target, DRW_TEX_DEPTH_24, 0};
395         DRW_framebuffer_init(&sldata->shadow_target_fb, &draw_engine_eevee_type,
396                              linfo->shadow_size, linfo->shadow_size,
397                              &tex_cascade, 1);
398
399         /* Storage FB */
400         DRWFboTexture tex_pool = {&sldata->shadow_pool, shadow_pool_format, DRW_TEX_FILTER};
401         DRW_framebuffer_init(&sldata->shadow_store_fb, &draw_engine_eevee_type,
402                              linfo->shadow_size, linfo->shadow_size,
403                              &tex_pool, 1);
404
405         /* Restore */
406         DRW_framebuffer_texture_detach(sldata->shadow_cube_target);
407
408         /* Update Lamps UBOs. */
409         EEVEE_lights_update(sldata);
410 }
411
412 /* Update buffer with lamp data */
413 static void eevee_light_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led)
414 {
415         /* TODO only update if data changes */
416         EEVEE_LightData *evld = led->storage;
417         EEVEE_Light *evli = linfo->light_data + evld->light_id;
418         Lamp *la = (Lamp *)ob->data;
419         float mat[4][4], scale[3], power;
420
421         /* Position */
422         copy_v3_v3(evli->position, ob->obmat[3]);
423
424         /* Color */
425         copy_v3_v3(evli->color, &la->r);
426
427         /* Influence Radius */
428         evli->dist = la->dist;
429
430         /* Vectors */
431         normalize_m4_m4_ex(mat, ob->obmat, scale);
432         copy_v3_v3(evli->forwardvec, mat[2]);
433         normalize_v3(evli->forwardvec);
434         negate_v3(evli->forwardvec);
435
436         copy_v3_v3(evli->rightvec, mat[0]);
437         normalize_v3(evli->rightvec);
438
439         copy_v3_v3(evli->upvec, mat[1]);
440         normalize_v3(evli->upvec);
441
442         /* Spot size & blend */
443         if (la->type == LA_SPOT) {
444                 evli->sizex = scale[0] / scale[2];
445                 evli->sizey = scale[1] / scale[2];
446                 evli->spotsize = cosf(la->spotsize * 0.5f);
447                 evli->spotblend = (1.0f - evli->spotsize) * la->spotblend;
448                 evli->radius = max_ff(0.001f, la->area_size);
449         }
450         else if (la->type == LA_AREA) {
451                 evli->sizex = max_ff(0.0001f, la->area_size * scale[0] * 0.5f);
452                 if (la->area_shape == LA_AREA_RECT) {
453                         evli->sizey = max_ff(0.0001f, la->area_sizey * scale[1] * 0.5f);
454                 }
455                 else {
456                         evli->sizey = max_ff(0.0001f, la->area_size * scale[1] * 0.5f);
457                 }
458         }
459         else {
460                 evli->radius = max_ff(0.001f, la->area_size);
461         }
462
463         /* Make illumination power constant */
464         if (la->type == LA_AREA) {
465                 power = 1.0f / (evli->sizex * evli->sizey * 4.0f * M_PI) /* 1/(w*h*Pi) */
466                         * 80.0f; /* XXX : Empirical, Fit cycles power */
467         }
468         else if (la->type == LA_SPOT || la->type == LA_LOCAL) {
469                 power = 1.0f / (4.0f * evli->radius * evli->radius * M_PI * M_PI) /* 1/(4*r²*Pi²) */
470                         * M_PI * M_PI * M_PI * 10.0; /* XXX : Empirical, Fit cycles power */
471
472                 /* for point lights (a.k.a radius == 0.0) */
473                 // power = M_PI * M_PI * 0.78; /* XXX : Empirical, Fit cycles power */
474         }
475         else {
476                 power = 1.0f;
477         }
478         mul_v3_fl(evli->color, power * la->energy);
479
480         /* Lamp Type */
481         evli->lamptype = (float)la->type;
482
483         /* No shadow by default */
484         evli->shadowid = -1.0f;
485 }
486
487 static void eevee_shadow_cube_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led)
488 {
489         EEVEE_ShadowCubeData *sh_data = (EEVEE_ShadowCubeData *)led->storage;
490         EEVEE_Light *evli = linfo->light_data + sh_data->light_id;
491         EEVEE_Shadow *ubo_data = linfo->shadow_data + sh_data->shadow_id;
492         EEVEE_ShadowCube *cube_data = linfo->shadow_cube_data + sh_data->cube_id;
493         Lamp *la = (Lamp *)ob->data;
494
495         int sh_nbr = 1; /* TODO: MSM */
496
497         for (int i = 0; i < sh_nbr; ++i) {
498                 /* TODO : choose MSM sample point here. */
499                 copy_v3_v3(cube_data->position, ob->obmat[3]);
500         }
501
502         ubo_data->bias = 0.05f * la->bias;
503         ubo_data->near = la->clipsta;
504         ubo_data->far = la->clipend;
505         ubo_data->exp = (linfo->shadow_method == SHADOW_VSM) ? la->bleedbias : la->bleedexp;
506
507         evli->shadowid = (float)(sh_data->shadow_id);
508         ubo_data->shadow_start = (float)(sh_data->layer_id);
509         ubo_data->data_start = (float)(sh_data->cube_id);
510         ubo_data->multi_shadow_count = (float)(sh_nbr);
511 }
512
513 #define LERP(t, a, b) ((a) + (t) * ((b) - (a)))
514
515 static void frustum_min_bounding_sphere(const float corners[8][4], float r_center[3], float *r_radius)
516 {
517 #if 0 /* Simple solution but waist too much space. */
518         float minvec[3], maxvec[3];
519
520         /* compute the bounding box */
521         INIT_MINMAX(minvec, maxvec);
522         for (int i = 0; i < 8; ++i)     {
523                 minmax_v3v3_v3(minvec, maxvec, corners[i]);
524         }
525
526         /* compute the bounding sphere of this box */
527         r_radius = len_v3v3(minvec, maxvec) * 0.5f;
528         add_v3_v3v3(r_center, minvec, maxvec);
529         mul_v3_fl(r_center, 0.5f);
530 #else
531         /* Make the bouding sphere always centered on the front diagonal */
532         add_v3_v3v3(r_center, corners[4], corners[7]);
533         mul_v3_fl(r_center, 0.5f);
534         *r_radius = len_v3v3(corners[0], r_center);
535
536         /* Search the largest distance between the sphere center
537          * and the front plane corners. */
538         for (int i = 0; i < 4; ++i) {
539                 float rad = len_v3v3(corners[4+i], r_center);
540                 if (rad > *r_radius) {
541                         *r_radius = rad;
542                 }
543         }
544 #endif
545 }
546
547 static void eevee_shadow_cascade_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led)
548 {
549         Lamp *la = (Lamp *)ob->data;
550
551         /* Camera Matrices */
552         float persmat[4][4], persinv[4][4];
553         float viewprojmat[4][4], projinv[4][4];
554         float view_near, view_far;
555         float near_v[4] = {0.0f, 0.0f, -1.0f, 1.0f};
556         float far_v[4] = {0.0f, 0.0f,  1.0f, 1.0f};
557         bool is_persp = DRW_viewport_is_persp_get();
558         DRW_viewport_matrix_get(persmat, DRW_MAT_PERS);
559         invert_m4_m4(persinv, persmat);
560         /* FIXME : Get near / far from Draw manager? */
561         DRW_viewport_matrix_get(viewprojmat, DRW_MAT_WIN);
562         invert_m4_m4(projinv, viewprojmat);
563         mul_m4_v4(projinv, near_v);
564         mul_m4_v4(projinv, far_v);
565         view_near = near_v[2];
566         view_far = far_v[2]; /* TODO: Should be a shadow parameter */
567         if (is_persp) {
568                 view_near /= near_v[3];
569                 view_far /= far_v[3];
570         }
571
572         /* Lamps Matrices */
573         float viewmat[4][4], projmat[4][4];
574         int sh_nbr = 1; /* TODO : MSM */
575         int cascade_nbr = la->cascade_count;
576
577         EEVEE_ShadowCascadeData *sh_data = (EEVEE_ShadowCascadeData *)led->storage;
578         EEVEE_Light *evli = linfo->light_data + sh_data->light_id;
579         EEVEE_Shadow *ubo_data = linfo->shadow_data + sh_data->shadow_id;
580         EEVEE_ShadowCascade *cascade_data = linfo->shadow_cascade_data + sh_data->cascade_id;
581
582         /* The technique consists into splitting
583          * the view frustum into several sub-frustum
584          * that are individually receiving one shadow map */
585
586         float csm_start, csm_end;
587
588         if (is_persp) {
589                 csm_start = view_near;
590                 csm_end = max_ff(view_far, -la->cascade_max_dist);
591                 /* Avoid artifacts */
592                 csm_end = min_ff(view_near, csm_end);
593         }
594         else {
595                 csm_start = -view_far;
596                 csm_end = view_far;
597         }
598
599         /* init near/far */
600         for (int c = 0; c < MAX_CASCADE_NUM; ++c) {
601                 cascade_data->split_start[c] = csm_end;
602                 cascade_data->split_end[c] = csm_end;
603         }
604
605         /* Compute split planes */
606         float splits_start_ndc[MAX_CASCADE_NUM];
607         float splits_end_ndc[MAX_CASCADE_NUM];
608
609         {
610                 /* Nearest plane */
611                 float p[4] = {1.0f, 1.0f, csm_start, 1.0f};
612                 /* TODO: we don't need full m4 multiply here */
613                 mul_m4_v4(viewprojmat, p);
614                 splits_start_ndc[0] = p[2];
615                 if (is_persp) {
616                         splits_start_ndc[0] /= p[3];
617                 }
618         }
619
620         {
621                 /* Farthest plane */
622                 float p[4] = {1.0f, 1.0f, csm_end, 1.0f};
623                 /* TODO: we don't need full m4 multiply here */
624                 mul_m4_v4(viewprojmat, p);
625                 splits_end_ndc[cascade_nbr - 1] = p[2];
626                 if (is_persp) {
627                         splits_end_ndc[cascade_nbr - 1] /= p[3];
628                 }
629         }
630
631         cascade_data->split_start[0] = csm_start;
632         cascade_data->split_end[cascade_nbr - 1] = csm_end;
633
634         for (int c = 1; c < cascade_nbr; ++c) {
635                 /* View Space */
636                 float linear_split = LERP(((float)(c) / (float)cascade_nbr), csm_start, csm_end);
637                 float exp_split = csm_start * powf(csm_end / csm_start, (float)(c) / (float)cascade_nbr);
638
639                 if (is_persp) {
640                         cascade_data->split_start[c] = LERP(la->cascade_exponent, linear_split, exp_split);
641                 }
642                 else {
643                         cascade_data->split_start[c] = linear_split;
644                 }
645                 cascade_data->split_end[c-1] = cascade_data->split_start[c];
646
647                 /* Add some overlap for smooth transition */
648                 cascade_data->split_start[c] = LERP(la->cascade_fade, cascade_data->split_end[c-1],
649                                                     (c > 1) ? cascade_data->split_end[c-2] : cascade_data->split_start[0]);
650
651                 /* NDC Space */
652                 {
653                         float p[4] = {1.0f, 1.0f, cascade_data->split_start[c], 1.0f};
654                         /* TODO: we don't need full m4 multiply here */
655                         mul_m4_v4(viewprojmat, p);
656                         splits_start_ndc[c] = p[2];
657
658                         if (is_persp) {
659                                 splits_start_ndc[c] /= p[3];
660                         }
661                 }
662
663                 {
664                         float p[4] = {1.0f, 1.0f, cascade_data->split_end[c-1], 1.0f};
665                         /* TODO: we don't need full m4 multiply here */
666                         mul_m4_v4(viewprojmat, p);
667                         splits_end_ndc[c-1] = p[2];
668
669                         if (is_persp) {
670                                 splits_end_ndc[c-1] /= p[3];
671                         }
672                 }
673         }
674
675         /* Set last cascade split fade distance into the first split_start. */
676         float prev_split = (cascade_nbr > 1) ? cascade_data->split_end[cascade_nbr-2] : cascade_data->split_start[0];
677         cascade_data->split_start[0] = LERP(la->cascade_fade, cascade_data->split_end[cascade_nbr-1], prev_split);
678
679         /* For each cascade */
680         for (int c = 0; c < cascade_nbr; ++c) {
681                 /* Given 8 frustum corners */
682                 float corners[8][4] = {
683                         /* Near Cap */
684                         {-1.0f, -1.0f, splits_start_ndc[c], 1.0f},
685                         { 1.0f, -1.0f, splits_start_ndc[c], 1.0f},
686                         {-1.0f,  1.0f, splits_start_ndc[c], 1.0f},
687                         { 1.0f,  1.0f, splits_start_ndc[c], 1.0f},
688                         /* Far Cap */
689                         {-1.0f, -1.0f, splits_end_ndc[c], 1.0f},
690                         { 1.0f, -1.0f, splits_end_ndc[c], 1.0f},
691                         {-1.0f,  1.0f, splits_end_ndc[c], 1.0f},
692                         { 1.0f,  1.0f, splits_end_ndc[c], 1.0f}
693                 };
694
695                 /* Transform them into world space */
696                 for (int i = 0; i < 8; ++i)     {
697                         mul_m4_v4(persinv, corners[i]);
698                         mul_v3_fl(corners[i], 1.0f / corners[i][3]);
699                         corners[i][3] = 1.0f;
700                 }
701
702
703                 /* Project them into light space */
704                 invert_m4_m4(viewmat, ob->obmat);
705                 normalize_v3(viewmat[0]);
706                 normalize_v3(viewmat[1]);
707                 normalize_v3(viewmat[2]);
708
709                 for (int i = 0; i < 8; ++i)     {
710                         mul_m4_v4(viewmat, corners[i]);
711                 }
712
713                 float center[3];
714                 frustum_min_bounding_sphere(corners, center, &(sh_data->radius[c]));
715
716                 /* Snap projection center to nearest texel to cancel shimmering. */
717                 float shadow_origin[2], shadow_texco[2];
718                 mul_v2_v2fl(shadow_origin, center, linfo->shadow_size / (2.0f * sh_data->radius[c])); /* Light to texture space. */
719
720                 /* Find the nearest texel. */
721                 shadow_texco[0] = round(shadow_origin[0]);
722                 shadow_texco[1] = round(shadow_origin[1]);
723
724                 /* Compute offset. */
725                 sub_v2_v2(shadow_texco, shadow_origin);
726                 mul_v2_fl(shadow_texco, (2.0f * sh_data->radius[c]) / linfo->shadow_size); /* Texture to light space. */
727
728                 /* Apply offset. */
729                 add_v2_v2(center, shadow_texco);
730
731                 /* Expand the projection to cover frustum range */
732                 orthographic_m4(projmat,
733                                 center[0] - sh_data->radius[c],
734                                 center[0] + sh_data->radius[c],
735                                 center[1] - sh_data->radius[c],
736                                 center[1] + sh_data->radius[c],
737                                 la->clipsta, la->clipend);
738
739                 mul_m4_m4m4(sh_data->viewprojmat[c], projmat, viewmat);
740                 mul_m4_m4m4(cascade_data->shadowmat[c], texcomat, sh_data->viewprojmat[c]);
741         }
742
743         ubo_data->bias = 0.05f * la->bias;
744         ubo_data->near = la->clipsta;
745         ubo_data->far = la->clipend;
746         ubo_data->exp = (linfo->shadow_method == SHADOW_VSM) ? la->bleedbias : la->bleedexp;
747
748         evli->shadowid = (float)(sh_data->shadow_id);
749         ubo_data->shadow_start = (float)(sh_data->layer_id);
750         ubo_data->data_start = (float)(sh_data->cascade_id);
751         ubo_data->multi_shadow_count = (float)(sh_nbr);
752 }
753
754 /* Used for checking if object is inside the shadow volume. */
755 static bool cube_bbox_intersect(const float cube_center[3], float cube_half_dim, const BoundBox *bb, float (*obmat)[4])
756 {
757         float min[3], max[4], tmp[4][4];
758         unit_m4(tmp);
759         translate_m4(tmp, -cube_center[0], -cube_center[1], -cube_center[2]);
760         mul_m4_m4m4(tmp, tmp, obmat);
761
762         /* Just simple AABB intersection test in world space. */
763         INIT_MINMAX(min, max);
764         for (int i = 0; i < 8; ++i) {
765                 float vec[3];
766                 copy_v3_v3(vec, bb->vec[i]);
767                 mul_m4_v3(tmp, vec);
768                 minmax_v3v3_v3(min, max, vec);
769         }
770
771     if (MAX3(max[0], max[1], max[2]) < -cube_half_dim) return false;
772     if (MIN3(min[0], min[1], min[2]) >  cube_half_dim) return false;
773
774         return true;
775 }
776
777 static ShadowCaster *search_object_in_list(ListBase *list, Object *ob)
778 {
779         for (ShadowCaster *ldata = list->first; ldata; ldata = ldata->next) {
780                 if (ldata->ob == ob)
781                         return ldata;
782         }
783
784         return NULL;
785 }
786
787 static void delete_pruned_shadowcaster(EEVEE_LampEngineData *led)
788 {
789         ShadowCaster *next;
790         for (ShadowCaster *ldata = led->shadow_caster_list.first; ldata; ldata = next) {
791                 next = ldata->next;
792                 if (ldata->prune == true) {
793                         led->need_update = true;
794                         BLI_freelinkN(&led->shadow_caster_list, ldata);
795                 }
796         }
797 }
798
799 static void light_tag_shadow_update(Object *lamp, Object *ob)
800 {
801         Lamp *la = lamp->data;
802         EEVEE_LampEngineData *led = EEVEE_lamp_data_get(lamp);
803
804         bool is_inside_range = cube_bbox_intersect(lamp->obmat[3], la->clipend, BKE_object_boundbox_get(ob), ob->obmat);
805         ShadowCaster *ldata = search_object_in_list(&led->shadow_caster_list, ob);
806
807         if (is_inside_range) {
808                 if (ldata == NULL) {
809                         /* Object was not a shadow caster previously but is now. Add it. */
810                         ldata = MEM_callocN(sizeof(ShadowCaster), "ShadowCaster");
811                         ldata->ob = ob;
812                         BLI_addtail(&led->shadow_caster_list, ldata);
813                         led->need_update = true;
814                 }
815                 else {
816                         EEVEE_ObjectEngineData *oedata = EEVEE_object_data_get(ob);
817                         if (oedata->need_update) {
818                                 led->need_update = true;
819                         }
820                 }
821                 ldata->prune = false;
822         }
823         else if (ldata != NULL) {
824                 /* Object was a shadow caster previously and is not anymore. Remove it. */
825                 led->need_update = true;
826                 BLI_freelinkN(&led->shadow_caster_list, ldata);
827         }
828 }
829
830 static void eevee_lights_shcaster_updated(EEVEE_SceneLayerData *sldata, Object *ob)
831 {
832         Object *lamp;
833         EEVEE_LampsInfo *linfo = sldata->lamps;
834
835         /* Iterate over all shadow casting lamps to see if
836          * each of them needs update because of this object */
837         for (int i = 0; (lamp = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
838                 light_tag_shadow_update(lamp, ob);
839         }
840 }
841
842 void EEVEE_lights_update(EEVEE_SceneLayerData *sldata)
843 {
844         EEVEE_LampsInfo *linfo = sldata->lamps;
845         Object *ob;
846         int i;
847
848         /* Prune shadow casters to remove if object does not exists anymore (unprune them if object exists) */
849         Object *lamp;
850         for (i = 0; (lamp = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
851                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(lamp);
852
853                 if ((linfo->update_flag & LIGHT_UPDATE_SHADOW_CUBE) != 0) {
854                         led->need_update = true;
855                 }
856
857                 for (ShadowCaster *ldata = led->shadow_caster_list.first; ldata; ldata = ldata->next) {
858                         ldata->prune = true;
859                 }
860         }
861
862         for (LinkData *ldata = sldata->shadow_casters.first; ldata; ldata = ldata->next) {
863                 eevee_lights_shcaster_updated(sldata, ldata->data);
864         }
865
866         for (i = 0; (ob = linfo->light_ref[i]) && (i < MAX_LIGHT); i++) {
867                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
868                 eevee_light_setup(ob, linfo, led);
869         }
870
871         for (i = 0; (ob = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
872                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
873                 eevee_shadow_cube_setup(ob, linfo, led);
874                 delete_pruned_shadowcaster(led);
875         }
876 }
877
878 /* this refresh lamps shadow buffers */
879 void EEVEE_draw_shadows(EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl)
880 {
881         EEVEE_LampsInfo *linfo = sldata->lamps;
882         Object *ob;
883         int i;
884         float clear_col[4] = {FLT_MAX};
885
886         /* Cube Shadow Maps */
887         DRW_stats_group_start("Cube Shadow Maps");
888         DRW_framebuffer_texture_attach(sldata->shadow_target_fb, sldata->shadow_cube_target, 0, 0);
889         /* Render each shadow to one layer of the array */
890         for (i = 0; (ob = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
891                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
892                 Lamp *la = (Lamp *)ob->data;
893
894                 float cube_projmat[4][4];
895                 perspective_m4(cube_projmat, -la->clipsta, la->clipsta, -la->clipsta, la->clipsta, la->clipsta, la->clipend);
896
897                 if (led->need_update) {
898                         EEVEE_ShadowRender *srd = &linfo->shadow_render_data;
899
900                         srd->clip_near = la->clipsta;
901                         srd->clip_far = la->clipend;
902                         copy_v3_v3(srd->position, ob->obmat[3]);
903                         for (int j = 0; j < 6; j++) {
904                                 float tmp[4][4];
905
906                                 unit_m4(tmp);
907                                 negate_v3_v3(tmp[3], ob->obmat[3]);
908                                 mul_m4_m4m4(srd->viewmat[j], cubefacemat[j], tmp);
909
910                                 mul_m4_m4m4(srd->shadowmat[j], cube_projmat, srd->viewmat[j]);
911                         }
912                         DRW_uniformbuffer_update(sldata->shadow_render_ubo, srd);
913
914                         DRW_framebuffer_bind(sldata->shadow_target_fb);
915                         DRW_framebuffer_clear(true, true, false, clear_col, 1.0f);
916
917                         /* Render shadow cube */
918                         DRW_draw_pass(psl->shadow_cube_pass);
919
920                         /* 0.001f is arbitrary, but it should be relatively small so that filter size is not too big. */
921                         float filter_texture_size = la->soft * 0.001f;
922                         float filter_pixel_size = ceil(filter_texture_size / linfo->shadow_render_data.cube_texel_size);
923                         linfo->filter_size = linfo->shadow_render_data.cube_texel_size * ((filter_pixel_size > 1.0f) ? 1.5f : 0.0f);
924
925                         /* TODO: OPTI: Filter all faces in one/two draw call */
926                         for (linfo->current_shadow_face = 0;
927                              linfo->current_shadow_face < 6;
928                              linfo->current_shadow_face++)
929                         {
930                                 /* Copy using a small 3x3 box filter */
931                                 DRW_framebuffer_cubeface_attach(sldata->shadow_store_fb, sldata->shadow_cube_blur, 0, linfo->current_shadow_face, 0);
932                                 DRW_framebuffer_bind(sldata->shadow_store_fb);
933                                 DRW_draw_pass(psl->shadow_cube_copy_pass);
934                                 DRW_framebuffer_texture_detach(sldata->shadow_cube_blur);
935                         }
936
937                         /* Push it to shadowmap array */
938
939                         /* Adjust constants if concentric samples change. */
940                         const float max_filter_size = 7.5f;
941                         const float previous_box_filter_size = 9.0f; /* Dunno why but that works. */
942                         const int max_sample = 256;
943
944                         if (filter_pixel_size > 2.0f) {
945                                 linfo->filter_size = linfo->shadow_render_data.cube_texel_size * max_filter_size * previous_box_filter_size;
946                                 filter_pixel_size = max_ff(0.0f, filter_pixel_size - 3.0f);
947                                 /* Compute number of concentric samples. Depends directly on filter size. */
948                                 float pix_size_sqr = filter_pixel_size * filter_pixel_size;
949                                 srd->shadow_samples_ct = min_ii(max_sample, 4 + 8 * (int)filter_pixel_size + 4 * (int)(pix_size_sqr));
950                         }
951                         else {
952                                 linfo->filter_size = 0.0f;
953                                 srd->shadow_samples_ct = 4;
954                         }
955                         srd->shadow_inv_samples_ct = 1.0f / (float)srd->shadow_samples_ct;
956                         DRW_uniformbuffer_update(sldata->shadow_render_ubo, srd);
957
958                         DRW_framebuffer_texture_layer_attach(sldata->shadow_store_fb, sldata->shadow_pool, 0, i, 0);
959                         DRW_framebuffer_bind(sldata->shadow_store_fb);
960                         DRW_draw_pass(psl->shadow_cube_store_pass);
961
962                         led->need_update = false;
963                 }
964         }
965         linfo->update_flag &= ~LIGHT_UPDATE_SHADOW_CUBE;
966
967         DRW_framebuffer_texture_detach(sldata->shadow_cube_target);
968         DRW_stats_group_end();
969
970         /* Cascaded Shadow Maps */
971         DRW_stats_group_start("Cascaded Shadow Maps");
972         DRW_framebuffer_texture_attach(sldata->shadow_target_fb, sldata->shadow_cascade_target, 0, 0);
973         for (i = 0; (ob = linfo->shadow_cascade_ref[i]) && (i < MAX_SHADOW_CASCADE); i++) {
974                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
975                 Lamp *la = (Lamp *)ob->data;
976
977                 EEVEE_ShadowCascadeData *evscd = (EEVEE_ShadowCascadeData *)led->storage;
978                 EEVEE_ShadowRender *srd = &linfo->shadow_render_data;
979
980                 eevee_shadow_cascade_setup(ob, linfo, led);
981
982                 srd->clip_near = la->clipsta;
983                 srd->clip_far = la->clipend;
984                 for (int j = 0; j < la->cascade_count; ++j) {
985                         copy_m4_m4(srd->shadowmat[j], evscd->viewprojmat[j]);
986                 }
987                 DRW_uniformbuffer_update(sldata->shadow_render_ubo, &linfo->shadow_render_data);
988
989                 DRW_framebuffer_bind(sldata->shadow_target_fb);
990                 DRW_framebuffer_clear(false, true, false, NULL, 1.0);
991
992                 /* Render shadow cascades */
993                 DRW_draw_pass(psl->shadow_cascade_pass);
994
995                 /* TODO: OPTI: Filter all cascade in one/two draw call */
996                 for (linfo->current_shadow_cascade = 0;
997                      linfo->current_shadow_cascade < la->cascade_count;
998                      ++linfo->current_shadow_cascade)
999                 {
1000                         /* 0.01f factor to convert to percentage */
1001                         float filter_texture_size = la->soft * 0.01f / evscd->radius[linfo->current_shadow_cascade];
1002                         float filter_pixel_size = ceil(linfo->shadow_size * filter_texture_size);
1003
1004                         /* Copy using a small 3x3 box filter */
1005                         linfo->filter_size = linfo->shadow_render_data.stored_texel_size * ((filter_pixel_size > 1.0f) ? 1.0f : 0.0f);
1006                         DRW_framebuffer_texture_layer_attach(sldata->shadow_store_fb, sldata->shadow_cascade_blur, 0, linfo->current_shadow_cascade, 0);
1007                         DRW_framebuffer_bind(sldata->shadow_store_fb);
1008                         DRW_draw_pass(psl->shadow_cascade_copy_pass);
1009                         DRW_framebuffer_texture_detach(sldata->shadow_cascade_blur);
1010
1011                         /* Push it to shadowmap array and blur more */
1012
1013                         /* Adjust constants if concentric samples change. */
1014                         const float max_filter_size = 7.5f;
1015                         const float previous_box_filter_size = 3.2f; /* Arbitrary: less banding */
1016                         const int max_sample = 256;
1017
1018                         if (filter_pixel_size > 2.0f) {
1019                                 linfo->filter_size = linfo->shadow_render_data.stored_texel_size * max_filter_size * previous_box_filter_size;
1020                                 filter_pixel_size = max_ff(0.0f, filter_pixel_size - 3.0f);
1021                                 /* Compute number of concentric samples. Depends directly on filter size. */
1022                                 float pix_size_sqr = filter_pixel_size * filter_pixel_size;
1023                                 srd->shadow_samples_ct = min_ii(max_sample, 4 + 8 * (int)filter_pixel_size + 4 * (int)(pix_size_sqr));
1024                         }
1025                         else {
1026                                 linfo->filter_size = 0.0f;
1027                                 srd->shadow_samples_ct = 4;
1028                         }
1029                         srd->shadow_inv_samples_ct = 1.0f / (float)srd->shadow_samples_ct;
1030                         DRW_uniformbuffer_update(sldata->shadow_render_ubo, &linfo->shadow_render_data);
1031
1032                         int layer = evscd->layer_id + linfo->current_shadow_cascade;
1033                         DRW_framebuffer_texture_layer_attach(sldata->shadow_store_fb, sldata->shadow_pool, 0, layer, 0);
1034                         DRW_framebuffer_bind(sldata->shadow_store_fb);
1035                         DRW_draw_pass(psl->shadow_cascade_store_pass);
1036                 }
1037         }
1038
1039         DRW_framebuffer_texture_detach(sldata->shadow_cascade_target);
1040         DRW_stats_group_end();
1041
1042         DRW_uniformbuffer_update(sldata->light_ubo, &linfo->light_data);
1043         DRW_uniformbuffer_update(sldata->shadow_ubo, &linfo->shadow_data); /* Update all data at once */
1044 }
1045
1046 void EEVEE_lights_free(void)
1047 {
1048         DRW_SHADER_FREE_SAFE(e_data.shadow_sh);
1049         for (int i = 0; i < SHADOW_METHOD_MAX; ++i) {
1050                 DRW_SHADER_FREE_SAFE(e_data.shadow_store_cube_sh[i]);
1051                 DRW_SHADER_FREE_SAFE(e_data.shadow_store_cascade_sh[i]);
1052                 DRW_SHADER_FREE_SAFE(e_data.shadow_copy_cube_sh[i]);
1053                 DRW_SHADER_FREE_SAFE(e_data.shadow_copy_cascade_sh[i]);
1054         }
1055 }