GP: Improve Blur FX quality in transparency.
[blender.git] / source / blender / draw / engines / eevee / eevee_materials.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_materials.c
23  *  \ingroup draw_engine
24  */
25
26 #include "DRW_render.h"
27
28 #include "BLI_dynstr.h"
29 #include "BLI_ghash.h"
30 #include "BLI_alloca.h"
31 #include "BLI_rand.h"
32 #include "BLI_string_utils.h"
33
34 #include "BKE_particle.h"
35 #include "BKE_paint.h"
36 #include "BKE_pbvh.h"
37 #include "BKE_studiolight.h"
38
39 #include "DNA_world_types.h"
40 #include "DNA_modifier_types.h"
41 #include "DNA_view3d_types.h"
42
43 #include "GPU_material.h"
44
45 #include "eevee_engine.h"
46 #include "eevee_lut.h"
47 #include "eevee_private.h"
48
49 /* *********** STATIC *********** */
50 static struct {
51         char *frag_shader_lib;
52         char *vert_shader_str;
53         char *volume_shader_lib;
54
55         struct GPUShader *default_prepass_sh;
56         struct GPUShader *default_prepass_clip_sh;
57         struct GPUShader *default_hair_prepass_sh;
58         struct GPUShader *default_hair_prepass_clip_sh;
59         struct GPUShader *default_lit[VAR_MAT_MAX];
60         struct GPUShader *default_background;
61         struct GPUShader *default_studiolight_background;
62         struct GPUShader *update_noise_sh;
63
64         /* 64*64 array texture containing all LUTs and other utilitarian arrays.
65          * Packing enables us to same precious textures slots. */
66         struct GPUTexture *util_tex;
67         struct GPUTexture *noise_tex;
68
69         uint sss_count;
70
71         float alpha_hash_offset;
72         float noise_offsets[3];
73 } e_data = {NULL}; /* Engine data */
74
75 extern char datatoc_lamps_lib_glsl[];
76 extern char datatoc_lightprobe_lib_glsl[];
77 extern char datatoc_ambient_occlusion_lib_glsl[];
78 extern char datatoc_prepass_frag_glsl[];
79 extern char datatoc_prepass_vert_glsl[];
80 extern char datatoc_default_frag_glsl[];
81 extern char datatoc_default_world_frag_glsl[];
82 extern char datatoc_ltc_lib_glsl[];
83 extern char datatoc_bsdf_lut_frag_glsl[];
84 extern char datatoc_btdf_lut_frag_glsl[];
85 extern char datatoc_bsdf_common_lib_glsl[];
86 extern char datatoc_bsdf_sampling_lib_glsl[];
87 extern char datatoc_common_uniforms_lib_glsl[];
88 extern char datatoc_common_hair_lib_glsl[];
89 extern char datatoc_common_view_lib_glsl[];
90 extern char datatoc_irradiance_lib_glsl[];
91 extern char datatoc_octahedron_lib_glsl[];
92 extern char datatoc_lit_surface_frag_glsl[];
93 extern char datatoc_lit_surface_vert_glsl[];
94 extern char datatoc_raytrace_lib_glsl[];
95 extern char datatoc_ssr_lib_glsl[];
96 extern char datatoc_shadow_vert_glsl[];
97 extern char datatoc_lightprobe_geom_glsl[];
98 extern char datatoc_lightprobe_vert_glsl[];
99 extern char datatoc_background_vert_glsl[];
100 extern char datatoc_update_noise_frag_glsl[];
101 extern char datatoc_volumetric_vert_glsl[];
102 extern char datatoc_volumetric_geom_glsl[];
103 extern char datatoc_volumetric_frag_glsl[];
104 extern char datatoc_volumetric_lib_glsl[];
105
106 extern char datatoc_gpu_shader_uniform_color_frag_glsl[];
107
108 extern Material defmaterial;
109 extern GlobalsUboStorage ts;
110
111 /* *********** FUNCTIONS *********** */
112
113 #if 0 /* Used only to generate the LUT values */
114 static struct GPUTexture *create_ggx_lut_texture(int UNUSED(w), int UNUSED(h))
115 {
116         struct GPUTexture *tex;
117         struct GPUFrameBuffer *fb = NULL;
118         static float samples_len = 8192.0f;
119         static float inv_samples_len = 1.0f / 8192.0f;
120
121         char *lib_str = BLI_string_joinN(
122                 datatoc_bsdf_common_lib_glsl,
123                 datatoc_bsdf_sampling_lib_glsl);
124
125         struct GPUShader *sh = DRW_shader_create_with_lib(
126                 datatoc_lightprobe_vert_glsl, datatoc_lightprobe_geom_glsl, datatoc_bsdf_lut_frag_glsl, lib_str,
127                 "#define HAMMERSLEY_SIZE 8192\n"
128                 "#define BRDF_LUT_SIZE 64\n"
129                 "#define NOISE_SIZE 64\n");
130
131         DRWPass *pass = DRW_pass_create("LightProbe Filtering", DRW_STATE_WRITE_COLOR);
132         DRWShadingGroup *grp = DRW_shgroup_create(sh, pass);
133         DRW_shgroup_uniform_float(grp, "sampleCount", &samples_len, 1);
134         DRW_shgroup_uniform_float(grp, "invSampleCount", &inv_samples_len, 1);
135         DRW_shgroup_uniform_texture(grp, "texHammersley", e_data.hammersley);
136         DRW_shgroup_uniform_texture(grp, "texJitter", e_data.jitter);
137
138         struct GPUBatch *geom = DRW_cache_fullscreen_quad_get();
139         DRW_shgroup_call_add(grp, geom, NULL);
140
141         float *texels = MEM_mallocN(sizeof(float[2]) * w * h, "lut");
142
143         tex = DRW_texture_create_2D(w, h, GPU_RG16F, DRW_TEX_FILTER, (float *)texels);
144
145         DRWFboTexture tex_filter = {&tex, GPU_RG16F, DRW_TEX_FILTER};
146         GPU_framebuffer_init(&fb, &draw_engine_eevee_type, w, h, &tex_filter, 1);
147
148         GPU_framebuffer_bind(fb);
149         DRW_draw_pass(pass);
150
151         float *data = MEM_mallocN(sizeof(float[3]) * w * h, "lut");
152         glReadBuffer(GL_COLOR_ATTACHMENT0);
153         glReadPixels(0, 0, w, h, GL_RGB, GL_FLOAT, data);
154
155         printf("{");
156         for (int i = 0; i < w*h * 3; i+=3) {
157                 printf("%ff, %ff, ", data[i],  data[i+1]); i+=3;
158                 printf("%ff, %ff, ", data[i],  data[i+1]); i+=3;
159                 printf("%ff, %ff, ", data[i],  data[i+1]); i+=3;
160                 printf("%ff, %ff, \n", data[i],  data[i+1]);
161         }
162         printf("}");
163
164         MEM_freeN(texels);
165         MEM_freeN(data);
166
167         return tex;
168 }
169
170 static struct GPUTexture *create_ggx_refraction_lut_texture(int w, int h)
171 {
172         struct GPUTexture *tex;
173         struct GPUTexture *hammersley = create_hammersley_sample_texture(8192);
174         struct GPUFrameBuffer *fb = NULL;
175         static float samples_len = 8192.0f;
176         static float a2 = 0.0f;
177         static float inv_samples_len = 1.0f / 8192.0f;
178
179         char *frag_str = BLI_string_joinN(
180                 datatoc_bsdf_common_lib_glsl,
181                 datatoc_bsdf_sampling_lib_glsl,
182                 datatoc_btdf_lut_frag_glsl);
183
184         struct GPUShader *sh = DRW_shader_create_fullscreen(frag_str,
185                 "#define HAMMERSLEY_SIZE 8192\n"
186                 "#define BRDF_LUT_SIZE 64\n"
187                 "#define NOISE_SIZE 64\n"
188                 "#define LUT_SIZE 64\n");
189
190         MEM_freeN(frag_str);
191
192         DRWPass *pass = DRW_pass_create("LightProbe Filtering", DRW_STATE_WRITE_COLOR);
193         DRWShadingGroup *grp = DRW_shgroup_create(sh, pass);
194         DRW_shgroup_uniform_float(grp, "a2", &a2, 1);
195         DRW_shgroup_uniform_float(grp, "sampleCount", &samples_len, 1);
196         DRW_shgroup_uniform_float(grp, "invSampleCount", &inv_samples_len, 1);
197         DRW_shgroup_uniform_texture(grp, "texHammersley", hammersley);
198         DRW_shgroup_uniform_texture(grp, "utilTex", e_data.util_tex);
199
200         struct GPUBatch *geom = DRW_cache_fullscreen_quad_get();
201         DRW_shgroup_call_add(grp, geom, NULL);
202
203         float *texels = MEM_mallocN(sizeof(float[2]) * w * h, "lut");
204
205         tex = DRW_texture_create_2D(w, h, GPU_R16F, DRW_TEX_FILTER, (float *)texels);
206
207         DRWFboTexture tex_filter = {&tex, GPU_R16F, DRW_TEX_FILTER};
208         GPU_framebuffer_init(&fb, &draw_engine_eevee_type, w, h, &tex_filter, 1);
209
210         GPU_framebuffer_bind(fb);
211
212         float *data = MEM_mallocN(sizeof(float[3]) * w * h, "lut");
213
214         float inc = 1.0f / 31.0f;
215         float roughness = 1e-8f - inc;
216         FILE *f = BLI_fopen("btdf_split_sum_ggx.h", "w");
217         fprintf(f, "static float btdf_split_sum_ggx[32][64 * 64] = {\n");
218         do {
219                 roughness += inc;
220                 CLAMP(roughness, 1e-4f, 1.0f);
221                 a2 = powf(roughness, 4.0f);
222                 DRW_draw_pass(pass);
223
224                 GPU_framebuffer_read_data(0, 0, w, h, 3, 0, data);
225
226 #if 1
227                 fprintf(f, "\t{\n\t\t");
228                 for (int i = 0; i < w*h * 3; i+=3) {
229                         fprintf(f, "%ff,", data[i]);
230                         if (((i/3)+1) % 12 == 0) fprintf(f, "\n\t\t");
231                         else fprintf(f, " ");
232                 }
233                 fprintf(f, "\n\t},\n");
234 #else
235                 for (int i = 0; i < w*h * 3; i+=3) {
236                         if (data[i] < 0.01) printf(" ");
237                         else if (data[i] < 0.3) printf(".");
238                         else if (data[i] < 0.6) printf("+");
239                         else if (data[i] < 0.9) printf("%%");
240                         else printf("#");
241                         if ((i/3+1) % 64 == 0) printf("\n");
242                 }
243 #endif
244
245         } while (roughness < 1.0f);
246         fprintf(f, "\n};\n");
247
248         fclose(f);
249
250         MEM_freeN(texels);
251         MEM_freeN(data);
252
253         return tex;
254 }
255 #endif
256 /* XXX TODO define all shared resources in a shared place without duplication */
257 struct GPUTexture *EEVEE_materials_get_util_tex(void)
258 {
259         return e_data.util_tex;
260 }
261
262 static int eevee_material_shadow_option(int shadow_method)
263 {
264         switch (shadow_method) {
265                 case SHADOW_ESM: return VAR_MAT_ESM;
266                 case SHADOW_VSM: return VAR_MAT_VSM;
267                 default:
268                         BLI_assert(!"Incorrect Shadow Method");
269                         break;
270         }
271
272         return 0;
273 }
274
275 static char *eevee_get_defines(int options)
276 {
277         char *str = NULL;
278
279         DynStr *ds = BLI_dynstr_new();
280         BLI_dynstr_appendf(ds, SHADER_DEFINES);
281
282         if ((options & VAR_MAT_MESH) != 0) {
283                 BLI_dynstr_appendf(ds, "#define MESH_SHADER\n");
284         }
285         if ((options & VAR_MAT_HAIR) != 0) {
286                 BLI_dynstr_appendf(ds, "#define HAIR_SHADER\n");
287         }
288         if ((options & VAR_MAT_PROBE) != 0) {
289                 BLI_dynstr_appendf(ds, "#define PROBE_CAPTURE\n");
290         }
291         if ((options & VAR_MAT_FLAT) != 0) {
292                 BLI_dynstr_appendf(ds, "#define USE_FLAT_NORMAL\n");
293         }
294         if ((options & VAR_MAT_CLIP) != 0) {
295                 BLI_dynstr_appendf(ds, "#define USE_ALPHA_CLIP\n");
296         }
297         if ((options & VAR_MAT_SHADOW) != 0) {
298                 BLI_dynstr_appendf(ds, "#define SHADOW_SHADER\n");
299         }
300         if ((options & VAR_MAT_HASH) != 0) {
301                 BLI_dynstr_appendf(ds, "#define USE_ALPHA_HASH\n");
302         }
303         if ((options & VAR_MAT_BLEND) != 0) {
304                 BLI_dynstr_appendf(ds, "#define USE_ALPHA_BLEND\n");
305         }
306         if ((options & VAR_MAT_MULT) != 0) {
307                 BLI_dynstr_appendf(ds, "#define USE_MULTIPLY\n");
308         }
309         if ((options & VAR_MAT_REFRACT) != 0) {
310                 BLI_dynstr_appendf(ds, "#define USE_REFRACTION\n");
311         }
312         if ((options & VAR_MAT_SSS) != 0) {
313                 BLI_dynstr_appendf(ds, "#define USE_SSS\n");
314         }
315         if ((options & VAR_MAT_SSSALBED) != 0) {
316                 BLI_dynstr_appendf(ds, "#define USE_SSS_ALBEDO\n");
317         }
318         if ((options & VAR_MAT_TRANSLUC) != 0) {
319                 BLI_dynstr_appendf(ds, "#define USE_TRANSLUCENCY\n");
320         }
321         if ((options & VAR_MAT_VSM) != 0) {
322                 BLI_dynstr_appendf(ds, "#define SHADOW_VSM\n");
323         }
324         if ((options & VAR_MAT_ESM) != 0) {
325                 BLI_dynstr_appendf(ds, "#define SHADOW_ESM\n");
326         }
327         if (((options & VAR_MAT_VOLUME) != 0) && ((options & VAR_MAT_BLEND) != 0)) {
328                 BLI_dynstr_appendf(ds, "#define USE_ALPHA_BLEND_VOLUMETRICS\n");
329         }
330         if ((options & VAR_MAT_LOOKDEV) != 0) {
331                 BLI_dynstr_appendf(ds, "#define LOOKDEV\n");
332         }
333
334         str = BLI_dynstr_get_cstring(ds);
335         BLI_dynstr_free(ds);
336
337         return str;
338 }
339
340 static char *eevee_get_volume_defines(int options)
341 {
342         char *str = NULL;
343
344         DynStr *ds = BLI_dynstr_new();
345         BLI_dynstr_appendf(ds, SHADER_DEFINES);
346         BLI_dynstr_appendf(ds, "#define VOLUMETRICS\n");
347
348         if ((options & VAR_MAT_VOLUME) != 0) {
349                 BLI_dynstr_appendf(ds, "#define MESH_SHADER\n");
350         }
351
352         str = BLI_dynstr_get_cstring(ds);
353         BLI_dynstr_free(ds);
354
355         return str;
356 }
357
358 /**
359  * ssr_id can be null to disable ssr contribution.
360  **/
361 static void add_standard_uniforms(
362         DRWShadingGroup *shgrp, EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata,
363         int *ssr_id, float *refract_depth,
364         bool use_diffuse, bool use_glossy, bool use_refract,
365         bool use_ssrefraction, bool use_alpha_blend)
366 {
367         LightCache *lcache = vedata->stl->g_data->light_cache;
368
369         if (ssr_id == NULL) {
370                 static int no_ssr = -1.0f;
371                 ssr_id = &no_ssr;
372         }
373
374         DRW_shgroup_uniform_block(shgrp, "probe_block", sldata->probe_ubo);
375         DRW_shgroup_uniform_block(shgrp, "grid_block", sldata->grid_ubo);
376         DRW_shgroup_uniform_block(shgrp, "planar_block", sldata->planar_ubo);
377         DRW_shgroup_uniform_block(shgrp, "light_block", sldata->light_ubo);
378         DRW_shgroup_uniform_block(shgrp, "shadow_block", sldata->shadow_ubo);
379         DRW_shgroup_uniform_block(shgrp, "common_block", sldata->common_ubo);
380         DRW_shgroup_uniform_block(shgrp, "clip_block", sldata->clip_ubo);
381
382         if (use_diffuse || use_glossy || use_refract) {
383                 DRW_shgroup_uniform_texture(shgrp, "utilTex", e_data.util_tex);
384                 DRW_shgroup_uniform_texture_ref(shgrp, "shadowCubeTexture", &sldata->shadow_cube_pool);
385                 DRW_shgroup_uniform_texture_ref(shgrp, "shadowCascadeTexture", &sldata->shadow_cascade_pool);
386                 DRW_shgroup_uniform_texture_ref(shgrp, "maxzBuffer", &vedata->txl->maxzbuffer);
387         }
388         if ((use_diffuse || use_glossy) && !use_refract) {
389                 if ((vedata->stl->effects->enabled_effects & EFFECT_GTAO) != 0) {
390                         DRW_shgroup_uniform_texture_ref(shgrp, "horizonBuffer", &vedata->stl->effects->gtao_horizons);
391                 }
392                 else {
393                         /* Use maxzbuffer as fallback to avoid sampling problem on certain platform, see: T52593 */
394                         DRW_shgroup_uniform_texture_ref(shgrp, "horizonBuffer", &vedata->txl->maxzbuffer);
395                 }
396         }
397         if (use_diffuse) {
398                 DRW_shgroup_uniform_texture_ref(shgrp, "irradianceGrid", &lcache->grid_tx.tex);
399         }
400         if (use_glossy || use_refract) {
401                 DRW_shgroup_uniform_texture_ref(shgrp, "probeCubes", &lcache->cube_tx.tex);
402         }
403         if (use_glossy) {
404                 DRW_shgroup_uniform_texture_ref(shgrp, "probePlanars", &vedata->txl->planar_pool);
405                 DRW_shgroup_uniform_int(shgrp, "outputSsrId", ssr_id, 1);
406         }
407         if (use_refract && use_ssrefraction) {
408                 BLI_assert(refract_depth != NULL);
409                 DRW_shgroup_uniform_float(shgrp, "refractionDepth", refract_depth, 1);
410                 DRW_shgroup_uniform_texture_ref(shgrp, "colorBuffer", &vedata->txl->refract_color);
411         }
412
413         if ((vedata->stl->effects->enabled_effects & EFFECT_VOLUMETRIC) != 0 &&
414              use_alpha_blend)
415         {
416                 /* Do not use history buffers as they already have been swapped */
417                 DRW_shgroup_uniform_texture_ref(shgrp, "inScattering", &vedata->txl->volume_scatter);
418                 DRW_shgroup_uniform_texture_ref(shgrp, "inTransmittance", &vedata->txl->volume_transmittance);
419         }
420 }
421
422 static void create_default_shader(int options)
423 {
424         char *frag_str = BLI_string_joinN(
425                 e_data.frag_shader_lib,
426                 datatoc_default_frag_glsl);
427
428         char *defines = eevee_get_defines(options);
429
430         e_data.default_lit[options] = DRW_shader_create(e_data.vert_shader_str, NULL, frag_str, defines);
431
432         MEM_freeN(defines);
433         MEM_freeN(frag_str);
434 }
435
436 static void eevee_init_noise_texture(void)
437 {
438         e_data.noise_tex = DRW_texture_create_2D(64, 64, GPU_RGBA16F, 0, (float *)blue_noise);
439 }
440
441 static void eevee_init_util_texture(void)
442 {
443         const int layers = 3 + 16;
444         float (*texels)[4] = MEM_mallocN(sizeof(float[4]) * 64 * 64 * layers, "utils texels");
445         float (*texels_layer)[4] = texels;
446
447         /* Copy ltc_mat_ggx into 1st layer */
448         memcpy(texels_layer, ltc_mat_ggx, sizeof(float[4]) * 64 * 64);
449         texels_layer += 64 * 64;
450
451         /* Copy bsdf_split_sum_ggx into 2nd layer red and green channels.
452            Copy ltc_mag_ggx into 2nd layer blue channel. */
453         for (int i = 0; i < 64 * 64; i++) {
454                 texels_layer[i][0] = bsdf_split_sum_ggx[i * 2 + 0];
455                 texels_layer[i][1] = bsdf_split_sum_ggx[i * 2 + 1];
456                 texels_layer[i][2] = ltc_mag_ggx[i];
457                 texels_layer[i][3] = ltc_disk_integral[i];
458         }
459         texels_layer += 64 * 64;
460
461         /* Copy blue noise in 3rd layer  */
462         for (int i = 0; i < 64 * 64; i++) {
463                 texels_layer[i][0] = blue_noise[i][0];
464                 texels_layer[i][1] = blue_noise[i][2];
465                 texels_layer[i][2] = cosf(blue_noise[i][1] * 2.0f * M_PI);
466                 texels_layer[i][3] = sinf(blue_noise[i][1] * 2.0f * M_PI);
467         }
468         texels_layer += 64 * 64;
469
470         /* Copy Refraction GGX LUT in layer 4 - 20 */
471         for (int j = 0; j < 16; ++j) {
472                 for (int i = 0; i < 64 * 64; i++) {
473                         texels_layer[i][0] = btdf_split_sum_ggx[j * 2][i];
474                         texels_layer[i][1] = btdf_split_sum_ggx[j * 2][i];
475                         texels_layer[i][2] = btdf_split_sum_ggx[j * 2][i];
476                         texels_layer[i][3] = btdf_split_sum_ggx[j * 2][i];
477                 }
478                 texels_layer += 64 * 64;
479         }
480
481         e_data.util_tex = DRW_texture_create_2D_array(
482                 64, 64, layers, GPU_RGBA16F, DRW_TEX_FILTER | DRW_TEX_WRAP, (float *)texels);
483
484         MEM_freeN(texels);
485 }
486
487 void EEVEE_update_noise(EEVEE_PassList *psl, EEVEE_FramebufferList *fbl, const double offsets[3])
488 {
489         e_data.noise_offsets[0] = offsets[0];
490         e_data.noise_offsets[1] = offsets[1];
491         e_data.noise_offsets[2] = offsets[2];
492
493         /* Attach & detach because we don't currently support multiple FB per texture,
494          * and this would be the case for multiple viewport. */
495         GPU_framebuffer_bind(fbl->update_noise_fb);
496         DRW_draw_pass(psl->update_noise_pass);
497 }
498
499 static void EEVEE_update_viewvecs(float invproj[4][4], float winmat[4][4], float (*r_viewvecs)[4])
500 {
501         /* view vectors for the corners of the view frustum.
502          * Can be used to recreate the world space position easily */
503         float view_vecs[4][4] = {
504             {-1.0f, -1.0f, -1.0f, 1.0f},
505             { 1.0f, -1.0f, -1.0f, 1.0f},
506             {-1.0f,  1.0f, -1.0f, 1.0f},
507             {-1.0f, -1.0f,  1.0f, 1.0f}
508         };
509
510         /* convert the view vectors to view space */
511         const bool is_persp = (winmat[3][3] == 0.0f);
512         for (int i = 0; i < 4; i++) {
513                 mul_project_m4_v3(invproj, view_vecs[i]);
514                 /* normalized trick see:
515                  * http://www.derschmale.com/2014/01/26/reconstructing-positions-from-the-depth-buffer */
516                 if (is_persp) {
517                         /* Divide XY by Z. */
518                         mul_v2_fl(view_vecs[i], 1.0f / view_vecs[i][2]);
519                 }
520         }
521
522         /**
523          * If ortho : view_vecs[0] is the near-bottom-left corner of the frustum and
524          *            view_vecs[1] is the vector going from the near-bottom-left corner to
525          *            the far-top-right corner.
526          * If Persp : view_vecs[0].xy and view_vecs[1].xy are respectively the bottom-left corner
527          *            when Z = 1, and top-left corner if Z = 1.
528          *            view_vecs[0].z the near clip distance and view_vecs[1].z is the (signed)
529          *            distance from the near plane to the far clip plane.
530          **/
531         copy_v4_v4(r_viewvecs[0], view_vecs[0]);
532
533         /* we need to store the differences */
534         r_viewvecs[1][0] = view_vecs[1][0] - view_vecs[0][0];
535         r_viewvecs[1][1] = view_vecs[2][1] - view_vecs[0][1];
536         r_viewvecs[1][2] = view_vecs[3][2] - view_vecs[0][2];
537 }
538
539 void EEVEE_materials_init(EEVEE_ViewLayerData *sldata, EEVEE_StorageList *stl, EEVEE_FramebufferList *fbl)
540 {
541         if (!e_data.frag_shader_lib) {
542                 /* Shaders */
543                 e_data.frag_shader_lib = BLI_string_joinN(
544                         datatoc_common_view_lib_glsl,
545                         datatoc_common_uniforms_lib_glsl,
546                         datatoc_bsdf_common_lib_glsl,
547                         datatoc_bsdf_sampling_lib_glsl,
548                         datatoc_ambient_occlusion_lib_glsl,
549                         datatoc_raytrace_lib_glsl,
550                         datatoc_ssr_lib_glsl,
551                         datatoc_octahedron_lib_glsl,
552                         datatoc_irradiance_lib_glsl,
553                         datatoc_lightprobe_lib_glsl,
554                         datatoc_ltc_lib_glsl,
555                         datatoc_lamps_lib_glsl,
556                         /* Add one for each Closure */
557                         datatoc_lit_surface_frag_glsl,
558                         datatoc_lit_surface_frag_glsl,
559                         datatoc_lit_surface_frag_glsl,
560                         datatoc_lit_surface_frag_glsl,
561                         datatoc_lit_surface_frag_glsl,
562                         datatoc_lit_surface_frag_glsl,
563                         datatoc_lit_surface_frag_glsl,
564                         datatoc_lit_surface_frag_glsl,
565                         datatoc_lit_surface_frag_glsl,
566                         datatoc_lit_surface_frag_glsl,
567                         datatoc_volumetric_lib_glsl);
568
569                 e_data.volume_shader_lib = BLI_string_joinN(
570                         datatoc_common_view_lib_glsl,
571                         datatoc_common_uniforms_lib_glsl,
572                         datatoc_bsdf_common_lib_glsl,
573                         datatoc_ambient_occlusion_lib_glsl,
574                         datatoc_octahedron_lib_glsl,
575                         datatoc_irradiance_lib_glsl,
576                         datatoc_lightprobe_lib_glsl,
577                         datatoc_ltc_lib_glsl,
578                         datatoc_lamps_lib_glsl,
579                         datatoc_volumetric_lib_glsl,
580                         datatoc_volumetric_frag_glsl);
581
582                 e_data.vert_shader_str = BLI_string_joinN(
583                         datatoc_common_view_lib_glsl,
584                         datatoc_common_hair_lib_glsl,
585                         datatoc_lit_surface_vert_glsl);
586
587                 e_data.default_background = DRW_shader_create(
588                         datatoc_background_vert_glsl, NULL, datatoc_default_world_frag_glsl,
589                         NULL);
590
591                 e_data.default_studiolight_background = DRW_shader_create(
592                         datatoc_background_vert_glsl, NULL, datatoc_default_world_frag_glsl,
593                         "#define LOOKDEV\n");
594
595                 e_data.default_prepass_sh = DRW_shader_create(
596                         datatoc_prepass_vert_glsl, NULL, datatoc_prepass_frag_glsl,
597                         NULL);
598
599                 e_data.default_prepass_clip_sh = DRW_shader_create(
600                         datatoc_prepass_vert_glsl, NULL, datatoc_prepass_frag_glsl,
601                         "#define CLIP_PLANES\n");
602
603                 char *vert_str = BLI_string_joinN(
604                         datatoc_common_view_lib_glsl,
605                         datatoc_common_hair_lib_glsl,
606                         datatoc_prepass_vert_glsl);
607
608                 e_data.default_hair_prepass_sh = DRW_shader_create(
609                         vert_str, NULL, datatoc_prepass_frag_glsl,
610                         "#define HAIR_SHADER\n");
611
612                 e_data.default_hair_prepass_clip_sh = DRW_shader_create(
613                         vert_str, NULL, datatoc_prepass_frag_glsl,
614                         "#define HAIR_SHADER\n"
615                         "#define CLIP_PLANES\n");
616
617                 MEM_freeN(vert_str);
618
619                 e_data.update_noise_sh = DRW_shader_create_fullscreen(
620                         datatoc_update_noise_frag_glsl, NULL);
621
622                 eevee_init_util_texture();
623                 eevee_init_noise_texture();
624         }
625
626         if (!DRW_state_is_image_render() &&
627             ((stl->effects->enabled_effects & EFFECT_TAA) == 0))
628         {
629                 e_data.alpha_hash_offset = 0.0f;
630         }
631         else {
632                 double r;
633                 BLI_halton_1D(5, 0.0, stl->effects->taa_current_sample - 1, &r);
634                 e_data.alpha_hash_offset = (float)r;
635         }
636
637         {
638                 /* Update view_vecs */
639                 float invproj[4][4], winmat[4][4];
640                 DRW_viewport_matrix_get(winmat, DRW_MAT_WIN);
641                 DRW_viewport_matrix_get(invproj, DRW_MAT_WININV);
642
643                 EEVEE_update_viewvecs(invproj, winmat, sldata->common_data.view_vecs);
644         }
645
646         {
647                 /* Update noise Framebuffer. */
648                 GPU_framebuffer_ensure_config(&fbl->update_noise_fb, {
649                         GPU_ATTACHMENT_NONE,
650                         GPU_ATTACHMENT_TEXTURE_LAYER(e_data.util_tex, 2)
651                 });
652         }
653 }
654
655 struct GPUMaterial *EEVEE_material_world_lightprobe_get(struct Scene *scene, World *wo)
656 {
657         const void *engine = &DRW_engine_viewport_eevee_type;
658         const int options = VAR_WORLD_PROBE;
659
660         GPUMaterial *mat = DRW_shader_find_from_world(wo, engine, options, false);
661         if (mat != NULL) {
662                 return mat;
663         }
664         return DRW_shader_create_from_world(
665                 scene, wo, engine, options,
666                 datatoc_background_vert_glsl, NULL, e_data.frag_shader_lib,
667                 SHADER_DEFINES "#define PROBE_CAPTURE\n", false);
668 }
669
670 struct GPUMaterial *EEVEE_material_world_background_get(struct Scene *scene, World *wo)
671 {
672         const void *engine = &DRW_engine_viewport_eevee_type;
673         int options = VAR_WORLD_BACKGROUND;
674
675         GPUMaterial *mat = DRW_shader_find_from_world(wo, engine, options, true);
676         if (mat != NULL) {
677                 return mat;
678         }
679         return DRW_shader_create_from_world(
680                 scene, wo, engine, options,
681                 datatoc_background_vert_glsl, NULL, e_data.frag_shader_lib,
682                 SHADER_DEFINES "#define WORLD_BACKGROUND\n", true);
683 }
684
685 struct GPUMaterial *EEVEE_material_world_volume_get(struct Scene *scene, World *wo)
686 {
687         const void *engine = &DRW_engine_viewport_eevee_type;
688         int options = VAR_WORLD_VOLUME;
689
690         GPUMaterial *mat = DRW_shader_find_from_world(wo, engine, options, true);
691         if (mat != NULL) {
692                 return mat;
693         }
694
695         char *defines = eevee_get_volume_defines(options);
696
697         mat = DRW_shader_create_from_world(
698                 scene, wo, engine, options,
699                 datatoc_volumetric_vert_glsl, datatoc_volumetric_geom_glsl, e_data.volume_shader_lib,
700                 defines, true);
701
702         MEM_freeN(defines);
703
704         return mat;
705 }
706
707 struct GPUMaterial *EEVEE_material_mesh_get(
708         struct Scene *scene, Material *ma, EEVEE_Data *vedata,
709         bool use_blend, bool use_multiply, bool use_refract, bool use_sss, bool use_translucency, int shadow_method)
710 {
711         EEVEE_EffectsInfo *effects = vedata->stl->effects;
712         const void *engine = &DRW_engine_viewport_eevee_type;
713         int options = VAR_MAT_MESH;
714
715         if (use_blend) options |= VAR_MAT_BLEND;
716         if (use_multiply) options |= VAR_MAT_MULT;
717         if (use_refract) options |= VAR_MAT_REFRACT;
718         if (use_sss) options |= VAR_MAT_SSS;
719         if (use_sss && effects->sss_separate_albedo) options |= VAR_MAT_SSSALBED;
720         if (use_translucency) options |= VAR_MAT_TRANSLUC;
721         if (((effects->enabled_effects & EFFECT_VOLUMETRIC) != 0) && use_blend) options |= VAR_MAT_VOLUME;
722
723         options |= eevee_material_shadow_option(shadow_method);
724
725         GPUMaterial *mat = DRW_shader_find_from_material(ma, engine, options, true);
726         if (mat) {
727                 return mat;
728         }
729
730         char *defines = eevee_get_defines(options);
731
732         mat = DRW_shader_create_from_material(
733                 scene, ma, engine, options,
734                 e_data.vert_shader_str, NULL, e_data.frag_shader_lib,
735                 defines, true);
736
737         MEM_freeN(defines);
738
739         return mat;
740 }
741
742 struct GPUMaterial *EEVEE_material_mesh_volume_get(struct Scene *scene, Material *ma)
743 {
744         const void *engine = &DRW_engine_viewport_eevee_type;
745         int options = VAR_MAT_VOLUME;
746
747         GPUMaterial *mat = DRW_shader_find_from_material(ma, engine, options, true);
748         if (mat != NULL) {
749                 return mat;
750         }
751
752         char *defines = eevee_get_volume_defines(options);
753
754         mat = DRW_shader_create_from_material(
755                 scene, ma, engine, options,
756                 datatoc_volumetric_vert_glsl, datatoc_volumetric_geom_glsl, e_data.volume_shader_lib,
757                 defines, true);
758
759         MEM_freeN(defines);
760
761         return mat;
762 }
763
764 struct GPUMaterial *EEVEE_material_mesh_depth_get(
765         struct Scene *scene, Material *ma,
766         bool use_hashed_alpha, bool is_shadow)
767 {
768         const void *engine = &DRW_engine_viewport_eevee_type;
769         int options = VAR_MAT_MESH;
770
771         if (use_hashed_alpha) {
772                 options |= VAR_MAT_HASH;
773         }
774         else {
775                 options |= VAR_MAT_CLIP;
776         }
777
778         if (is_shadow)
779                 options |= VAR_MAT_SHADOW;
780
781         GPUMaterial *mat = DRW_shader_find_from_material(ma, engine, options, true);
782         if (mat) {
783                 return mat;
784         }
785
786         char *defines = eevee_get_defines(options);
787
788         char *frag_str = BLI_string_joinN(
789                 e_data.frag_shader_lib,
790                 datatoc_prepass_frag_glsl);
791
792         mat = DRW_shader_create_from_material(
793                 scene, ma, engine, options,
794                 (is_shadow) ? datatoc_shadow_vert_glsl : e_data.vert_shader_str,
795                 NULL,
796                 frag_str,
797                 defines,
798                 true);
799
800         MEM_freeN(frag_str);
801         MEM_freeN(defines);
802
803         return mat;
804 }
805
806 struct GPUMaterial *EEVEE_material_hair_get(
807         struct Scene *scene, Material *ma, int shadow_method)
808 {
809         const void *engine = &DRW_engine_viewport_eevee_type;
810         int options = VAR_MAT_MESH | VAR_MAT_HAIR;
811
812         options |= eevee_material_shadow_option(shadow_method);
813
814         GPUMaterial *mat = DRW_shader_find_from_material(ma, engine, options, true);
815         if (mat) {
816                 return mat;
817         }
818
819         char *defines = eevee_get_defines(options);
820
821         mat = DRW_shader_create_from_material(
822                 scene, ma, engine, options,
823                 e_data.vert_shader_str, NULL, e_data.frag_shader_lib,
824                 defines, true);
825
826         MEM_freeN(defines);
827
828         return mat;
829 }
830
831 /**
832  * Create a default shading group inside the given pass.
833  **/
834 static struct DRWShadingGroup *EEVEE_default_shading_group_create(
835         EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata, DRWPass *pass,
836         bool is_hair, bool is_flat_normal, bool use_blend, bool use_ssr, int shadow_method)
837 {
838         EEVEE_EffectsInfo *effects = vedata->stl->effects;
839         static int ssr_id;
840         ssr_id = (use_ssr) ? 1 : -1;
841         int options = VAR_MAT_MESH;
842
843         if (is_hair) options |= VAR_MAT_HAIR;
844         if (is_flat_normal) options |= VAR_MAT_FLAT;
845         if (use_blend) options |= VAR_MAT_BLEND;
846         if (((effects->enabled_effects & EFFECT_VOLUMETRIC) != 0) && use_blend) options |= VAR_MAT_VOLUME;
847
848         options |= eevee_material_shadow_option(shadow_method);
849
850         if (e_data.default_lit[options] == NULL) {
851                 create_default_shader(options);
852         }
853
854         DRWShadingGroup *shgrp = DRW_shgroup_create(e_data.default_lit[options], pass);
855         add_standard_uniforms(shgrp, sldata, vedata, &ssr_id, NULL, true, true, false, false, use_blend);
856
857         return shgrp;
858 }
859
860 /**
861  * Create a default shading group inside the default pass without standard uniforms.
862  **/
863 static struct DRWShadingGroup *EEVEE_default_shading_group_get(
864         EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata,
865         Object *ob, ParticleSystem *psys, ModifierData *md,
866         bool is_hair, bool is_flat_normal, bool use_ssr, int shadow_method)
867 {
868         static int ssr_id;
869         ssr_id = (use_ssr) ? 1 : -1;
870         int options = VAR_MAT_MESH;
871
872         BLI_assert(!is_hair || (ob && psys && md));
873
874         if (is_hair) options |= VAR_MAT_HAIR;
875         if (is_flat_normal) options |= VAR_MAT_FLAT;
876
877         options |= eevee_material_shadow_option(shadow_method);
878
879         if (e_data.default_lit[options] == NULL) {
880                 create_default_shader(options);
881         }
882
883         if (vedata->psl->default_pass[options] == NULL) {
884                 DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_DEPTH_EQUAL | DRW_STATE_CLIP_PLANES | DRW_STATE_WIRE;
885                 vedata->psl->default_pass[options] = DRW_pass_create("Default Lit Pass", state);
886
887                 /* XXX / WATCH: This creates non persistent binds for the ubos and textures.
888                  * But it's currently OK because the following shgroups does not add any bind.
889                  * EDIT: THIS IS NOT THE CASE FOR HAIRS !!! DUMMY!!! */
890                 if (!is_hair) {
891                         DRWShadingGroup *shgrp = DRW_shgroup_create(e_data.default_lit[options], vedata->psl->default_pass[options]);
892                         add_standard_uniforms(shgrp, sldata, vedata, &ssr_id, NULL, true, true, false, false, false);
893                 }
894         }
895
896         if (is_hair) {
897                 DRWShadingGroup *shgrp = DRW_shgroup_hair_create(ob, psys, md,
898                                                                  vedata->psl->default_pass[options],
899                                                                  e_data.default_lit[options]);
900                 add_standard_uniforms(shgrp, sldata, vedata, &ssr_id, NULL, true, true, false, false, false);
901                 return shgrp;
902         }
903         else {
904                 return DRW_shgroup_create(e_data.default_lit[options], vedata->psl->default_pass[options]);
905         }
906 }
907
908 /**
909  * Create a default shading group inside the lookdev pass without standard uniforms.
910  **/
911 static struct DRWShadingGroup *EEVEE_lookdev_shading_group_get(
912         EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata,
913         bool use_ssr, int shadow_method)
914 {
915         static int ssr_id;
916         ssr_id = (use_ssr) ? 1 : -1;
917         int options = VAR_MAT_MESH | VAR_MAT_LOOKDEV;
918
919         options |= eevee_material_shadow_option(shadow_method);
920
921         if (e_data.default_lit[options] == NULL) {
922                 create_default_shader(options);
923         }
924
925         if (vedata->psl->lookdev_pass == NULL) {
926                 DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_ALWAYS | DRW_STATE_CULL_BACK;
927                 vedata->psl->lookdev_pass = DRW_pass_create("LookDev Pass", state);
928
929                 DRWShadingGroup *shgrp = DRW_shgroup_create(e_data.default_lit[options], vedata->psl->lookdev_pass);
930                 /* XXX / WATCH: This creates non persistent binds for the ubos and textures.
931                  * But it's currently OK because the following shgroups does not add any bind. */
932                 add_standard_uniforms(shgrp, sldata, vedata, &ssr_id, NULL, true, true, false, false, false);
933         }
934
935         return DRW_shgroup_create(e_data.default_lit[options], vedata->psl->lookdev_pass);
936 }
937 void EEVEE_materials_cache_init(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
938 {
939         EEVEE_PassList *psl = ((EEVEE_Data *)vedata)->psl;
940         EEVEE_StorageList *stl = ((EEVEE_Data *)vedata)->stl;
941
942         /* Create Material Ghash */
943         {
944                 stl->g_data->material_hash = BLI_ghash_ptr_new("Eevee_material ghash");
945         }
946
947         {
948                 psl->background_pass = DRW_pass_create("Background Pass", DRW_STATE_WRITE_COLOR | DRW_STATE_DEPTH_EQUAL);
949
950                 struct GPUBatch *geom = DRW_cache_fullscreen_quad_get();
951                 DRWShadingGroup *grp = NULL;
952
953                 const DRWContextState *draw_ctx = DRW_context_state_get();
954                 Scene *scene = draw_ctx->scene;
955                 World *wo = scene->world;
956
957                 float *col = ts.colorBackground;
958
959                 /* LookDev */
960                 EEVEE_lookdev_cache_init(vedata, &grp, e_data.default_studiolight_background, psl->background_pass, wo, NULL);
961                 /* END */
962
963                 if (!grp && wo) {
964                         col = &wo->horr;
965
966                         if (wo->use_nodes && wo->nodetree) {
967                                 static float error_col[3] = {1.0f, 0.0f, 1.0f};
968                                 static float compile_col[3] = {0.5f, 0.5f, 0.5f};
969                                 struct GPUMaterial *gpumat = EEVEE_material_world_background_get(scene, wo);
970
971                                 switch (GPU_material_status(gpumat)) {
972                                         case GPU_MAT_SUCCESS:
973                                                 grp = DRW_shgroup_material_create(gpumat, psl->background_pass);
974                                                 DRW_shgroup_uniform_float(grp, "backgroundAlpha", &stl->g_data->background_alpha, 1);
975                                                 /* TODO (fclem): remove those (need to clean the GLSL files). */
976                                                 DRW_shgroup_uniform_block(grp, "common_block", sldata->common_ubo);
977                                                 DRW_shgroup_uniform_block(grp, "grid_block", sldata->grid_ubo);
978                                                 DRW_shgroup_uniform_block(grp, "probe_block", sldata->probe_ubo);
979                                                 DRW_shgroup_uniform_block(grp, "planar_block", sldata->planar_ubo);
980                                                 DRW_shgroup_uniform_block(grp, "light_block", sldata->light_ubo);
981                                                 DRW_shgroup_uniform_block(grp, "shadow_block", sldata->shadow_ubo);
982                                                 DRW_shgroup_call_add(grp, geom, NULL);
983                                                 break;
984                                         case GPU_MAT_QUEUED:
985                                                 /* TODO Bypass probe compilation. */
986                                                 col = compile_col;
987                                                 break;
988                                         case GPU_MAT_FAILED:
989                                         default:
990                                                 col = error_col;
991                                                 break;
992                                 }
993                         }
994                 }
995
996                 /* Fallback if shader fails or if not using nodetree. */
997                 if (grp == NULL) {
998                         grp = DRW_shgroup_create(e_data.default_background, psl->background_pass);
999                         DRW_shgroup_uniform_vec3(grp, "color", col, 1);
1000                         DRW_shgroup_uniform_float(grp, "backgroundAlpha", &stl->g_data->background_alpha, 1);
1001                         DRW_shgroup_call_add(grp, geom, NULL);
1002                 }
1003         }
1004
1005         {
1006                 DRWState state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_WIRE;
1007                 psl->depth_pass = DRW_pass_create("Depth Pass", state);
1008                 stl->g_data->depth_shgrp = DRW_shgroup_create(e_data.default_prepass_sh, psl->depth_pass);
1009
1010                 state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CULL_BACK;
1011                 psl->depth_pass_cull = DRW_pass_create("Depth Pass Cull", state);
1012                 stl->g_data->depth_shgrp_cull = DRW_shgroup_create(e_data.default_prepass_sh, psl->depth_pass_cull);
1013
1014                 state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CLIP_PLANES | DRW_STATE_WIRE;
1015                 psl->depth_pass_clip = DRW_pass_create("Depth Pass Clip", state);
1016                 stl->g_data->depth_shgrp_clip = DRW_shgroup_create(e_data.default_prepass_clip_sh, psl->depth_pass_clip);
1017                 DRW_shgroup_uniform_block(stl->g_data->depth_shgrp_clip, "clip_block", sldata->clip_ubo);
1018
1019                 state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CLIP_PLANES | DRW_STATE_CULL_BACK;
1020                 psl->depth_pass_clip_cull = DRW_pass_create("Depth Pass Cull Clip", state);
1021                 stl->g_data->depth_shgrp_clip_cull = DRW_shgroup_create(
1022                         e_data.default_prepass_clip_sh, psl->depth_pass_clip_cull);
1023                 DRW_shgroup_uniform_block(stl->g_data->depth_shgrp_clip_cull, "clip_block", sldata->clip_ubo);
1024         }
1025
1026         {
1027                 DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_DEPTH_EQUAL | DRW_STATE_CLIP_PLANES | DRW_STATE_WIRE;
1028                 psl->material_pass = DRW_pass_create("Material Shader Pass", state);
1029         }
1030
1031         {
1032                 DRWState state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_WIRE;
1033                 psl->refract_depth_pass = DRW_pass_create("Refract Depth Pass", state);
1034                 stl->g_data->refract_depth_shgrp = DRW_shgroup_create(e_data.default_prepass_sh, psl->refract_depth_pass);
1035
1036                 state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CULL_BACK;
1037                 psl->refract_depth_pass_cull = DRW_pass_create("Refract Depth Pass Cull", state);
1038                 stl->g_data->refract_depth_shgrp_cull = DRW_shgroup_create(
1039                         e_data.default_prepass_sh, psl->refract_depth_pass_cull);
1040
1041                 state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CLIP_PLANES | DRW_STATE_WIRE;
1042                 psl->refract_depth_pass_clip = DRW_pass_create("Refract Depth Pass Clip", state);
1043                 stl->g_data->refract_depth_shgrp_clip = DRW_shgroup_create(
1044                         e_data.default_prepass_clip_sh, psl->refract_depth_pass_clip);
1045                 DRW_shgroup_uniform_block(stl->g_data->refract_depth_shgrp_clip, "clip_block", sldata->clip_ubo);
1046
1047                 state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CLIP_PLANES | DRW_STATE_CULL_BACK;
1048                 psl->refract_depth_pass_clip_cull = DRW_pass_create("Refract Depth Pass Cull Clip", state);
1049                 stl->g_data->refract_depth_shgrp_clip_cull = DRW_shgroup_create(
1050                         e_data.default_prepass_clip_sh, psl->refract_depth_pass_clip_cull);
1051                 DRW_shgroup_uniform_block(stl->g_data->refract_depth_shgrp_clip_cull, "clip_block", sldata->clip_ubo);
1052         }
1053
1054         {
1055                 DRWState state = (
1056                         DRW_STATE_WRITE_COLOR | DRW_STATE_DEPTH_EQUAL | DRW_STATE_CLIP_PLANES |
1057                         DRW_STATE_WIRE);
1058                 psl->refract_pass = DRW_pass_create("Opaque Refraction Pass", state);
1059         }
1060
1061         {
1062                 DRWState state = (
1063                         DRW_STATE_WRITE_COLOR | DRW_STATE_DEPTH_EQUAL | DRW_STATE_CLIP_PLANES |
1064                         DRW_STATE_WIRE | DRW_STATE_WRITE_STENCIL);
1065                 psl->sss_pass = DRW_pass_create("Subsurface Pass", state);
1066                 e_data.sss_count = 0;
1067         }
1068
1069         {
1070                 DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CLIP_PLANES | DRW_STATE_WIRE;
1071                 psl->transparent_pass = DRW_pass_create("Material Transparent Pass", state);
1072         }
1073
1074         {
1075                 psl->update_noise_pass = DRW_pass_create("Update Noise Pass", DRW_STATE_WRITE_COLOR);
1076                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.update_noise_sh, psl->update_noise_pass);
1077                 DRW_shgroup_uniform_texture(grp, "blueNoise", e_data.noise_tex);
1078                 DRW_shgroup_uniform_vec3(grp, "offsets", e_data.noise_offsets, 1);
1079                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
1080         }
1081 }
1082
1083 #define ADD_SHGROUP_CALL(shgrp, ob, ma, geom, oedata) do { \
1084         if (is_sculpt_mode_draw) { \
1085                 DRW_shgroup_call_sculpt_add(shgrp, ob, ob->obmat); \
1086         } \
1087         else { \
1088                 if (oedata) { \
1089                         DRW_shgroup_call_object_add_with_callback(shgrp, geom, ob, ma, EEVEE_lightprobes_obj_visibility_cb, oedata); \
1090                 } \
1091                 else { \
1092                         DRW_shgroup_call_object_add_ex(shgrp, geom, ob, ma, false); \
1093                 } \
1094         } \
1095 } while (0)
1096
1097 #define ADD_SHGROUP_CALL_SAFE(shgrp, ob, ma, geom, oedata) do { \
1098         if (shgrp) { \
1099                 ADD_SHGROUP_CALL(shgrp, ob, ma, geom, oedata); \
1100         } \
1101 } while (0)
1102
1103 typedef struct EeveeMaterialShadingGroups {
1104         struct DRWShadingGroup *shading_grp;
1105         struct DRWShadingGroup *depth_grp;
1106         struct DRWShadingGroup *depth_clip_grp;
1107 } EeveeMaterialShadingGroups;
1108
1109 static void material_opaque(
1110         Material *ma, GHash *material_hash, EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata,
1111         bool do_cull, bool use_flat_nor, struct GPUMaterial **gpumat, struct GPUMaterial **gpumat_depth,
1112         struct DRWShadingGroup **shgrp, struct DRWShadingGroup **shgrp_depth, struct DRWShadingGroup **shgrp_depth_clip)
1113 {
1114         EEVEE_EffectsInfo *effects = vedata->stl->effects;
1115         const DRWContextState *draw_ctx = DRW_context_state_get();
1116         Scene *scene = draw_ctx->scene;
1117         EEVEE_StorageList *stl = ((EEVEE_Data *)vedata)->stl;
1118         EEVEE_PassList *psl = ((EEVEE_Data *)vedata)->psl;
1119         EEVEE_LampsInfo *linfo = sldata->lamps;
1120         bool use_diffuse, use_glossy, use_refract;
1121
1122         float *color_p = &ma->r;
1123         float *metal_p = &ma->metallic;
1124         float *spec_p = &ma->spec;
1125         float *rough_p = &ma->roughness;
1126
1127         const bool use_gpumat = (ma->use_nodes && ma->nodetree);
1128         const bool use_ssrefract = ((ma->blend_flag & MA_BL_SS_REFRACTION) != 0) &&
1129                                  ((effects->enabled_effects & EFFECT_REFRACT) != 0);
1130         bool use_sss = ((effects->enabled_effects & EFFECT_SSS) != 0);
1131         const bool use_translucency = use_sss && ((ma->blend_flag & MA_BL_TRANSLUCENCY) != 0);
1132
1133         EeveeMaterialShadingGroups *emsg = BLI_ghash_lookup(material_hash, (const void *)ma);
1134
1135         if (emsg) {
1136                 *shgrp = emsg->shading_grp;
1137                 *shgrp_depth = emsg->depth_grp;
1138                 *shgrp_depth_clip = emsg->depth_clip_grp;
1139
1140                 /* This will have been created already, just perform a lookup. */
1141                 *gpumat = (use_gpumat) ? EEVEE_material_mesh_get(
1142                         scene, ma, vedata, false, false, use_ssrefract, use_sss, use_translucency, linfo->shadow_method) : NULL;
1143                 *gpumat_depth = (use_gpumat) ? EEVEE_material_mesh_depth_get(
1144                         scene, ma, (ma->blend_method == MA_BM_HASHED), false) : NULL;
1145                 return;
1146         }
1147
1148         if (use_gpumat) {
1149                 static float error_col[3] = {1.0f, 0.0f, 1.0f};
1150                 static float compile_col[3] = {0.5f, 0.5f, 0.5f};
1151                 static float half = 0.5f;
1152
1153                 /* Shading */
1154                 *gpumat = EEVEE_material_mesh_get(
1155                         scene, ma, vedata, false, false, use_ssrefract,
1156                         use_sss, use_translucency, linfo->shadow_method);
1157
1158                 GPUMaterialStatus status_mat_surface = GPU_material_status(*gpumat);
1159
1160                 /* Alpha CLipped : Discard pixel from depth pass, then
1161                  * fail the depth test for shading. */
1162                 if (ELEM(ma->blend_method, MA_BM_CLIP, MA_BM_HASHED)) {
1163                         *gpumat_depth = EEVEE_material_mesh_depth_get(scene, ma, (ma->blend_method == MA_BM_HASHED), false);
1164
1165                         GPUMaterialStatus status_mat_depth = GPU_material_status(*gpumat_depth);
1166                         if (status_mat_depth != GPU_MAT_SUCCESS) {
1167                                 /* Mixing both flags. If depth shader fails, show it to the user by not using
1168                                  * the surface shader. */
1169                                 status_mat_surface = status_mat_depth;
1170                         }
1171                         else if (use_ssrefract) {
1172                                 *shgrp_depth = DRW_shgroup_material_create(
1173                                         *gpumat_depth, (do_cull) ? psl->refract_depth_pass_cull : psl->refract_depth_pass);
1174                                 *shgrp_depth_clip = DRW_shgroup_material_create(
1175                                         *gpumat_depth, (do_cull) ? psl->refract_depth_pass_clip_cull : psl->refract_depth_pass_clip);
1176                         }
1177                         else {
1178                                 *shgrp_depth = DRW_shgroup_material_create(
1179                                         *gpumat_depth, (do_cull) ? psl->depth_pass_cull : psl->depth_pass);
1180                                 *shgrp_depth_clip = DRW_shgroup_material_create(
1181                                         *gpumat_depth, (do_cull) ? psl->depth_pass_clip_cull : psl->depth_pass_clip);
1182                         }
1183
1184                         if (*shgrp_depth != NULL) {
1185                                 use_diffuse = GPU_material_flag_get(*gpumat_depth, GPU_MATFLAG_DIFFUSE);
1186                                 use_glossy = GPU_material_flag_get(*gpumat_depth, GPU_MATFLAG_GLOSSY);
1187                                 use_refract = GPU_material_flag_get(*gpumat_depth, GPU_MATFLAG_REFRACT);
1188
1189                                 add_standard_uniforms(*shgrp_depth, sldata, vedata, NULL, NULL,
1190                                                       use_diffuse, use_glossy, use_refract, false, false);
1191                                 add_standard_uniforms(*shgrp_depth_clip, sldata, vedata, NULL, NULL,
1192                                                       use_diffuse, use_glossy, use_refract, false, false);
1193
1194                                 if (ma->blend_method == MA_BM_CLIP) {
1195                                         DRW_shgroup_uniform_float(*shgrp_depth, "alphaThreshold", &ma->alpha_threshold, 1);
1196                                         DRW_shgroup_uniform_float(*shgrp_depth_clip, "alphaThreshold", &ma->alpha_threshold, 1);
1197                                 }
1198                                 else if (ma->blend_method == MA_BM_HASHED) {
1199                                         DRW_shgroup_uniform_float(*shgrp_depth, "hashAlphaOffset", &e_data.alpha_hash_offset, 1);
1200                                         DRW_shgroup_uniform_float(*shgrp_depth_clip, "hashAlphaOffset", &e_data.alpha_hash_offset, 1);
1201                                 }
1202                         }
1203                 }
1204
1205                 switch (status_mat_surface) {
1206                         case GPU_MAT_SUCCESS:
1207                         {
1208                                 static int no_ssr = -1;
1209                                 static int first_ssr = 1;
1210                                 int *ssr_id = (((effects->enabled_effects & EFFECT_SSR) != 0) && !use_ssrefract) ? &first_ssr : &no_ssr;
1211                                 use_diffuse = GPU_material_flag_get(*gpumat, GPU_MATFLAG_DIFFUSE);
1212                                 use_glossy = GPU_material_flag_get(*gpumat, GPU_MATFLAG_GLOSSY);
1213                                 use_refract = GPU_material_flag_get(*gpumat, GPU_MATFLAG_REFRACT);
1214                                 use_sss = use_sss && GPU_material_flag_get(*gpumat, GPU_MATFLAG_SSS);
1215
1216                                 *shgrp = DRW_shgroup_material_create(
1217                                         *gpumat,
1218                                         (use_ssrefract) ? psl->refract_pass :
1219                                         (use_sss) ? psl->sss_pass : psl->material_pass);
1220
1221                                 add_standard_uniforms(*shgrp, sldata, vedata, ssr_id, &ma->refract_depth,
1222                                                       use_diffuse, use_glossy, use_refract, use_ssrefract, false);
1223
1224                                 if (use_sss) {
1225                                         struct GPUTexture *sss_tex_profile = NULL;
1226                                         struct GPUUniformBuffer *sss_profile = GPU_material_sss_profile_get(
1227                                                 *gpumat,
1228                                                 stl->effects->sss_sample_count,
1229                                                 &sss_tex_profile);
1230
1231                                         if (sss_profile) {
1232                                                 if (use_translucency) {
1233                                                         DRW_shgroup_uniform_block(*shgrp, "sssProfile", sss_profile);
1234                                                         DRW_shgroup_uniform_texture(*shgrp, "sssTexProfile", sss_tex_profile);
1235                                                 }
1236
1237                                                 /* Limit of 8 bit stencil buffer. ID 255 is refraction. */
1238                                                 if (e_data.sss_count < 254) {
1239                                                         DRW_shgroup_stencil_mask(*shgrp, e_data.sss_count + 1);
1240                                                         EEVEE_subsurface_add_pass(sldata, vedata, e_data.sss_count + 1, sss_profile);
1241                                                         e_data.sss_count++;
1242                                                 }
1243                                                 else {
1244                                                         /* TODO : display message. */
1245                                                         printf("Error: Too many different Subsurface shader in the scene.\n");
1246                                                 }
1247                                         }
1248                                 }
1249                                 break;
1250                         }
1251                         case GPU_MAT_QUEUED:
1252                         {
1253                                 color_p = compile_col;
1254                                 metal_p = spec_p = rough_p = &half;
1255                                 break;
1256                         }
1257                         case GPU_MAT_FAILED:
1258                         default:
1259                                 color_p = error_col;
1260                                 metal_p = spec_p = rough_p = &half;
1261                                 break;
1262                 }
1263         }
1264
1265         /* Fallback to default shader */
1266         if (*shgrp == NULL) {
1267                 bool use_ssr = ((effects->enabled_effects & EFFECT_SSR) != 0);
1268                 *shgrp = EEVEE_default_shading_group_get(sldata, vedata,
1269                                                          NULL, NULL, NULL,
1270                                                          false, use_flat_nor, use_ssr, linfo->shadow_method);
1271                 DRW_shgroup_uniform_vec3(*shgrp, "basecol", color_p, 1);
1272                 DRW_shgroup_uniform_float(*shgrp, "metallic", metal_p, 1);
1273                 DRW_shgroup_uniform_float(*shgrp, "specular", spec_p, 1);
1274                 DRW_shgroup_uniform_float(*shgrp, "roughness", rough_p, 1);
1275         }
1276
1277         /* Fallback default depth prepass */
1278         if (*shgrp_depth == NULL) {
1279                 if (use_ssrefract) {
1280                         *shgrp_depth = (do_cull) ? stl->g_data->refract_depth_shgrp_cull : stl->g_data->refract_depth_shgrp;
1281                         *shgrp_depth_clip = (do_cull) ? stl->g_data->refract_depth_shgrp_clip_cull : stl->g_data->refract_depth_shgrp_clip;
1282                 }
1283                 else {
1284                         *shgrp_depth = (do_cull) ? stl->g_data->depth_shgrp_cull : stl->g_data->depth_shgrp;
1285                         *shgrp_depth_clip = (do_cull) ? stl->g_data->depth_shgrp_clip_cull : stl->g_data->depth_shgrp_clip;
1286                 }
1287         }
1288
1289         emsg = MEM_mallocN(sizeof(EeveeMaterialShadingGroups), "EeveeMaterialShadingGroups");
1290         emsg->shading_grp = *shgrp;
1291         emsg->depth_grp = *shgrp_depth;
1292         emsg->depth_clip_grp = *shgrp_depth_clip;
1293         BLI_ghash_insert(material_hash, ma, emsg);
1294 }
1295
1296 static void material_transparent(
1297         Material *ma, EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata,
1298         bool do_cull, bool use_flat_nor,
1299         struct GPUMaterial **gpumat, struct DRWShadingGroup **shgrp, struct DRWShadingGroup **shgrp_depth)
1300 {
1301         const DRWContextState *draw_ctx = DRW_context_state_get();
1302         Scene *scene = draw_ctx->scene;
1303         EEVEE_StorageList *stl = ((EEVEE_Data *)vedata)->stl;
1304         EEVEE_PassList *psl = ((EEVEE_Data *)vedata)->psl;
1305         EEVEE_LampsInfo *linfo = sldata->lamps;
1306
1307         const bool use_ssrefract = (
1308                 ((ma->blend_flag & MA_BL_SS_REFRACTION) != 0) &&
1309                 ((stl->effects->enabled_effects & EFFECT_REFRACT) != 0)
1310         );
1311         float *color_p = &ma->r;
1312         float *metal_p = &ma->metallic;
1313         float *spec_p = &ma->spec;
1314         float *rough_p = &ma->roughness;
1315
1316         if (ma->use_nodes && ma->nodetree) {
1317                 static float error_col[3] = {1.0f, 0.0f, 1.0f};
1318                 static float compile_col[3] = {0.5f, 0.5f, 0.5f};
1319                 static float half = 0.5f;
1320
1321                 /* Shading */
1322                 *gpumat = EEVEE_material_mesh_get(
1323                         scene, ma, vedata, true, (ma->blend_method == MA_BM_MULTIPLY), use_ssrefract,
1324                         false, false, linfo->shadow_method);
1325
1326                 switch (GPU_material_status(*gpumat)) {
1327                         case GPU_MAT_SUCCESS:
1328                         {
1329                                 static int ssr_id = -1; /* TODO transparent SSR */
1330                                 bool use_blend = (ma->blend_method & MA_BM_BLEND) != 0;
1331
1332                                 *shgrp = DRW_shgroup_material_create(*gpumat, psl->transparent_pass);
1333
1334                                 bool use_diffuse = GPU_material_flag_get(*gpumat, GPU_MATFLAG_DIFFUSE);
1335                                 bool use_glossy = GPU_material_flag_get(*gpumat, GPU_MATFLAG_GLOSSY);
1336                                 bool use_refract = GPU_material_flag_get(*gpumat, GPU_MATFLAG_REFRACT);
1337
1338                                 add_standard_uniforms(*shgrp, sldata, vedata, &ssr_id, &ma->refract_depth,
1339                                                       use_diffuse, use_glossy, use_refract, use_ssrefract, use_blend);
1340                                 break;
1341                         }
1342                         case GPU_MAT_QUEUED:
1343                         {
1344                                 /* TODO Bypass probe compilation. */
1345                                 color_p = compile_col;
1346                                 metal_p = spec_p = rough_p = &half;
1347                                 break;
1348                         }
1349                         case GPU_MAT_FAILED:
1350                         default:
1351                                 color_p = error_col;
1352                                 metal_p = spec_p = rough_p = &half;
1353                                 break;
1354                 }
1355         }
1356
1357         /* Fallback to default shader */
1358         if (*shgrp == NULL) {
1359                 *shgrp = EEVEE_default_shading_group_create(
1360                         sldata, vedata, psl->transparent_pass,
1361                         false, use_flat_nor, true, false, linfo->shadow_method);
1362                 DRW_shgroup_uniform_vec3(*shgrp, "basecol", color_p, 1);
1363                 DRW_shgroup_uniform_float(*shgrp, "metallic", metal_p, 1);
1364                 DRW_shgroup_uniform_float(*shgrp, "specular", spec_p, 1);
1365                 DRW_shgroup_uniform_float(*shgrp, "roughness", rough_p, 1);
1366         }
1367
1368         const bool use_prepass = ((ma->blend_flag & MA_BL_HIDE_BACKSIDE) != 0);
1369
1370         DRWState all_state = (
1371                 DRW_STATE_WRITE_DEPTH | DRW_STATE_WRITE_COLOR | DRW_STATE_CULL_BACK |
1372                 DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_DEPTH_EQUAL |
1373                 DRW_STATE_BLEND | DRW_STATE_ADDITIVE | DRW_STATE_MULTIPLY
1374         );
1375
1376         DRWState cur_state = DRW_STATE_WRITE_COLOR;
1377         cur_state |= (use_prepass) ? DRW_STATE_DEPTH_EQUAL : DRW_STATE_DEPTH_LESS_EQUAL;
1378         cur_state |= (do_cull) ? DRW_STATE_CULL_BACK : 0;
1379
1380         switch (ma->blend_method) {
1381                 case MA_BM_ADD:
1382                         cur_state |= DRW_STATE_ADDITIVE;
1383                         break;
1384                 case MA_BM_MULTIPLY:
1385                         cur_state |= DRW_STATE_MULTIPLY;
1386                         break;
1387                 case MA_BM_BLEND:
1388                         cur_state |= DRW_STATE_BLEND;
1389                         break;
1390                 default:
1391                         BLI_assert(0);
1392                         break;
1393         }
1394
1395         /* Disable other blend modes and use the one we want. */
1396         DRW_shgroup_state_disable(*shgrp, all_state);
1397         DRW_shgroup_state_enable(*shgrp, cur_state);
1398
1399         /* Depth prepass */
1400         if (use_prepass) {
1401                 *shgrp_depth = DRW_shgroup_create(e_data.default_prepass_clip_sh, psl->transparent_pass);
1402                 DRW_shgroup_uniform_block(*shgrp_depth, "clip_block", sldata->clip_ubo);
1403
1404                 cur_state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL;
1405                 cur_state |= (do_cull) ? DRW_STATE_CULL_BACK : 0;
1406
1407                 DRW_shgroup_state_disable(*shgrp_depth, all_state);
1408                 DRW_shgroup_state_enable(*shgrp_depth, cur_state);
1409         }
1410 }
1411
1412 void EEVEE_materials_cache_populate(EEVEE_Data *vedata, EEVEE_ViewLayerData *sldata, Object *ob, bool *cast_shadow)
1413 {
1414         EEVEE_PassList *psl = vedata->psl;
1415         EEVEE_StorageList *stl = vedata->stl;
1416         const DRWContextState *draw_ctx = DRW_context_state_get();
1417         Scene *scene = draw_ctx->scene;
1418         GHash *material_hash = stl->g_data->material_hash;
1419
1420         const bool do_cull = (draw_ctx->v3d && (draw_ctx->v3d->flag2 & V3D_BACKFACE_CULLING));
1421         const bool is_active = (ob == draw_ctx->obact);
1422         const bool is_sculpt_mode = is_active && (draw_ctx->object_mode & OB_MODE_SCULPT) != 0;
1423 #if 0
1424         const bool is_sculpt_mode_draw = is_sculpt_mode && (draw_ctx->v3d->flag2 & V3D_SHOW_MODE_SHADE_OVERRIDE) == 0;
1425 #else
1426         /* For now just force fully shaded with eevee when supported. */
1427         const bool is_sculpt_mode_draw =
1428                 is_sculpt_mode &&
1429                 ((ob->sculpt && ob->sculpt->pbvh) && (BKE_pbvh_type(ob->sculpt->pbvh) != PBVH_FACES));
1430 #endif
1431         const bool is_default_mode_shader = is_sculpt_mode;
1432
1433         /* First get materials for this mesh. */
1434         if (ELEM(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL)) {
1435                 const int materials_len = MAX2(1, (is_sculpt_mode_draw ? 1 : ob->totcol));
1436
1437                 struct DRWShadingGroup **shgrp_array = BLI_array_alloca(shgrp_array, materials_len);
1438                 struct DRWShadingGroup **shgrp_depth_array = BLI_array_alloca(shgrp_depth_array, materials_len);
1439                 struct DRWShadingGroup **shgrp_depth_clip_array = BLI_array_alloca(shgrp_depth_clip_array, materials_len);
1440
1441                 struct GPUMaterial **gpumat_array = BLI_array_alloca(gpumat_array, materials_len);
1442                 struct GPUMaterial **gpumat_depth_array = BLI_array_alloca(gpumat_array, materials_len);
1443
1444                 bool use_flat_nor = false;
1445
1446                 if (is_default_mode_shader) {
1447                         if (is_sculpt_mode_draw) {
1448                                 use_flat_nor = DRW_object_is_flat_normal(ob);
1449                         }
1450                 }
1451
1452                 for (int i = 0; i < materials_len; ++i) {
1453                         Material *ma;
1454
1455                         if (is_sculpt_mode_draw) {
1456                                 ma = NULL;
1457                         }
1458                         else {
1459                                 ma = give_current_material(ob, i + 1);
1460                         }
1461
1462                         gpumat_array[i] = NULL;
1463                         gpumat_depth_array[i] = NULL;
1464                         shgrp_array[i] = NULL;
1465                         shgrp_depth_array[i] = NULL;
1466                         shgrp_depth_clip_array[i] = NULL;
1467
1468                         if (ma == NULL)
1469                                 ma = &defmaterial;
1470
1471                         switch (ma->blend_method) {
1472                                 case MA_BM_SOLID:
1473                                 case MA_BM_CLIP:
1474                                 case MA_BM_HASHED:
1475                                         material_opaque(ma, material_hash, sldata, vedata, do_cull, use_flat_nor,
1476                                                 &gpumat_array[i], &gpumat_depth_array[i],
1477                                                 &shgrp_array[i], &shgrp_depth_array[i], &shgrp_depth_clip_array[i]);
1478                                         break;
1479                                 case MA_BM_ADD:
1480                                 case MA_BM_MULTIPLY:
1481                                 case MA_BM_BLEND:
1482                                         material_transparent(ma, sldata, vedata, do_cull, use_flat_nor,
1483                                                 &gpumat_array[i], &shgrp_array[i], &shgrp_depth_array[i]);
1484                                         break;
1485                                 default:
1486                                         BLI_assert(0);
1487                                         break;
1488                         }
1489                 }
1490
1491                 if (is_sculpt_mode && is_sculpt_mode_draw == false) {
1492                         DRW_cache_mesh_sculpt_coords_ensure(ob);
1493                 }
1494
1495                 /* Only support single volume material for now. */
1496                 /* XXX We rely on the previously compiled surface shader
1497                  * to know if the material has a "volume nodetree".
1498                  */
1499                 bool use_volume_material = (gpumat_array[0] && GPU_material_use_domain_volume(gpumat_array[0]));
1500
1501                 if (ob->dt >= OB_SOLID) {
1502                         /* Get per-material split surface */
1503                         char *auto_layer_names;
1504                         int *auto_layer_is_srgb;
1505                         int auto_layer_count;
1506                         struct GPUBatch **mat_geom = DRW_cache_object_surface_material_get(
1507                                 ob, gpumat_array, materials_len,
1508                                 &auto_layer_names,
1509                                 &auto_layer_is_srgb,
1510                                 &auto_layer_count);
1511                         if (mat_geom) {
1512                                 for (int i = 0; i < materials_len; ++i) {
1513                                         if (mat_geom[i] == NULL) {
1514                                                 continue;
1515                                         }
1516                                         EEVEE_ObjectEngineData *oedata = NULL;
1517                                         Material *ma = give_current_material(ob, i + 1);
1518
1519                                         if (ma == NULL)
1520                                                 ma = &defmaterial;
1521
1522                                         /* Do not render surface if we are rendering a volume object
1523                                          * and do not have a surface closure. */
1524                                         if (use_volume_material &&
1525                                             (gpumat_array[i] && !GPU_material_use_domain_surface(gpumat_array[i])))
1526                                         {
1527                                                 continue;
1528                                         }
1529
1530                                         /* XXX TODO rewrite this to include the dupli objects.
1531                                          * This means we cannot exclude dupli objects from reflections!!! */
1532                                         if ((ob->base_flag & BASE_FROMDUPLI) == 0) {
1533                                                 oedata = EEVEE_object_data_ensure(ob);
1534                                                 oedata->ob = ob;
1535                                                 oedata->test_data = &sldata->probes->vis_data;
1536                                         }
1537
1538                                         /* Shading pass */
1539                                         ADD_SHGROUP_CALL(shgrp_array[i], ob, ma, mat_geom[i], oedata);
1540
1541                                         /* Depth Prepass */
1542                                         ADD_SHGROUP_CALL_SAFE(shgrp_depth_array[i], ob, ma, mat_geom[i], oedata);
1543                                         ADD_SHGROUP_CALL_SAFE(shgrp_depth_clip_array[i], ob, ma, mat_geom[i], oedata);
1544
1545                                         char *name = auto_layer_names;
1546                                         for (int j = 0; j < auto_layer_count; ++j) {
1547                                                 /* TODO don't add these uniform when not needed (default pass shaders). */
1548                                                 if (shgrp_array[i]) {
1549                                                         DRW_shgroup_uniform_bool(shgrp_array[i], name, &auto_layer_is_srgb[j], 1);
1550                                                 }
1551                                                 if (shgrp_depth_array[i]) {
1552                                                         DRW_shgroup_uniform_bool(shgrp_depth_array[i], name, &auto_layer_is_srgb[j], 1);
1553                                                 }
1554                                                 if (shgrp_depth_clip_array[i]) {
1555                                                         DRW_shgroup_uniform_bool(shgrp_depth_clip_array[i], name, &auto_layer_is_srgb[j], 1);
1556                                                 }
1557                                                 /* Go to next layer name. */
1558                                                 while (*name != '\0') { name++; }
1559                                                 name += 1;
1560                                         }
1561
1562                                         /* Shadow Pass */
1563                                         if (ma->use_nodes && ma->nodetree && (ma->blend_method != MA_BM_SOLID)) {
1564                                                 struct GPUMaterial *gpumat;
1565                                                 switch (ma->blend_shadow) {
1566                                                         case MA_BS_SOLID:
1567                                                                 EEVEE_lights_cache_shcaster_add(
1568                                                                         sldata, stl, mat_geom[i], ob);
1569                                                                 *cast_shadow = true;
1570                                                                 break;
1571                                                         case MA_BS_CLIP:
1572                                                                 gpumat = EEVEE_material_mesh_depth_get(scene, ma, false, true);
1573                                                                 EEVEE_lights_cache_shcaster_material_add(
1574                                                                         sldata, psl, gpumat, mat_geom[i], ob, &ma->alpha_threshold);
1575                                                                 *cast_shadow = true;
1576                                                                 break;
1577                                                         case MA_BS_HASHED:
1578                                                                 gpumat = EEVEE_material_mesh_depth_get(scene, ma, true, true);
1579                                                                 EEVEE_lights_cache_shcaster_material_add(
1580                                                                         sldata, psl, gpumat, mat_geom[i], ob, NULL);
1581                                                                 *cast_shadow = true;
1582                                                                 break;
1583                                                         case MA_BS_NONE:
1584                                                         default:
1585                                                                 break;
1586                                                 }
1587                                         }
1588                                         else {
1589                                                 EEVEE_lights_cache_shcaster_add(sldata, stl, mat_geom[i], ob);
1590                                                 *cast_shadow = true;
1591                                         }
1592                                 }
1593                         }
1594                 }
1595
1596                 /* Volumetrics */
1597                 if (((stl->effects->enabled_effects & EFFECT_VOLUMETRIC) != 0) && use_volume_material) {
1598                         EEVEE_volumes_cache_object_add(sldata, vedata, scene, ob);
1599                 }
1600         }
1601 }
1602
1603 void EEVEE_hair_cache_populate(EEVEE_Data *vedata, EEVEE_ViewLayerData *sldata, Object *ob, bool *cast_shadow)
1604 {
1605         EEVEE_PassList *psl = vedata->psl;
1606         EEVEE_StorageList *stl = vedata->stl;
1607         const DRWContextState *draw_ctx = DRW_context_state_get();
1608         Scene *scene = draw_ctx->scene;
1609
1610         bool use_ssr = ((stl->effects->enabled_effects & EFFECT_SSR) != 0);
1611
1612         if (ob->type == OB_MESH) {
1613                 if (ob != draw_ctx->object_edit) {
1614                         for (ModifierData *md = ob->modifiers.first; md; md = md->next) {
1615                                 if (md->type != eModifierType_ParticleSystem) {
1616                                         continue;
1617                                 }
1618                                 ParticleSystem *psys = ((ParticleSystemModifierData *)md)->psys;
1619                                 if (!psys_check_enabled(ob, psys, false)) {
1620                                         continue;
1621                                 }
1622                                 if (!DRW_object_is_visible_psys_in_active_context(ob, psys)) {
1623                                         continue;
1624                                 }
1625                                 ParticleSettings *part = psys->part;
1626                                 const int draw_as = (part->draw_as == PART_DRAW_REND) ? part->ren_as : part->draw_as;
1627                                 if (draw_as != PART_DRAW_PATH) {
1628                                         continue;
1629                                 }
1630
1631                                 DRWShadingGroup *shgrp = NULL;
1632                                 Material *ma = give_current_material(ob, part->omat);
1633
1634                                 if (ma == NULL) {
1635                                         ma = &defmaterial;
1636                                 }
1637
1638                                 float *color_p = &ma->r;
1639                                 float *metal_p = &ma->metallic;
1640                                 float *spec_p = &ma->spec;
1641                                 float *rough_p = &ma->roughness;
1642
1643                                 shgrp = DRW_shgroup_hair_create(
1644                                         ob, psys, md,
1645                                         psl->depth_pass,
1646                                         e_data.default_hair_prepass_sh);
1647
1648                                 shgrp = DRW_shgroup_hair_create(
1649                                         ob, psys, md,
1650                                         psl->depth_pass_clip,
1651                                         e_data.default_hair_prepass_clip_sh);
1652                                 DRW_shgroup_uniform_block(shgrp, "clip_block", sldata->clip_ubo);
1653
1654                                 shgrp = NULL;
1655                                 if (ma->use_nodes && ma->nodetree) {
1656                                         static int ssr_id;
1657                                         ssr_id = (use_ssr) ? 1 : -1;
1658                                         static float half = 0.5f;
1659                                         static float error_col[3] = {1.0f, 0.0f, 1.0f};
1660                                         static float compile_col[3] = {0.5f, 0.5f, 0.5f};
1661                                         struct GPUMaterial *gpumat = EEVEE_material_hair_get(scene, ma, sldata->lamps->shadow_method);
1662
1663                                         switch (GPU_material_status(gpumat)) {
1664                                                 case GPU_MAT_SUCCESS:
1665                                                 {
1666                                                         bool use_diffuse = GPU_material_flag_get(gpumat, GPU_MATFLAG_DIFFUSE);
1667                                                         bool use_glossy = GPU_material_flag_get(gpumat, GPU_MATFLAG_GLOSSY);
1668                                                         bool use_refract = GPU_material_flag_get(gpumat, GPU_MATFLAG_REFRACT);
1669
1670                                                         shgrp = DRW_shgroup_material_hair_create(
1671                                                                 ob, psys, md,
1672                                                                 psl->material_pass,
1673                                                                 gpumat);
1674
1675                                                         add_standard_uniforms(shgrp, sldata, vedata, &ssr_id, NULL,
1676                                                                               use_diffuse, use_glossy, use_refract, false, false);
1677                                                         break;
1678                                                 }
1679                                                 case GPU_MAT_QUEUED:
1680                                                 {
1681                                                         color_p = compile_col;
1682                                                         metal_p = spec_p = rough_p = &half;
1683                                                         break;
1684                                                 }
1685                                                 case GPU_MAT_FAILED:
1686                                                 default:
1687                                                         color_p = error_col;
1688                                                         metal_p = spec_p = rough_p = &half;
1689                                                         break;
1690                                         }
1691                                 }
1692
1693                                 /* Fallback to default shader */
1694                                 if (shgrp == NULL) {
1695                                         shgrp = EEVEE_default_shading_group_get(sldata, vedata,
1696                                                                                 ob, psys, md,
1697                                                                                 true, false, use_ssr,
1698                                                                                 sldata->lamps->shadow_method);
1699                                         DRW_shgroup_uniform_vec3(shgrp, "basecol", color_p, 1);
1700                                         DRW_shgroup_uniform_float(shgrp, "metallic", metal_p, 1);
1701                                         DRW_shgroup_uniform_float(shgrp, "specular", spec_p, 1);
1702                                         DRW_shgroup_uniform_float(shgrp, "roughness", rough_p, 1);
1703                                 }
1704
1705                                 /* Shadows */
1706                                 DRW_shgroup_hair_create(
1707                                         ob, psys, md,
1708                                         psl->shadow_pass,
1709                                         e_data.default_hair_prepass_sh);
1710                                 *cast_shadow = true;
1711                         }
1712                 }
1713         }
1714 }
1715
1716 void EEVEE_materials_cache_finish(EEVEE_Data *vedata)
1717 {
1718         EEVEE_StorageList *stl = ((EEVEE_Data *)vedata)->stl;
1719
1720         /* Look-Dev */
1721         const DRWContextState *draw_ctx = DRW_context_state_get();
1722         const View3D *v3d = draw_ctx->v3d;
1723         if (LOOK_DEV_OVERLAY_ENABLED(v3d)) {
1724                 EEVEE_ViewLayerData *sldata = EEVEE_view_layer_data_ensure();
1725                 EEVEE_LampsInfo *linfo = sldata->lamps;
1726                 struct GPUBatch *sphere = DRW_cache_sphere_get();
1727                 static float mat1[4][4];
1728                 static float color[3] = {0.8f, 0.8f, 0.8f};
1729                 static float metallic_on = 1.0f;
1730                 static float metallic_off = 0.00f;
1731                 static float specular_off = 0.5f;
1732                 static float specular_on = 1.0f;
1733                 static float roughness_off = 0.05f;
1734                 static float roughness_on = 1.00f;
1735
1736                 float view_mat[4][4];
1737                 DRW_viewport_matrix_get(view_mat, DRW_MAT_VIEWINV);
1738
1739                 DRWShadingGroup *shgrp = EEVEE_lookdev_shading_group_get(sldata, vedata, false, linfo->shadow_method);
1740                 DRW_shgroup_uniform_vec3(shgrp, "basecol", color, 1);
1741                 DRW_shgroup_uniform_float(shgrp, "metallic", &metallic_on, 1);
1742                 DRW_shgroup_uniform_float(shgrp, "specular", &specular_on, 1);
1743                 DRW_shgroup_uniform_float(shgrp, "roughness", &roughness_off, 1);
1744                 unit_m4(mat1);
1745                 mul_m4_m4m4(mat1, mat1, view_mat);
1746                 translate_m4(mat1, -1.5f, 0.0f, -5.0f);
1747                 DRW_shgroup_call_add(shgrp, sphere, mat1);
1748
1749                 shgrp = EEVEE_lookdev_shading_group_get(sldata, vedata, false, linfo->shadow_method);
1750                 DRW_shgroup_uniform_vec3(shgrp, "basecol", color, 1);
1751                 DRW_shgroup_uniform_float(shgrp, "metallic", &metallic_off, 1);
1752                 DRW_shgroup_uniform_float(shgrp, "specular", &specular_off, 1);
1753                 DRW_shgroup_uniform_float(shgrp, "roughness", &roughness_on, 1);
1754                 translate_m4(mat1, 3.0f, 0.0f, 0.0f);
1755                 DRW_shgroup_call_add(shgrp, sphere, mat1);
1756         }
1757         /* END */
1758
1759         BLI_ghash_free(stl->g_data->material_hash, NULL, MEM_freeN);
1760 }
1761
1762 void EEVEE_materials_free(void)
1763 {
1764         for (int i = 0; i < VAR_MAT_MAX; ++i) {
1765                 DRW_SHADER_FREE_SAFE(e_data.default_lit[i]);
1766         }
1767         MEM_SAFE_FREE(e_data.frag_shader_lib);
1768         MEM_SAFE_FREE(e_data.vert_shader_str);
1769         MEM_SAFE_FREE(e_data.volume_shader_lib);
1770         DRW_SHADER_FREE_SAFE(e_data.default_hair_prepass_sh);
1771         DRW_SHADER_FREE_SAFE(e_data.default_hair_prepass_clip_sh);
1772         DRW_SHADER_FREE_SAFE(e_data.default_prepass_sh);
1773         DRW_SHADER_FREE_SAFE(e_data.default_prepass_clip_sh);
1774         DRW_SHADER_FREE_SAFE(e_data.default_background);
1775         DRW_SHADER_FREE_SAFE(e_data.default_studiolight_background);
1776         DRW_SHADER_FREE_SAFE(e_data.update_noise_sh);
1777         DRW_TEXTURE_FREE_SAFE(e_data.util_tex);
1778         DRW_TEXTURE_FREE_SAFE(e_data.noise_tex);
1779 }
1780
1781 void EEVEE_draw_default_passes(EEVEE_PassList *psl)
1782 {
1783         for (int i = 0; i < VAR_MAT_MAX; ++i) {
1784                 if (psl->default_pass[i]) {
1785                         DRW_draw_pass(psl->default_pass[i]);
1786                 }
1787         }
1788 }