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