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