Cleanup: style, duplicate header
[blender.git] / source / blender / draw / engines / eevee / eevee_lightprobes.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_lightprobes.c
23  *  \ingroup draw_engine
24  */
25
26 #include "DRW_render.h"
27
28 #include "BLI_utildefines.h"
29 #include "BLI_string_utils.h"
30 #include "BLI_rand.h"
31
32 #include "DNA_world_types.h"
33 #include "DNA_texture_types.h"
34 #include "DNA_image_types.h"
35 #include "DNA_lightprobe_types.h"
36 #include "DNA_view3d_types.h"
37
38 #include "BKE_collection.h"
39 #include "BKE_object.h"
40 #include "MEM_guardedalloc.h"
41
42 #include "GPU_material.h"
43 #include "GPU_texture.h"
44 #include "GPU_glew.h"
45
46 #include "DEG_depsgraph_query.h"
47
48 #include "eevee_engine.h"
49 #include "eevee_lightcache.h"
50 #include "eevee_private.h"
51
52 #include "ED_screen.h"
53
54 #include "WM_api.h"
55 #include "WM_types.h"
56
57 #define HAMMERSLEY_SIZE 1024
58
59 static struct {
60         struct GPUShader *probe_default_sh;
61         struct GPUShader *probe_default_studiolight_sh;
62         struct GPUShader *probe_filter_glossy_sh;
63         struct GPUShader *probe_filter_diffuse_sh;
64         struct GPUShader *probe_filter_visibility_sh;
65         struct GPUShader *probe_grid_fill_sh;
66         struct GPUShader *probe_grid_display_sh;
67         struct GPUShader *probe_planar_display_sh;
68         struct GPUShader *probe_planar_downsample_sh;
69         struct GPUShader *probe_cube_display_sh;
70
71         struct GPUTexture *hammersley;
72         struct GPUTexture *planar_pool_placeholder;
73         struct GPUTexture *depth_placeholder;
74         struct GPUTexture *depth_array_placeholder;
75         struct GPUTexture *cube_face_minmaxz;
76
77         struct Gwn_VertFormat *format_probe_display_cube;
78         struct Gwn_VertFormat *format_probe_display_planar;
79 } e_data = {NULL}; /* Engine data */
80
81 extern char datatoc_background_vert_glsl[];
82 extern char datatoc_default_world_frag_glsl[];
83 extern char datatoc_lightprobe_filter_glossy_frag_glsl[];
84 extern char datatoc_lightprobe_filter_diffuse_frag_glsl[];
85 extern char datatoc_lightprobe_filter_visibility_frag_glsl[];
86 extern char datatoc_lightprobe_geom_glsl[];
87 extern char datatoc_lightprobe_vert_glsl[];
88 extern char datatoc_lightprobe_planar_display_frag_glsl[];
89 extern char datatoc_lightprobe_planar_display_vert_glsl[];
90 extern char datatoc_lightprobe_planar_downsample_frag_glsl[];
91 extern char datatoc_lightprobe_planar_downsample_geom_glsl[];
92 extern char datatoc_lightprobe_planar_downsample_vert_glsl[];
93 extern char datatoc_lightprobe_cube_display_frag_glsl[];
94 extern char datatoc_lightprobe_cube_display_vert_glsl[];
95 extern char datatoc_lightprobe_grid_display_frag_glsl[];
96 extern char datatoc_lightprobe_grid_display_vert_glsl[];
97 extern char datatoc_lightprobe_grid_fill_frag_glsl[];
98 extern char datatoc_irradiance_lib_glsl[];
99 extern char datatoc_lightprobe_lib_glsl[];
100 extern char datatoc_octahedron_lib_glsl[];
101 extern char datatoc_bsdf_common_lib_glsl[];
102 extern char datatoc_common_uniforms_lib_glsl[];
103 extern char datatoc_common_view_lib_glsl[];
104 extern char datatoc_bsdf_sampling_lib_glsl[];
105
106 extern GlobalsUboStorage ts;
107
108 /* *********** FUNCTIONS *********** */
109
110 /* TODO find a better way than this. This does not support dupli objects if
111  * the original object is hidden. */
112 bool EEVEE_lightprobes_obj_visibility_cb(bool vis_in, void *user_data)
113 {
114         EEVEE_ObjectEngineData *oed = (EEVEE_ObjectEngineData *)user_data;
115
116         /* test disabled if group is NULL */
117         if (oed->test_data->collection == NULL)
118                 return vis_in;
119
120         if (oed->test_data->cached == false)
121                 oed->ob_vis_dirty = true;
122
123         /* early out, don't need to compute ob_vis yet. */
124         if (vis_in == false)
125                 return vis_in;
126
127         if (oed->ob_vis_dirty) {
128                 oed->ob_vis_dirty = false;
129                 oed->ob_vis = BKE_collection_has_object_recursive(oed->test_data->collection, oed->ob);
130                 oed->ob_vis = (oed->test_data->invert) ? !oed->ob_vis : oed->ob_vis;
131         }
132
133         return vis_in && oed->ob_vis;
134 }
135
136 static struct GPUTexture *create_hammersley_sample_texture(int samples)
137 {
138         struct GPUTexture *tex;
139         float (*texels)[2] = MEM_mallocN(sizeof(float[2]) * samples, "hammersley_tex");
140         int i;
141
142         for (i = 0; i < samples; i++) {
143                 double dphi;
144                 BLI_hammersley_1D(i, &dphi);
145                 float phi = (float)dphi * 2.0f * M_PI;
146                 texels[i][0] = cosf(phi);
147                 texels[i][1] = sinf(phi);
148         }
149
150         tex = DRW_texture_create_1D(samples, GPU_RG16F, DRW_TEX_WRAP, (float *)texels);
151         MEM_freeN(texels);
152         return tex;
153 }
154
155 static void planar_pool_ensure_alloc(EEVEE_Data *vedata, int num_planar_ref)
156 {
157         EEVEE_TextureList *txl = vedata->txl;
158
159         /* XXX TODO OPTIMISATION : This is a complete waist of texture memory.
160          * Instead of allocating each planar probe for each viewport,
161          * only alloc them once using the biggest viewport resolution. */
162         const float *viewport_size = DRW_viewport_size_get();
163
164         /* TODO get screen percentage from layer setting */
165         // const DRWContextState *draw_ctx = DRW_context_state_get();
166         // ViewLayer *view_layer = draw_ctx->view_layer;
167         float screen_percentage = 1.0f;
168
169         int width = (int)(viewport_size[0] * screen_percentage);
170         int height = (int)(viewport_size[1] * screen_percentage);
171
172         /* We need an Array texture so allocate it ourself */
173         if (!txl->planar_pool) {
174                 if (num_planar_ref > 0) {
175                         txl->planar_pool = DRW_texture_create_2D_array(width, height, max_ff(1, num_planar_ref),
176                                                                          GPU_R11F_G11F_B10F, DRW_TEX_FILTER | DRW_TEX_MIPMAP, NULL);
177                         txl->planar_depth = DRW_texture_create_2D_array(width, height, max_ff(1, num_planar_ref),
178                                                                         GPU_DEPTH_COMPONENT24, 0, NULL);
179                 }
180                 else if (num_planar_ref == 0) {
181                         /* Makes Opengl Happy : Create a placeholder texture that will never be sampled but still bound to shader. */
182                         txl->planar_pool = DRW_texture_create_2D_array(1, 1, 1, GPU_RGBA8, DRW_TEX_FILTER | DRW_TEX_MIPMAP, NULL);
183                         txl->planar_depth = DRW_texture_create_2D_array(1, 1, 1, GPU_DEPTH_COMPONENT24, 0, NULL);
184                 }
185         }
186 }
187
188 static void lightprobe_shaders_init(void)
189 {
190         const char *filter_defines = "#define HAMMERSLEY_SIZE " STRINGIFY(HAMMERSLEY_SIZE) "\n"
191 #if defined(IRRADIANCE_SH_L2)
192                                      "#define IRRADIANCE_SH_L2\n"
193 #elif defined(IRRADIANCE_CUBEMAP)
194                                      "#define IRRADIANCE_CUBEMAP\n"
195 #elif defined(IRRADIANCE_HL2)
196                                      "#define IRRADIANCE_HL2\n"
197 #endif
198                                      "#define NOISE_SIZE 64\n";
199
200         char *shader_str = NULL;
201         char *vert_str = NULL;
202
203         shader_str = BLI_string_joinN(
204                 datatoc_common_view_lib_glsl,
205                 datatoc_common_uniforms_lib_glsl,
206                 datatoc_bsdf_common_lib_glsl,
207                 datatoc_bsdf_sampling_lib_glsl,
208                 datatoc_lightprobe_filter_glossy_frag_glsl);
209
210         e_data.probe_filter_glossy_sh = DRW_shader_create(
211                 datatoc_lightprobe_vert_glsl, datatoc_lightprobe_geom_glsl, shader_str, filter_defines);
212
213         e_data.probe_default_sh = DRW_shader_create(
214                 datatoc_background_vert_glsl, NULL, datatoc_default_world_frag_glsl, NULL);
215
216         e_data.probe_default_studiolight_sh = DRW_shader_create(
217                 datatoc_background_vert_glsl, NULL, datatoc_default_world_frag_glsl, "#define LOOKDEV\n");
218
219         MEM_freeN(shader_str);
220
221         shader_str = BLI_string_joinN(
222                 datatoc_common_view_lib_glsl,
223                 datatoc_common_uniforms_lib_glsl,
224                 datatoc_bsdf_common_lib_glsl,
225                 datatoc_bsdf_sampling_lib_glsl,
226                 datatoc_lightprobe_filter_diffuse_frag_glsl);
227
228         e_data.probe_filter_diffuse_sh = DRW_shader_create_fullscreen(shader_str, filter_defines);
229
230         MEM_freeN(shader_str);
231
232         shader_str = BLI_string_joinN(
233                 datatoc_common_view_lib_glsl,
234                 datatoc_common_uniforms_lib_glsl,
235                 datatoc_bsdf_common_lib_glsl,
236                 datatoc_bsdf_sampling_lib_glsl,
237                 datatoc_lightprobe_filter_visibility_frag_glsl);
238
239         e_data.probe_filter_visibility_sh = DRW_shader_create_fullscreen(shader_str, filter_defines);
240
241         MEM_freeN(shader_str);
242
243         shader_str = BLI_string_joinN(
244                 datatoc_octahedron_lib_glsl,
245                 datatoc_common_view_lib_glsl,
246                 datatoc_common_uniforms_lib_glsl,
247                 datatoc_bsdf_common_lib_glsl,
248                 datatoc_irradiance_lib_glsl,
249                 datatoc_lightprobe_lib_glsl,
250                 datatoc_lightprobe_grid_display_frag_glsl);
251
252         vert_str = BLI_string_joinN(
253                 datatoc_common_view_lib_glsl,
254                 datatoc_lightprobe_grid_display_vert_glsl);
255
256         e_data.probe_grid_display_sh = DRW_shader_create(vert_str, NULL, shader_str, filter_defines);
257
258         MEM_freeN(vert_str);
259         MEM_freeN(shader_str);
260
261         e_data.probe_grid_fill_sh = DRW_shader_create_fullscreen(
262                 datatoc_lightprobe_grid_fill_frag_glsl, filter_defines);
263
264         shader_str = BLI_string_joinN(
265                 datatoc_octahedron_lib_glsl,
266                 datatoc_common_view_lib_glsl,
267                 datatoc_common_uniforms_lib_glsl,
268                 datatoc_bsdf_common_lib_glsl,
269                 datatoc_lightprobe_lib_glsl,
270                 datatoc_lightprobe_cube_display_frag_glsl);
271
272         vert_str = BLI_string_joinN(
273                 datatoc_common_view_lib_glsl,
274                 datatoc_lightprobe_cube_display_vert_glsl);
275
276         e_data.probe_cube_display_sh = DRW_shader_create(vert_str, NULL, shader_str, SHADER_DEFINES);
277
278         MEM_freeN(vert_str);
279         MEM_freeN(shader_str);
280
281         vert_str = BLI_string_joinN(
282                 datatoc_common_view_lib_glsl,
283                 datatoc_lightprobe_planar_display_vert_glsl);
284
285         shader_str = BLI_string_joinN(
286                 datatoc_common_view_lib_glsl,
287                 datatoc_lightprobe_planar_display_frag_glsl);
288
289         e_data.probe_planar_display_sh = DRW_shader_create(vert_str, NULL, shader_str, NULL);
290
291         MEM_freeN(vert_str);
292         MEM_freeN(shader_str);
293
294         e_data.probe_planar_downsample_sh = DRW_shader_create(
295                 datatoc_lightprobe_planar_downsample_vert_glsl,
296                 datatoc_lightprobe_planar_downsample_geom_glsl,
297                 datatoc_lightprobe_planar_downsample_frag_glsl,
298                 NULL);
299
300         e_data.hammersley = create_hammersley_sample_texture(HAMMERSLEY_SIZE);
301 }
302
303 void EEVEE_lightprobes_init(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
304 {
305         EEVEE_CommonUniformBuffer *common_data = &sldata->common_data;
306         EEVEE_StorageList *stl = vedata->stl;
307
308         const DRWContextState *draw_ctx = DRW_context_state_get();
309         const Scene *scene_eval = DEG_get_evaluated_scene(draw_ctx->depsgraph);
310
311         if (!e_data.probe_filter_glossy_sh) {
312                 lightprobe_shaders_init();
313         }
314
315         if ((scene_eval->eevee.light_cache == NULL) &&
316             (sldata->fallback_lightcache == NULL))
317         {
318 #if defined(IRRADIANCE_SH_L2)
319                 int grid_res = 4;
320 #elif defined(IRRADIANCE_CUBEMAP)
321                 int grid_res = 8;
322 #elif defined(IRRADIANCE_HL2)
323                 int grid_res = 4;
324 #endif
325                 int cube_res = OCTAHEDRAL_SIZE_FROM_CUBESIZE(scene_eval->eevee.gi_cubemap_resolution);
326                 int vis_res = scene_eval->eevee.gi_visibility_resolution;
327
328                 sldata->fallback_lightcache = EEVEE_lightcache_create(1, 1, cube_res, vis_res, (int[3]){grid_res, grid_res, 1});
329         }
330
331         stl->g_data->light_cache = (scene_eval->eevee.light_cache) ? scene_eval->eevee.light_cache : sldata->fallback_lightcache;
332
333         EEVEE_lightcache_load(stl->g_data->light_cache);
334
335         if (!sldata->probes) {
336                 sldata->probes = MEM_callocN(sizeof(EEVEE_LightProbesInfo), "EEVEE_LightProbesInfo");
337                 sldata->probe_ubo = DRW_uniformbuffer_create(sizeof(EEVEE_LightProbe) * MAX_PROBE, NULL);
338                 sldata->grid_ubo = DRW_uniformbuffer_create(sizeof(EEVEE_LightGrid) * MAX_GRID, NULL);
339                 sldata->planar_ubo = DRW_uniformbuffer_create(sizeof(EEVEE_PlanarReflection) * MAX_PLANAR, NULL);
340         }
341
342         common_data->prb_num_planar = 0;
343         common_data->prb_num_render_cube = 1;
344         common_data->prb_num_render_grid = 1;
345
346         common_data->spec_toggle = true;
347         common_data->ssr_toggle = true;
348         common_data->sss_toggle = true;
349
350         /* Placeholder planar pool: used when rendering planar reflections (avoid dependency loop). */
351         if (!e_data.planar_pool_placeholder) {
352                 e_data.planar_pool_placeholder = DRW_texture_create_2D_array(1, 1, 1, GPU_RGBA8, DRW_TEX_FILTER, NULL);
353         }
354 }
355
356 /* Only init the passes usefull for rendering the light cache. */
357 void EEVEE_lightbake_cache_init(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata, GPUTexture *rt_color, GPUTexture *rt_depth)
358 {
359         EEVEE_PassList *psl = vedata->psl;
360         LightCache *light_cache = vedata->stl->g_data->light_cache;
361         EEVEE_LightProbesInfo *pinfo = sldata->probes;
362
363         {
364                 psl->probe_glossy_compute = DRW_pass_create("LightProbe Glossy Compute", DRW_STATE_WRITE_COLOR);
365
366                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.probe_filter_glossy_sh, psl->probe_glossy_compute);
367                 DRW_shgroup_uniform_float(grp, "intensityFac", &pinfo->intensity_fac, 1);
368                 DRW_shgroup_uniform_float(grp, "sampleCount", &pinfo->samples_len, 1);
369                 DRW_shgroup_uniform_float(grp, "invSampleCount", &pinfo->samples_len_inv, 1);
370                 DRW_shgroup_uniform_float(grp, "roughnessSquared", &pinfo->roughness, 1);
371                 DRW_shgroup_uniform_float(grp, "lodFactor", &pinfo->lodfactor, 1);
372                 DRW_shgroup_uniform_float(grp, "lodMax", &pinfo->lod_rt_max, 1);
373                 DRW_shgroup_uniform_float(grp, "texelSize", &pinfo->texel_size, 1);
374                 DRW_shgroup_uniform_float(grp, "paddingSize", &pinfo->padding_size, 1);
375                 DRW_shgroup_uniform_int(grp, "Layer", &pinfo->layer, 1);
376                 DRW_shgroup_uniform_texture(grp, "texHammersley", e_data.hammersley);
377                 // DRW_shgroup_uniform_texture(grp, "texJitter", e_data.jitter);
378                 DRW_shgroup_uniform_texture(grp, "probeHdr", rt_color);
379                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
380         }
381
382         {
383                 psl->probe_diffuse_compute = DRW_pass_create("LightProbe Diffuse Compute", DRW_STATE_WRITE_COLOR);
384
385                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.probe_filter_diffuse_sh, psl->probe_diffuse_compute);
386 #ifdef IRRADIANCE_SH_L2
387                 DRW_shgroup_uniform_int(grp, "probeSize", &pinfo->shres, 1);
388 #else
389                 DRW_shgroup_uniform_float(grp, "sampleCount", &pinfo->samples_len, 1);
390                 DRW_shgroup_uniform_float(grp, "invSampleCount", &pinfo->samples_len_inv, 1);
391                 DRW_shgroup_uniform_float(grp, "lodFactor", &pinfo->lodfactor, 1);
392                 DRW_shgroup_uniform_float(grp, "lodMax", &pinfo->lod_rt_max, 1);
393                 DRW_shgroup_uniform_texture(grp, "texHammersley", e_data.hammersley);
394 #endif
395                 DRW_shgroup_uniform_float(grp, "intensityFac", &pinfo->intensity_fac, 1);
396                 DRW_shgroup_uniform_texture(grp, "probeHdr", rt_color);
397
398                 struct Gwn_Batch *geom = DRW_cache_fullscreen_quad_get();
399                 DRW_shgroup_call_add(grp, geom, NULL);
400         }
401
402         {
403                 psl->probe_visibility_compute = DRW_pass_create("LightProbe Visibility Compute", DRW_STATE_WRITE_COLOR);
404
405                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.probe_filter_visibility_sh, psl->probe_visibility_compute);
406                 DRW_shgroup_uniform_int(grp, "outputSize", &pinfo->shres, 1);
407                 DRW_shgroup_uniform_float(grp, "visibilityRange", &pinfo->visibility_range, 1);
408                 DRW_shgroup_uniform_float(grp, "visibilityBlur", &pinfo->visibility_blur, 1);
409                 DRW_shgroup_uniform_float(grp, "sampleCount", &pinfo->samples_len, 1);
410                 DRW_shgroup_uniform_float(grp, "invSampleCount", &pinfo->samples_len_inv, 1);
411                 DRW_shgroup_uniform_float(grp, "storedTexelSize", &pinfo->texel_size, 1);
412                 DRW_shgroup_uniform_float(grp, "nearClip", &pinfo->near_clip, 1);
413                 DRW_shgroup_uniform_float(grp, "farClip", &pinfo->far_clip, 1);
414                 DRW_shgroup_uniform_texture(grp, "texHammersley", e_data.hammersley);
415                 DRW_shgroup_uniform_texture(grp, "probeDepth", rt_depth);
416
417                 struct Gwn_Batch *geom = DRW_cache_fullscreen_quad_get();
418                 DRW_shgroup_call_add(grp, geom, NULL);
419         }
420
421         {
422                 psl->probe_grid_fill = DRW_pass_create("LightProbe Grid Floodfill", DRW_STATE_WRITE_COLOR);
423
424                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.probe_grid_fill_sh, psl->probe_grid_fill);
425                 DRW_shgroup_uniform_texture_ref(grp, "irradianceGrid", &light_cache->grid_tx.tex);
426
427                 struct Gwn_Batch *geom = DRW_cache_fullscreen_quad_get();
428                 DRW_shgroup_call_add(grp, geom, NULL);
429         }
430 }
431
432 void EEVEE_lightprobes_cache_init(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
433 {
434         EEVEE_TextureList *txl = vedata->txl;
435         EEVEE_PassList *psl = vedata->psl;
436         EEVEE_StorageList *stl = vedata->stl;
437         EEVEE_LightProbesInfo *pinfo = sldata->probes;
438         LightCache *lcache = stl->g_data->light_cache;
439         const DRWContextState *draw_ctx = DRW_context_state_get();
440         const Scene *scene_eval = DEG_get_evaluated_scene(draw_ctx->depsgraph);
441
442         pinfo->num_planar = 0;
443         pinfo->vis_data.collection = NULL;
444         pinfo->do_grid_update = false;
445         pinfo->do_cube_update = false;
446
447         {
448                 psl->probe_background = DRW_pass_create("World Probe Background Pass", DRW_STATE_WRITE_COLOR | DRW_STATE_DEPTH_EQUAL);
449
450                 struct Gwn_Batch *geom = DRW_cache_fullscreen_quad_get();
451                 DRWShadingGroup *grp = NULL;
452
453                 Scene *scene = draw_ctx->scene;
454                 World *wo = scene->world;
455
456                 float *col = ts.colorBackground;
457
458                 /* LookDev */
459                 EEVEE_lookdev_cache_init(vedata, &grp, e_data.probe_default_studiolight_sh, psl->probe_background, wo, pinfo);
460                 /* END */
461                 if (!grp && wo) {
462                         col = &wo->horr;
463
464                         if (wo->use_nodes && wo->nodetree) {
465                                 static float error_col[3] = {1.0f, 0.0f, 1.0f};
466                                 struct GPUMaterial *gpumat = EEVEE_material_world_lightprobe_get(scene, wo);
467
468                                 GPUMaterialStatus status = GPU_material_status(gpumat);
469
470                                 switch (status) {
471                                         case GPU_MAT_SUCCESS:
472                                                 grp = DRW_shgroup_material_create(gpumat, psl->probe_background);
473                                                 DRW_shgroup_uniform_float(grp, "backgroundAlpha", &stl->g_data->background_alpha, 1);
474                                                 DRW_shgroup_call_add(grp, geom, NULL);
475                                                 break;
476                                         default:
477                                                 col = error_col;
478                                                 break;
479                                 }
480                         }
481                 }
482
483                 /* Fallback if shader fails or if not using nodetree. */
484                 if (grp == NULL) {
485                         grp = DRW_shgroup_create(e_data.probe_default_sh, psl->probe_background);
486                         DRW_shgroup_uniform_vec3(grp, "color", col, 1);
487                         DRW_shgroup_uniform_float(grp, "backgroundAlpha", &stl->g_data->background_alpha, 1);
488                         DRW_shgroup_call_add(grp, geom, NULL);
489                 }
490         }
491
492         if (DRW_state_draw_support()) {
493                 DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CULL_BACK;
494                 psl->probe_display = DRW_pass_create("LightProbe Display", state);
495
496                 /* Cube Display */
497                 if (scene_eval->eevee.flag & SCE_EEVEE_SHOW_CUBEMAPS && lcache->cube_len > 1) {
498                         int cube_len = lcache->cube_len - 1; /* don't count the world. */
499                         DRWShadingGroup *grp = DRW_shgroup_empty_tri_batch_create(e_data.probe_cube_display_sh,
500                                                                                   psl->probe_display, cube_len * 2);
501                         DRW_shgroup_uniform_texture_ref(grp, "probeCubes", &lcache->cube_tx.tex);
502                         DRW_shgroup_uniform_block(grp, "probe_block", sldata->probe_ubo);
503                         DRW_shgroup_uniform_block(grp, "common_block", sldata->common_ubo);
504                         DRW_shgroup_uniform_vec3(grp, "screen_vecs[0]", DRW_viewport_screenvecs_get(), 2);
505                         DRW_shgroup_uniform_float_copy(grp, "sphere_size", scene_eval->eevee.gi_cubemap_draw_size * 0.5f);
506                 }
507
508                 /* Grid Display */
509                 if (scene_eval->eevee.flag & SCE_EEVEE_SHOW_IRRADIANCE) {
510                         EEVEE_LightGrid *egrid = lcache->grid_data + 1;
511                         for (int p = 1; p < lcache->grid_len; ++p, egrid++) {
512                                 DRWShadingGroup *shgrp = DRW_shgroup_create(e_data.probe_grid_display_sh, psl->probe_display);
513                                 DRW_shgroup_uniform_int(shgrp, "offset", &egrid->offset, 1);
514                                 DRW_shgroup_uniform_ivec3(shgrp, "grid_resolution", egrid->resolution, 1);
515                                 DRW_shgroup_uniform_vec3(shgrp, "corner", egrid->corner, 1);
516                                 DRW_shgroup_uniform_vec3(shgrp, "increment_x", egrid->increment_x, 1);
517                                 DRW_shgroup_uniform_vec3(shgrp, "increment_y", egrid->increment_y, 1);
518                                 DRW_shgroup_uniform_vec3(shgrp, "increment_z", egrid->increment_z, 1);
519                                 DRW_shgroup_uniform_vec3(shgrp, "screen_vecs[0]", DRW_viewport_screenvecs_get(), 2);
520                                 DRW_shgroup_uniform_texture_ref(shgrp, "irradianceGrid", &lcache->grid_tx.tex);
521                                 DRW_shgroup_uniform_float_copy(shgrp, "sphere_size", scene_eval->eevee.gi_irradiance_draw_size * 0.5f);
522                                 int tri_count = egrid->resolution[0] * egrid->resolution[1] * egrid->resolution[2] * 2;
523                                 DRW_shgroup_call_procedural_triangles_add(shgrp, tri_count, NULL);
524                         }
525                 }
526
527                 /* Planar Display */
528                 DRW_shgroup_instance_format(e_data.format_probe_display_planar, {
529                     {"probe_id", DRW_ATTRIB_INT, 1},
530                     {"probe_mat", DRW_ATTRIB_FLOAT, 16},
531                 });
532
533                 DRWShadingGroup *grp = DRW_shgroup_instance_create(
534                         e_data.probe_planar_display_sh,
535                         psl->probe_display,
536                         DRW_cache_quad_get(),
537                         e_data.format_probe_display_planar);
538                 stl->g_data->planar_display_shgrp = grp;
539                 DRW_shgroup_uniform_texture_ref(grp, "probePlanars", &txl->planar_pool);
540         }
541         else {
542                 stl->g_data->planar_display_shgrp = NULL;
543         }
544
545         {
546                 psl->probe_planar_downsample_ps = DRW_pass_create("LightProbe Planar Downsample", DRW_STATE_WRITE_COLOR);
547
548                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.probe_planar_downsample_sh, psl->probe_planar_downsample_ps);
549                 DRW_shgroup_uniform_texture_ref(grp, "source", &txl->planar_pool);
550                 DRW_shgroup_uniform_float(grp, "fireflyFactor", &sldata->common_data.ssr_firefly_fac, 1);
551                 DRW_shgroup_call_instances_add(grp, DRW_cache_fullscreen_quad_get(), NULL, (uint *)&pinfo->num_planar);
552         }
553 }
554
555 static bool eevee_lightprobes_culling_test(Object *ob)
556 {
557         LightProbe *probe = (LightProbe *)ob->data;
558
559         switch (probe->type) {
560                 case LIGHTPROBE_TYPE_PLANAR:
561                 {
562                         /* See if this planar probe is inside the view frustum. If not, no need to update it. */
563                         /* NOTE: this could be bypassed if we want feedback loop mirrors for rendering. */
564                         BoundBox bbox; float tmp[4][4];
565                         const float min[3] = {-1.0f, -1.0f, -1.0f};
566                         const float max[3] = { 1.0f,  1.0f,  1.0f};
567                         BKE_boundbox_init_from_minmax(&bbox, min, max);
568
569                         copy_m4_m4(tmp, ob->obmat);
570                         normalize_v3(tmp[2]);
571                         mul_v3_fl(tmp[2], probe->distinf);
572
573                         for (int v = 0; v < 8; ++v) {
574                                 mul_m4_v3(tmp, bbox.vec[v]);
575                         }
576                         return DRW_culling_box_test(&bbox);
577                 }
578                 case LIGHTPROBE_TYPE_CUBE:
579                         return true; /* TODO */
580                 case LIGHTPROBE_TYPE_GRID:
581                         return true; /* TODO */
582         }
583         BLI_assert(0);
584         return true;
585 }
586
587 void EEVEE_lightprobes_cache_add(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata, Object *ob)
588 {
589         EEVEE_LightProbesInfo *pinfo = sldata->probes;
590         LightProbe *probe = (LightProbe *)ob->data;
591
592         if ((probe->type == LIGHTPROBE_TYPE_CUBE && pinfo->num_cube >= MAX_PROBE) ||
593             (probe->type == LIGHTPROBE_TYPE_GRID && pinfo->num_grid >= MAX_PROBE) ||
594             (probe->type == LIGHTPROBE_TYPE_PLANAR && pinfo->num_planar >= MAX_PLANAR))
595         {
596                 printf("Too many probes in the view !!!\n");
597                 return;
598         }
599
600         if (probe->type == LIGHTPROBE_TYPE_PLANAR) {
601                 if (!eevee_lightprobes_culling_test(ob)) {
602                         return; /* Culled */
603                 }
604                 EEVEE_lightprobes_planar_data_from_object(ob,
605                                                           &pinfo->planar_data[pinfo->num_planar],
606                                                           &pinfo->planar_vis_tests[pinfo->num_planar]);
607                 /* Debug Display */
608                 DRWShadingGroup *grp = vedata->stl->g_data->planar_display_shgrp;
609                 if (grp && (probe->flag & LIGHTPROBE_FLAG_SHOW_DATA)) {
610                         DRW_shgroup_call_dynamic_add(grp, &pinfo->num_planar, ob->obmat);
611                 }
612
613                 pinfo->num_planar++;
614         }
615         else {
616                 EEVEE_LightProbeEngineData *ped = EEVEE_lightprobe_data_ensure(ob);
617                 if (ped->need_update) {
618                         if (probe->type == LIGHTPROBE_TYPE_GRID) {
619                                 pinfo->do_grid_update = true;
620                         }
621                         else {
622                                 pinfo->do_cube_update = true;
623                         }
624                         ped->need_update = false;
625                 }
626         }
627 }
628
629 void EEVEE_lightprobes_grid_data_from_object(Object *ob, EEVEE_LightGrid *egrid, int *offset)
630 {
631         LightProbe *probe = (LightProbe *)ob->data;
632
633         copy_v3_v3_int(egrid->resolution, &probe->grid_resolution_x);
634
635         /* Save current offset and advance it for the next grid. */
636         egrid->offset = *offset;
637         *offset += egrid->resolution[0] * egrid->resolution[1] * egrid->resolution[2];
638
639         /* Add one for level 0 */
640         float fac = 1.0f / max_ff(1e-8f, probe->falloff);
641         egrid->attenuation_scale = fac / max_ff(1e-8f, probe->distinf);
642         egrid->attenuation_bias = fac;
643
644         /* Update transforms */
645         float cell_dim[3], half_cell_dim[3];
646         cell_dim[0] = 2.0f / egrid->resolution[0];
647         cell_dim[1] = 2.0f / egrid->resolution[1];
648         cell_dim[2] = 2.0f / egrid->resolution[2];
649
650         mul_v3_v3fl(half_cell_dim, cell_dim, 0.5f);
651
652         /* Matrix converting world space to cell ranges. */
653         invert_m4_m4(egrid->mat, ob->obmat);
654
655         /* First cell. */
656         copy_v3_fl(egrid->corner, -1.0f);
657         add_v3_v3(egrid->corner, half_cell_dim);
658         mul_m4_v3(ob->obmat, egrid->corner);
659
660         /* Opposite neighbor cell. */
661         copy_v3_fl3(egrid->increment_x, cell_dim[0], 0.0f, 0.0f);
662         add_v3_v3(egrid->increment_x, half_cell_dim);
663         add_v3_fl(egrid->increment_x, -1.0f);
664         mul_m4_v3(ob->obmat, egrid->increment_x);
665         sub_v3_v3(egrid->increment_x, egrid->corner);
666
667         copy_v3_fl3(egrid->increment_y, 0.0f, cell_dim[1], 0.0f);
668         add_v3_v3(egrid->increment_y, half_cell_dim);
669         add_v3_fl(egrid->increment_y, -1.0f);
670         mul_m4_v3(ob->obmat, egrid->increment_y);
671         sub_v3_v3(egrid->increment_y, egrid->corner);
672
673         copy_v3_fl3(egrid->increment_z, 0.0f, 0.0f, cell_dim[2]);
674         add_v3_v3(egrid->increment_z, half_cell_dim);
675         add_v3_fl(egrid->increment_z, -1.0f);
676         mul_m4_v3(ob->obmat, egrid->increment_z);
677         sub_v3_v3(egrid->increment_z, egrid->corner);
678
679         /* Visibility bias */
680         egrid->visibility_bias = 0.05f * probe->vis_bias;
681         egrid->visibility_bleed = probe->vis_bleedbias;
682         egrid->visibility_range = 1.0f + sqrtf(max_fff(len_squared_v3(egrid->increment_x),
683                                                        len_squared_v3(egrid->increment_y),
684                                                        len_squared_v3(egrid->increment_z)));
685 }
686
687 void EEVEE_lightprobes_cube_data_from_object(Object *ob, EEVEE_LightProbe *eprobe)
688 {
689         LightProbe *probe = (LightProbe *)ob->data;
690
691         /* Update transforms */
692         copy_v3_v3(eprobe->position, ob->obmat[3]);
693
694         /* Attenuation */
695         eprobe->attenuation_type = probe->attenuation_type;
696         eprobe->attenuation_fac = 1.0f / max_ff(1e-8f, probe->falloff);
697
698         unit_m4(eprobe->attenuationmat);
699         scale_m4_fl(eprobe->attenuationmat, probe->distinf);
700         mul_m4_m4m4(eprobe->attenuationmat, ob->obmat, eprobe->attenuationmat);
701         invert_m4(eprobe->attenuationmat);
702
703         /* Parallax */
704         unit_m4(eprobe->parallaxmat);
705
706         if ((probe->flag & LIGHTPROBE_FLAG_CUSTOM_PARALLAX) != 0) {
707                 eprobe->parallax_type = probe->parallax_type;
708                 scale_m4_fl(eprobe->parallaxmat, probe->distpar);
709         }
710         else {
711                 eprobe->parallax_type = probe->attenuation_type;
712                 scale_m4_fl(eprobe->parallaxmat, probe->distinf);
713         }
714
715         mul_m4_m4m4(eprobe->parallaxmat, ob->obmat, eprobe->parallaxmat);
716         invert_m4(eprobe->parallaxmat);
717 }
718
719 void EEVEE_lightprobes_planar_data_from_object(Object *ob, EEVEE_PlanarReflection *eplanar, EEVEE_LightProbeVisTest *vis_test)
720 {
721         LightProbe *probe = (LightProbe *)ob->data;
722         float normat[4][4], imat[4][4];
723
724         vis_test->collection = probe->visibility_grp;
725         vis_test->invert = probe->flag & LIGHTPROBE_FLAG_INVERT_GROUP;
726         vis_test->cached = false;
727
728         /* Computing mtx : matrix that mirror position around object's XY plane. */
729         normalize_m4_m4(normat, ob->obmat);  /* object > world */
730         invert_m4_m4(imat, normat); /* world > object */
731         /* XY reflection plane */
732         imat[0][2] = -imat[0][2];
733         imat[1][2] = -imat[1][2];
734         imat[2][2] = -imat[2][2];
735         imat[3][2] = -imat[3][2]; /* world > object > mirrored obj */
736         mul_m4_m4m4(eplanar->mtx, normat, imat); /* world > object > mirrored obj > world */
737
738         /* Compute clip plane equation / normal. */
739         copy_v3_v3(eplanar->plane_equation, ob->obmat[2]);
740         normalize_v3(eplanar->plane_equation); /* plane normal */
741         eplanar->plane_equation[3] = -dot_v3v3(eplanar->plane_equation, ob->obmat[3]);
742         eplanar->clipsta = probe->clipsta;
743
744         /* Compute XY clip planes. */
745         normalize_v3_v3(eplanar->clip_vec_x, ob->obmat[0]);
746         normalize_v3_v3(eplanar->clip_vec_y, ob->obmat[1]);
747
748         float vec[3] = {0.0f, 0.0f, 0.0f};
749         vec[0] = 1.0f; vec[1] = 0.0f; vec[2] = 0.0f;
750         mul_m4_v3(ob->obmat, vec); /* Point on the edge */
751         eplanar->clip_edge_x_pos = dot_v3v3(eplanar->clip_vec_x, vec);
752
753         vec[0] = 0.0f; vec[1] = 1.0f; vec[2] = 0.0f;
754         mul_m4_v3(ob->obmat, vec); /* Point on the edge */
755         eplanar->clip_edge_y_pos = dot_v3v3(eplanar->clip_vec_y, vec);
756
757         vec[0] = -1.0f; vec[1] = 0.0f; vec[2] = 0.0f;
758         mul_m4_v3(ob->obmat, vec); /* Point on the edge */
759         eplanar->clip_edge_x_neg = dot_v3v3(eplanar->clip_vec_x, vec);
760
761         vec[0] = 0.0f; vec[1] = -1.0f; vec[2] = 0.0f;
762         mul_m4_v3(ob->obmat, vec); /* Point on the edge */
763         eplanar->clip_edge_y_neg = dot_v3v3(eplanar->clip_vec_y, vec);
764
765         /* Facing factors */
766         float max_angle = max_ff(1e-2f, probe->falloff) * M_PI * 0.5f;
767         float min_angle = 0.0f;
768         eplanar->facing_scale = 1.0f / max_ff(1e-8f, cosf(min_angle) - cosf(max_angle));
769         eplanar->facing_bias = -min_ff(1.0f - 1e-8f, cosf(max_angle)) * eplanar->facing_scale;
770
771         /* Distance factors */
772         float max_dist = probe->distinf;
773         float min_dist = min_ff(1.0f - 1e-8f, 1.0f - probe->falloff) * probe->distinf;
774         eplanar->attenuation_scale = -1.0f / max_ff(1e-8f, max_dist - min_dist);
775         eplanar->attenuation_bias = max_dist * -eplanar->attenuation_scale;
776 }
777
778 static void lightbake_planar_compute_render_matrices(
779         EEVEE_PlanarReflection *eplanar, DRWMatrixState *r_matstate, const float viewmat[4][4])
780 {
781         /* Reflect Camera Matrix. */
782         mul_m4_m4m4(r_matstate->viewmat, viewmat, eplanar->mtx);
783         /* TODO FOV margin */
784         /* Temporal sampling jitter should be already applied to the DRW_MAT_WIN. */
785         DRW_viewport_matrix_get(r_matstate->winmat, DRW_MAT_WIN);
786         /* Apply Projection Matrix. */
787         mul_m4_m4m4(r_matstate->persmat, r_matstate->winmat, r_matstate->viewmat);
788
789         /* This is the matrix used to reconstruct texture coordinates.
790          * We use the original view matrix because it does not create
791          * visual artifacts if receiver is not perfectly aligned with
792          * the planar reflection probe. */
793         mul_m4_m4m4(eplanar->reflectionmat, r_matstate->winmat, viewmat); /* TODO FOV margin */
794         /* Convert from [-1, 1] to [0, 1] (NDC to Texture coord). */
795         mul_m4_m4m4(eplanar->reflectionmat, texcomat, eplanar->reflectionmat);
796 }
797
798 static void eevee_lightprobes_extract_from_cache(EEVEE_LightProbesInfo *pinfo, LightCache *lcache)
799 {
800         /* copy the entire cache for now (up to MAX_PROBE) */
801         /* TODO Frutum cull to only add visible probes. */
802         memcpy(pinfo->probe_data, lcache->cube_data, sizeof(EEVEE_LightProbe) * max_ii(1, min_ii(lcache->cube_len, MAX_PROBE)));
803         /* TODO compute the max number of grid based on sample count. */
804         memcpy(pinfo->grid_data, lcache->grid_data, sizeof(EEVEE_LightGrid) * max_ii(1, min_ii(lcache->grid_len, MAX_GRID)));
805 }
806
807 void EEVEE_lightprobes_cache_finish(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
808 {
809         EEVEE_StorageList *stl = vedata->stl;
810         LightCache *light_cache = stl->g_data->light_cache;
811         EEVEE_LightProbesInfo *pinfo = sldata->probes;
812
813         eevee_lightprobes_extract_from_cache(sldata->probes, light_cache);
814
815         DRW_uniformbuffer_update(sldata->probe_ubo, &sldata->probes->probe_data);
816         DRW_uniformbuffer_update(sldata->grid_ubo, &sldata->probes->grid_data);
817
818         /* For shading, save max level of the octahedron map */
819         sldata->common_data.prb_lod_cube_max = (float)light_cache->mips_len - 1.0f;
820         sldata->common_data.prb_lod_planar_max = (float)MAX_PLANAR_LOD_LEVEL;
821         sldata->common_data.prb_irradiance_vis_size = light_cache->vis_res;
822         sldata->common_data.prb_num_render_cube = max_ii(1, light_cache->cube_len);
823         sldata->common_data.prb_num_render_grid = max_ii(1, light_cache->grid_len);
824         sldata->common_data.prb_num_planar = pinfo->num_planar;
825
826         if (pinfo->num_planar != pinfo->cache_num_planar) {
827                 DRW_TEXTURE_FREE_SAFE(vedata->txl->planar_pool);
828                 DRW_TEXTURE_FREE_SAFE(vedata->txl->planar_depth);
829                 pinfo->cache_num_planar = pinfo->num_planar;
830         }
831         planar_pool_ensure_alloc(vedata, pinfo->num_planar);
832
833         /* If lightcache auto-update is enable we tag the relevant part
834          * of the cache to update and fire up a baking job. */
835         if (!DRW_state_is_image_render() && !DRW_state_is_opengl_render() &&
836             (pinfo->do_grid_update || pinfo->do_cube_update))
837         {
838                 const DRWContextState *draw_ctx = DRW_context_state_get();
839                 BLI_assert(draw_ctx->evil_C);
840
841                 if (draw_ctx->scene->eevee.flag & SCE_EEVEE_GI_AUTOBAKE) {
842                         Scene *scene_orig = DEG_get_input_scene(draw_ctx->depsgraph);
843                         if (scene_orig->eevee.light_cache != NULL) {
844                                 if (pinfo->do_grid_update) {
845                                         scene_orig->eevee.light_cache->flag |= LIGHTCACHE_UPDATE_GRID;
846                                 }
847                                 /* If we update grid we need to update the cubemaps too.
848                                  * So always refresh cubemaps. */
849                                 scene_orig->eevee.light_cache->flag |= LIGHTCACHE_UPDATE_CUBE;
850                                 /* Tag the lightcache to auto update. */
851                                 scene_orig->eevee.light_cache->flag |= LIGHTCACHE_UPDATE_AUTO;
852                                 /* Use a notifier to trigger the operator after drawing. */
853                                 WM_event_add_notifier(draw_ctx->evil_C, NC_LIGHTPROBE, scene_orig);
854                         }
855                 }
856         }
857 }
858
859 /* -------------------------------------------------------------------- */
860
861 /** \name Rendering
862  * \{ */
863
864 typedef struct EEVEE_BakeRenderData {
865         EEVEE_Data *vedata;
866         EEVEE_ViewLayerData *sldata;
867         struct GPUFrameBuffer **face_fb; /* should contain 6 framebuffer */
868 } EEVEE_BakeRenderData;
869
870 static void render_cubemap(
871         void (*callback)(int face, EEVEE_BakeRenderData *user_data), EEVEE_BakeRenderData *user_data,
872         const float pos[3], float clipsta, float clipend)
873 {
874         DRWMatrixState matstate;
875
876         /* Move to capture position */
877         float posmat[4][4];
878         unit_m4(posmat);
879         negate_v3_v3(posmat[3], pos);
880
881         perspective_m4(matstate.winmat, -clipsta, clipsta, -clipsta, clipsta, clipsta, clipend);
882         invert_m4_m4(matstate.wininv, matstate.winmat);
883
884         /* 1 - Render to each cubeface individually.
885          * We do this instead of using geometry shader because a) it's faster,
886          * b) it's easier than fixing the nodetree shaders (for view dependant effects). */
887         for (int i = 0; i < 6; ++i) {
888                 /* Setup custom matrices */
889                 mul_m4_m4m4(matstate.viewmat, cubefacemat[i], posmat);
890                 mul_m4_m4m4(matstate.persmat, matstate.winmat, matstate.viewmat);
891                 invert_m4_m4(matstate.persinv, matstate.persmat);
892                 invert_m4_m4(matstate.viewinv, matstate.viewmat);
893                 invert_m4_m4(matstate.wininv, matstate.winmat);
894
895                 DRW_viewport_matrix_override_set_all(&matstate);
896
897                 callback(i, user_data);
898         }
899 }
900
901 static void render_reflections(
902         void (*callback)(int face, EEVEE_BakeRenderData *user_data), EEVEE_BakeRenderData *user_data,
903         EEVEE_PlanarReflection *planar_data, int ref_count)
904 {
905         DRWMatrixState matstate;
906
907         float original_viewmat[4][4];
908         DRW_viewport_matrix_get(original_viewmat, DRW_MAT_VIEW);
909
910         for (int i = 0; i < ref_count; ++i) {
911                 /* Setup custom matrices */
912                 lightbake_planar_compute_render_matrices(planar_data + i, &matstate, original_viewmat);
913                 invert_m4_m4(matstate.persinv, matstate.persmat);
914                 invert_m4_m4(matstate.viewinv, matstate.viewmat);
915                 invert_m4_m4(matstate.wininv, matstate.winmat);
916                 DRW_viewport_matrix_override_set_all(&matstate);
917
918                 callback(i, user_data);
919         }
920 }
921
922 static void lightbake_render_world_face(int face, EEVEE_BakeRenderData *user_data)
923 {
924         EEVEE_PassList *psl = user_data->vedata->psl;
925         struct GPUFrameBuffer **face_fb = user_data->face_fb;
926
927         /* For world probe, we don't need to clear the color buffer
928          * since we render the background directly. */
929         GPU_framebuffer_bind(face_fb[face]);
930         GPU_framebuffer_clear_depth(face_fb[face], 1.0f);
931         DRW_draw_pass(psl->probe_background);
932 }
933
934 void EEVEE_lightbake_render_world(EEVEE_ViewLayerData *UNUSED(sldata), EEVEE_Data *vedata, struct GPUFrameBuffer *face_fb[6])
935 {
936         EEVEE_BakeRenderData brdata = {
937                 .vedata = vedata,
938                 .face_fb = face_fb
939         };
940
941         render_cubemap(lightbake_render_world_face, &brdata, (float[3]){0.0f}, 1.0f, 10.0f);
942 }
943
944 static void lightbake_render_scene_face(int face, EEVEE_BakeRenderData *user_data)
945 {
946         EEVEE_ViewLayerData *sldata = user_data->sldata;
947         EEVEE_PassList *psl = user_data->vedata->psl;
948         struct GPUFrameBuffer **face_fb = user_data->face_fb;
949
950         /* Be sure that cascaded shadow maps are updated. */
951         EEVEE_draw_shadows(sldata, psl);
952
953         GPU_framebuffer_bind(face_fb[face]);
954         GPU_framebuffer_clear_depth(face_fb[face], 1.0f);
955
956         DRW_draw_pass(psl->depth_pass);
957         DRW_draw_pass(psl->depth_pass_cull);
958         DRW_draw_pass(psl->probe_background);
959         DRW_draw_pass(psl->material_pass);
960         DRW_draw_pass(psl->sss_pass); /* Only output standard pass */
961         EEVEE_draw_default_passes(psl);
962 }
963
964 /* Render the scene to the probe_rt texture. */
965 void EEVEE_lightbake_render_scene(
966         EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata, struct GPUFrameBuffer *face_fb[6],
967         const float pos[3], float near_clip, float far_clip)
968 {
969         EEVEE_BakeRenderData brdata = {
970                 .vedata = vedata,
971                 .sldata = sldata,
972                 .face_fb = face_fb
973         };
974
975         render_cubemap(lightbake_render_scene_face, &brdata, pos, near_clip, far_clip);
976 }
977
978 static void lightbake_render_scene_reflected(int layer, EEVEE_BakeRenderData *user_data)
979 {
980         EEVEE_Data *vedata = user_data->vedata;
981         EEVEE_ViewLayerData *sldata = user_data->sldata;
982         EEVEE_PassList *psl = vedata->psl;
983         EEVEE_TextureList *txl = vedata->txl;
984         EEVEE_FramebufferList *fbl = vedata->fbl;
985         EEVEE_LightProbesInfo *pinfo = sldata->probes;
986         EEVEE_PlanarReflection *eplanar = pinfo->planar_data + layer;
987
988         GPU_framebuffer_ensure_config(&fbl->planarref_fb, {
989                 GPU_ATTACHMENT_TEXTURE_LAYER(txl->planar_depth, layer),
990                 GPU_ATTACHMENT_TEXTURE_LAYER(txl->planar_pool, layer)
991         });
992
993         /* Use visibility info for this planar reflection. */
994         pinfo->vis_data = pinfo->planar_vis_tests[layer];
995
996         /* Avoid using the texture attached to framebuffer when rendering. */
997         /* XXX */
998         GPUTexture *tmp_planar_pool = txl->planar_pool;
999         GPUTexture *tmp_planar_depth = txl->planar_depth;
1000         txl->planar_pool = e_data.planar_pool_placeholder;
1001         txl->planar_depth = e_data.depth_array_placeholder;
1002
1003         /* Be sure that cascaded shadow maps are updated. */
1004         DRW_stats_group_start("Planar Reflection");
1005
1006         /* Be sure that cascaded shadow maps are updated. */
1007         EEVEE_draw_shadows(sldata, psl);
1008         /* Since we are rendering with an inverted view matrix, we need
1009          * to invert the facing for backface culling to be the same. */
1010         DRW_state_invert_facing();
1011         /* Compute offset plane equation (fix missing texels near reflection plane). */
1012         copy_v4_v4(sldata->clip_data.clip_planes[0], eplanar->plane_equation);
1013         sldata->clip_data.clip_planes[0][3] += eplanar->clipsta;
1014         /* Set clipping plane */
1015         DRW_uniformbuffer_update(sldata->clip_ubo, &sldata->clip_data);
1016         DRW_state_clip_planes_count_set(1);
1017
1018         GPU_framebuffer_bind(fbl->planarref_fb);
1019         GPU_framebuffer_clear_depth(fbl->planarref_fb, 1.0);
1020
1021         /* Slight modification: we handle refraction as normal
1022          * shading and don't do SSRefraction. */
1023
1024         DRW_draw_pass(psl->depth_pass_clip);
1025         DRW_draw_pass(psl->depth_pass_clip_cull);
1026         DRW_draw_pass(psl->refract_depth_pass);
1027         DRW_draw_pass(psl->refract_depth_pass_cull);
1028
1029         DRW_draw_pass(psl->probe_background);
1030         EEVEE_create_minmax_buffer(vedata, tmp_planar_depth, layer);
1031         EEVEE_occlusion_compute(sldata, vedata, tmp_planar_depth, layer);
1032
1033         GPU_framebuffer_bind(fbl->planarref_fb);
1034
1035         /* Shading pass */
1036         EEVEE_draw_default_passes(psl);
1037         DRW_draw_pass(psl->material_pass);
1038         DRW_draw_pass(psl->sss_pass); /* Only output standard pass */
1039         DRW_draw_pass(psl->refract_pass);
1040
1041         /* Transparent */
1042         if (DRW_state_is_image_render()) {
1043                 /* Do the reordering only for offline because it can be costly. */
1044                 DRW_pass_sort_shgroup_z(psl->transparent_pass);
1045         }
1046         DRW_draw_pass(psl->transparent_pass);
1047
1048         DRW_state_invert_facing();
1049         DRW_state_clip_planes_reset();
1050
1051         DRW_stats_group_end();
1052
1053         /* Restore */
1054         txl->planar_pool = tmp_planar_pool;
1055         txl->planar_depth = tmp_planar_depth;
1056 }
1057
1058 static void eevee_lightbake_render_scene_to_planars(
1059         EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
1060 {
1061         EEVEE_BakeRenderData brdata = {
1062                 .vedata = vedata,
1063                 .sldata = sldata,
1064         };
1065
1066         render_reflections(lightbake_render_scene_reflected, &brdata, sldata->probes->planar_data, sldata->probes->num_planar);
1067 }
1068 /** \} */
1069
1070 /* -------------------------------------------------------------------- */
1071
1072 /** \name Filtering
1073  * \{ */
1074
1075 /* Glossy filter rt_color to light_cache->cube_tx.tex at index probe_idx */
1076 void EEVEE_lightbake_filter_glossy(
1077         EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata,
1078         struct GPUTexture *rt_color, struct GPUFrameBuffer *fb,
1079         int probe_idx, float intensity, int maxlevel)
1080 {
1081         EEVEE_PassList *psl = vedata->psl;
1082         EEVEE_LightProbesInfo *pinfo = sldata->probes;
1083         LightCache *light_cache = vedata->stl->g_data->light_cache;
1084
1085         float target_size = (float)GPU_texture_width(rt_color);
1086
1087         /* Max lod used from the render target probe */
1088         pinfo->lod_rt_max = floorf(log2f(target_size)) - 2.0f;
1089         pinfo->intensity_fac = intensity;
1090
1091         /* Start fresh */
1092         GPU_framebuffer_ensure_config(&fb, {
1093                 GPU_ATTACHMENT_NONE,
1094                 GPU_ATTACHMENT_NONE
1095         });
1096
1097         /* 2 - Let gpu create Mipmaps for Filtered Importance Sampling. */
1098         /* Bind next framebuffer to be able to gen. mips for probe_rt. */
1099         EEVEE_downsample_cube_buffer(vedata, rt_color, (int)(pinfo->lod_rt_max));
1100
1101         /* 3 - Render to probe array to the specified layer, do prefiltering. */
1102         int mipsize = GPU_texture_width(light_cache->cube_tx.tex);
1103         for (int i = 0; i < maxlevel + 1; i++) {
1104                 float bias = (i == 0) ? -1.0f : 1.0f;
1105                 pinfo->texel_size = 1.0f / (float)mipsize;
1106                 pinfo->padding_size = (float)(1 << (maxlevel - i - 1));
1107                 pinfo->padding_size *= pinfo->texel_size;
1108                 pinfo->layer = probe_idx;
1109                 pinfo->roughness = i / (float)maxlevel;
1110                 pinfo->roughness *= pinfo->roughness; /* Disney Roughness */
1111                 pinfo->roughness *= pinfo->roughness; /* Distribute Roughness accros lod more evenly */
1112                 CLAMP(pinfo->roughness, 1e-8f, 0.99999f); /* Avoid artifacts */
1113
1114 #if 1 /* Variable Sample count (fast) */
1115                 switch (i) {
1116                         case 0: pinfo->samples_len = 1.0f; break;
1117                         case 1: pinfo->samples_len = 16.0f; break;
1118                         case 2: pinfo->samples_len = 32.0f; break;
1119                         case 3: pinfo->samples_len = 64.0f; break;
1120                         default: pinfo->samples_len = 128.0f; break;
1121                 }
1122 #else /* Constant Sample count (slow) */
1123                 pinfo->samples_len = 1024.0f;
1124 #endif
1125
1126                 pinfo->samples_len_inv = 1.0f / pinfo->samples_len;
1127                 pinfo->lodfactor = bias + 0.5f * log((float)(target_size * target_size) * pinfo->samples_len_inv) / log(2);
1128
1129                 GPU_framebuffer_ensure_config(&fb, {
1130                         GPU_ATTACHMENT_NONE,
1131                         GPU_ATTACHMENT_TEXTURE_MIP(light_cache->cube_tx.tex, i)
1132                 });
1133                 GPU_framebuffer_bind(fb);
1134                 GPU_framebuffer_viewport_set(fb, 0, 0, mipsize, mipsize);
1135                 DRW_draw_pass(psl->probe_glossy_compute);
1136
1137                 mipsize /= 2;
1138                 CLAMP_MIN(mipsize, 1);
1139         }
1140 }
1141
1142 /* Diffuse filter rt_color to light_cache->grid_tx.tex at index grid_offset */
1143 void EEVEE_lightbake_filter_diffuse(
1144         EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata,
1145         struct GPUTexture *rt_color, struct GPUFrameBuffer *fb,
1146         int grid_offset, float intensity)
1147 {
1148         EEVEE_PassList *psl = vedata->psl;
1149         EEVEE_LightProbesInfo *pinfo = sldata->probes;
1150         LightCache *light_cache = vedata->stl->g_data->light_cache;
1151
1152         float target_size = (float)GPU_texture_width(rt_color);
1153
1154         pinfo->intensity_fac = intensity;
1155
1156         /* find cell position on the virtual 3D texture */
1157         /* NOTE : Keep in sync with load_irradiance_cell() */
1158 #if defined(IRRADIANCE_SH_L2)
1159         int size[2] = {3, 3};
1160 #elif defined(IRRADIANCE_CUBEMAP)
1161         int size[2] = {8, 8};
1162         pinfo->samples_len = 1024.0f;
1163 #elif defined(IRRADIANCE_HL2)
1164         int size[2] = {3, 2};
1165         pinfo->samples_len = 1024.0f;
1166 #endif
1167
1168         int cell_per_row = GPU_texture_width(light_cache->grid_tx.tex) / size[0];
1169         int x = size[0] * (grid_offset % cell_per_row);
1170         int y = size[1] * (grid_offset / cell_per_row);
1171
1172 #ifndef IRRADIANCE_SH_L2
1173         /* Tweaking parameters to balance perf. vs precision */
1174         const float bias = 0.0f;
1175         pinfo->samples_len_inv = 1.0f / pinfo->samples_len;
1176         pinfo->lodfactor = bias + 0.5f * log((float)(target_size * target_size) * pinfo->samples_len_inv) / log(2);
1177         pinfo->lod_rt_max = floorf(log2f(target_size)) - 2.0f;
1178 #else
1179         pinfo->shres = 32; /* Less texture fetches & reduce branches */
1180         pinfo->lod_rt_max = 2.0f; /* Improve cache reuse */
1181 #endif
1182
1183         /* Start fresh */
1184         GPU_framebuffer_ensure_config(&fb, {
1185                 GPU_ATTACHMENT_NONE,
1186                 GPU_ATTACHMENT_NONE
1187         });
1188
1189         /* 4 - Compute diffuse irradiance */
1190         EEVEE_downsample_cube_buffer(vedata, rt_color, (int)(pinfo->lod_rt_max));
1191
1192         GPU_framebuffer_ensure_config(&fb, {
1193                 GPU_ATTACHMENT_NONE,
1194                 GPU_ATTACHMENT_TEXTURE_LAYER(light_cache->grid_tx.tex, 0)
1195         });
1196         GPU_framebuffer_bind(fb);
1197         GPU_framebuffer_viewport_set(fb, x, y, size[0], size[1]);
1198         DRW_draw_pass(psl->probe_diffuse_compute);
1199 }
1200
1201 /* Filter rt_depth to light_cache->grid_tx.tex at index grid_offset */
1202 void EEVEE_lightbake_filter_visibility(
1203         EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata,
1204         struct GPUTexture *UNUSED(rt_depth), struct GPUFrameBuffer *fb,
1205         int grid_offset, float clipsta, float clipend,
1206         float vis_range, float vis_blur, int vis_size)
1207 {
1208         EEVEE_PassList *psl = vedata->psl;
1209         EEVEE_LightProbesInfo *pinfo = sldata->probes;
1210         LightCache *light_cache = vedata->stl->g_data->light_cache;
1211
1212         pinfo->samples_len = 512.0f; /* TODO refine */
1213         pinfo->samples_len_inv = 1.0f / pinfo->samples_len;
1214         pinfo->shres = vis_size;
1215         pinfo->visibility_range = vis_range;
1216         pinfo->visibility_blur = vis_blur;
1217         pinfo->near_clip = -clipsta;
1218         pinfo->far_clip = -clipend;
1219         pinfo->texel_size = 1.0f / (float)vis_size;
1220
1221         int cell_per_col = GPU_texture_height(light_cache->grid_tx.tex) / vis_size;
1222         int cell_per_row = GPU_texture_width(light_cache->grid_tx.tex) / vis_size;
1223         int x = vis_size * (grid_offset % cell_per_row);
1224         int y = vis_size * ((grid_offset / cell_per_row) % cell_per_col);
1225         int layer = 1 + ((grid_offset / cell_per_row) / cell_per_col);
1226
1227         GPU_framebuffer_ensure_config(&fb, {
1228                 GPU_ATTACHMENT_NONE,
1229                 GPU_ATTACHMENT_TEXTURE_LAYER(light_cache->grid_tx.tex, layer)
1230         });
1231         GPU_framebuffer_bind(fb);
1232         GPU_framebuffer_viewport_set(fb, x, y, vis_size, vis_size);
1233         DRW_draw_pass(psl->probe_visibility_compute);
1234 }
1235
1236 /* Actually a simple downsampling */
1237 static void downsample_planar(void *vedata, int level)
1238 {
1239         EEVEE_PassList *psl = ((EEVEE_Data *)vedata)->psl;
1240         EEVEE_StorageList *stl = ((EEVEE_Data *)vedata)->stl;
1241
1242         const float *size = DRW_viewport_size_get();
1243         copy_v2_v2(stl->g_data->planar_texel_size, size);
1244         for (int i = 0; i < level - 1; ++i) {
1245                 stl->g_data->planar_texel_size[0] /= 2.0f;
1246                 stl->g_data->planar_texel_size[1] /= 2.0f;
1247                 min_ff(floorf(stl->g_data->planar_texel_size[0]), 1.0f);
1248                 min_ff(floorf(stl->g_data->planar_texel_size[1]), 1.0f);
1249         }
1250         invert_v2(stl->g_data->planar_texel_size);
1251
1252         DRW_draw_pass(psl->probe_planar_downsample_ps);
1253 }
1254
1255 static void EEVEE_lightbake_filter_planar(EEVEE_Data *vedata)
1256 {
1257         EEVEE_TextureList *txl = vedata->txl;
1258         EEVEE_FramebufferList  *fbl = vedata->fbl;
1259
1260         DRW_stats_group_start("Planar Probe Downsample");
1261
1262         GPU_framebuffer_ensure_config(&fbl->planar_downsample_fb, {
1263                 GPU_ATTACHMENT_NONE,
1264                 GPU_ATTACHMENT_TEXTURE(txl->planar_pool)
1265         });
1266
1267         GPU_framebuffer_recursive_downsample(fbl->planar_downsample_fb, MAX_PLANAR_LOD_LEVEL, &downsample_planar, vedata);
1268         DRW_stats_group_end();
1269 }
1270
1271 /** \} */
1272
1273 void EEVEE_lightprobes_refresh_planar(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
1274 {
1275         EEVEE_CommonUniformBuffer *common_data = &sldata->common_data;
1276         EEVEE_LightProbesInfo *pinfo = sldata->probes;
1277         DRWMatrixState saved_mats;
1278
1279         if (pinfo->num_planar == 0) {
1280                 /* Disable SSR if we cannot read previous frame */
1281                 common_data->ssr_toggle = vedata->stl->g_data->valid_double_buffer;
1282                 common_data->prb_num_planar = 0;
1283                 return;
1284         }
1285
1286         /* We need to save the Matrices before overidding them */
1287         DRW_viewport_matrix_get_all(&saved_mats);
1288
1289         /* Temporary Remove all planar reflections (avoid lag effect). */
1290         common_data->prb_num_planar = 0;
1291         /* Turn off ssr to avoid black specular */
1292         common_data->ssr_toggle = false;
1293         common_data->sss_toggle = false;
1294
1295         DRW_uniformbuffer_update(sldata->common_ubo, &sldata->common_data);
1296
1297         /* Rendering happens here! */
1298         eevee_lightbake_render_scene_to_planars(sldata, vedata);
1299
1300         /* Make sure no aditionnal visibility check runs after this. */
1301         pinfo->vis_data.collection = NULL;
1302
1303         DRW_uniformbuffer_update(sldata->planar_ubo, &sldata->probes->planar_data);
1304
1305         /* Restore */
1306         common_data->prb_num_planar = pinfo->num_planar;
1307         common_data->ssr_toggle = true;
1308         common_data->sss_toggle = true;
1309
1310         /* Prefilter for SSR */
1311         if ((vedata->stl->effects->enabled_effects & EFFECT_SSR) != 0) {
1312                 EEVEE_lightbake_filter_planar(vedata);
1313         }
1314
1315         DRW_viewport_matrix_override_set_all(&saved_mats);
1316
1317         if (DRW_state_is_image_render()) {
1318                 /* Sort transparents because planar reflections could have re-sorted them. */
1319                 DRW_pass_sort_shgroup_z(vedata->psl->transparent_pass);
1320         }
1321
1322         /* Disable SSR if we cannot read previous frame */
1323         common_data->ssr_toggle = vedata->stl->g_data->valid_double_buffer;
1324 }
1325
1326 void EEVEE_lightprobes_refresh(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
1327 {
1328         const DRWContextState *draw_ctx = DRW_context_state_get();
1329         const Scene *scene_eval = DEG_get_evaluated_scene(draw_ctx->depsgraph);
1330         LightCache *light_cache = vedata->stl->g_data->light_cache;
1331
1332         if (light_cache->flag & LIGHTCACHE_UPDATE_WORLD) {
1333                 DRWMatrixState saved_mats;
1334                 DRW_viewport_matrix_get_all(&saved_mats);
1335                 EEVEE_lightbake_update_world_quick(sldata, vedata, scene_eval);
1336                 DRW_viewport_matrix_override_set_all(&saved_mats);
1337         }
1338 }
1339
1340 void EEVEE_lightprobes_free(void)
1341 {
1342         MEM_SAFE_FREE(e_data.format_probe_display_cube);
1343         MEM_SAFE_FREE(e_data.format_probe_display_planar);
1344         DRW_SHADER_FREE_SAFE(e_data.probe_default_sh);
1345         DRW_SHADER_FREE_SAFE(e_data.probe_default_studiolight_sh);
1346         DRW_SHADER_FREE_SAFE(e_data.probe_filter_glossy_sh);
1347         DRW_SHADER_FREE_SAFE(e_data.probe_filter_diffuse_sh);
1348         DRW_SHADER_FREE_SAFE(e_data.probe_filter_visibility_sh);
1349         DRW_SHADER_FREE_SAFE(e_data.probe_grid_fill_sh);
1350         DRW_SHADER_FREE_SAFE(e_data.probe_grid_display_sh);
1351         DRW_SHADER_FREE_SAFE(e_data.probe_planar_display_sh);
1352         DRW_SHADER_FREE_SAFE(e_data.probe_planar_downsample_sh);
1353         DRW_SHADER_FREE_SAFE(e_data.probe_cube_display_sh);
1354         DRW_TEXTURE_FREE_SAFE(e_data.hammersley);
1355         DRW_TEXTURE_FREE_SAFE(e_data.planar_pool_placeholder);
1356         DRW_TEXTURE_FREE_SAFE(e_data.depth_placeholder);
1357         DRW_TEXTURE_FREE_SAFE(e_data.depth_array_placeholder);
1358 }