Merge branch 'blender-v2.81-release'
[blender.git] / source / blender / draw / engines / eevee / eevee_screen_raytrace.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  * Screen space reflections and refractions techniques.
23  */
24
25 #include "DRW_render.h"
26
27 #include "BLI_dynstr.h"
28 #include "BLI_string_utils.h"
29
30 #include "DEG_depsgraph_query.h"
31
32 #include "eevee_private.h"
33 #include "GPU_texture.h"
34
35 /* SSR shader variations */
36 enum {
37   SSR_RESOLVE = (1 << 0),
38   SSR_FULL_TRACE = (1 << 1),
39   SSR_AO = (1 << 3),
40   SSR_MAX_SHADER = (1 << 4),
41 };
42
43 static struct {
44   /* Screen Space Reflection */
45   struct GPUShader *ssr_sh[SSR_MAX_SHADER];
46
47   /* These are just references, not actually allocated */
48   struct GPUTexture *depth_src;
49 } e_data = {{NULL}}; /* Engine data */
50
51 extern char datatoc_ambient_occlusion_lib_glsl[];
52 extern char datatoc_common_view_lib_glsl[];
53 extern char datatoc_common_uniforms_lib_glsl[];
54 extern char datatoc_bsdf_common_lib_glsl[];
55 extern char datatoc_bsdf_sampling_lib_glsl[];
56 extern char datatoc_octahedron_lib_glsl[];
57 extern char datatoc_effect_ssr_frag_glsl[];
58 extern char datatoc_lightprobe_lib_glsl[];
59 extern char datatoc_raytrace_lib_glsl[];
60
61 static struct GPUShader *eevee_effects_screen_raytrace_shader_get(int options)
62 {
63   if (e_data.ssr_sh[options] == NULL) {
64     char *ssr_shader_str = BLI_string_joinN(datatoc_common_view_lib_glsl,
65                                             datatoc_common_uniforms_lib_glsl,
66                                             datatoc_bsdf_common_lib_glsl,
67                                             datatoc_bsdf_sampling_lib_glsl,
68                                             datatoc_ambient_occlusion_lib_glsl,
69                                             datatoc_octahedron_lib_glsl,
70                                             datatoc_lightprobe_lib_glsl,
71                                             datatoc_raytrace_lib_glsl,
72                                             datatoc_effect_ssr_frag_glsl);
73
74     DynStr *ds_defines = BLI_dynstr_new();
75     BLI_dynstr_append(ds_defines, SHADER_DEFINES);
76     if (options & SSR_RESOLVE) {
77       BLI_dynstr_append(ds_defines, "#define STEP_RESOLVE\n");
78     }
79     else {
80       BLI_dynstr_append(ds_defines, "#define STEP_RAYTRACE\n");
81       BLI_dynstr_append(ds_defines, "#define PLANAR_PROBE_RAYTRACE\n");
82     }
83     if (options & SSR_FULL_TRACE) {
84       BLI_dynstr_append(ds_defines, "#define FULLRES\n");
85     }
86     if (options & SSR_AO) {
87       BLI_dynstr_append(ds_defines, "#define SSR_AO\n");
88     }
89     char *ssr_define_str = BLI_dynstr_get_cstring(ds_defines);
90     BLI_dynstr_free(ds_defines);
91
92     e_data.ssr_sh[options] = DRW_shader_create_fullscreen(ssr_shader_str, ssr_define_str);
93
94     MEM_freeN(ssr_shader_str);
95     MEM_freeN(ssr_define_str);
96   }
97
98   return e_data.ssr_sh[options];
99 }
100
101 int EEVEE_screen_raytrace_init(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
102 {
103   EEVEE_CommonUniformBuffer *common_data = &sldata->common_data;
104   EEVEE_StorageList *stl = vedata->stl;
105   EEVEE_FramebufferList *fbl = vedata->fbl;
106   EEVEE_TextureList *txl = vedata->txl;
107   EEVEE_EffectsInfo *effects = stl->effects;
108   const float *viewport_size = DRW_viewport_size_get();
109
110   const DRWContextState *draw_ctx = DRW_context_state_get();
111   const Scene *scene_eval = DEG_get_evaluated_scene(draw_ctx->depsgraph);
112
113   /* Compute pixel size, (shared with contact shadows) */
114   copy_v2_v2(common_data->ssr_pixelsize, viewport_size);
115   invert_v2(common_data->ssr_pixelsize);
116
117   if (scene_eval->eevee.flag & SCE_EEVEE_SSR_ENABLED) {
118     const bool use_refraction = (scene_eval->eevee.flag & SCE_EEVEE_SSR_REFRACTION) != 0;
119
120     if (use_refraction) {
121       /* TODO: Opti: Could be shared. */
122       DRW_texture_ensure_fullscreen_2d(
123           &txl->refract_color, GPU_R11F_G11F_B10F, DRW_TEX_FILTER | DRW_TEX_MIPMAP);
124
125       GPU_framebuffer_ensure_config(
126           &fbl->refract_fb, {GPU_ATTACHMENT_NONE, GPU_ATTACHMENT_TEXTURE(txl->refract_color)});
127     }
128
129     const bool is_persp = DRW_view_is_persp_get(NULL);
130     if (effects->ssr_was_persp != is_persp) {
131       effects->ssr_was_persp = is_persp;
132       DRW_viewport_request_redraw();
133       EEVEE_temporal_sampling_reset(vedata);
134       stl->g_data->valid_double_buffer = false;
135     }
136
137     if (!effects->ssr_was_valid_double_buffer) {
138       DRW_viewport_request_redraw();
139       EEVEE_temporal_sampling_reset(vedata);
140     }
141     effects->ssr_was_valid_double_buffer = stl->g_data->valid_double_buffer;
142
143     effects->reflection_trace_full = (scene_eval->eevee.flag & SCE_EEVEE_SSR_HALF_RESOLUTION) == 0;
144     common_data->ssr_thickness = scene_eval->eevee.ssr_thickness;
145     common_data->ssr_border_fac = scene_eval->eevee.ssr_border_fade;
146     common_data->ssr_firefly_fac = scene_eval->eevee.ssr_firefly_fac;
147     common_data->ssr_max_roughness = scene_eval->eevee.ssr_max_roughness;
148     common_data->ssr_quality = 1.0f - 0.95f * scene_eval->eevee.ssr_quality;
149     common_data->ssr_brdf_bias = 0.1f + common_data->ssr_quality * 0.6f; /* Range [0.1, 0.7]. */
150
151     if (common_data->ssr_firefly_fac < 1e-8f) {
152       common_data->ssr_firefly_fac = FLT_MAX;
153     }
154
155     const int divisor = (effects->reflection_trace_full) ? 1 : 2;
156     int tracing_res[2] = {(int)viewport_size[0] / divisor, (int)viewport_size[1] / divisor};
157     int size_fs[2] = {(int)viewport_size[0], (int)viewport_size[1]};
158     const bool high_qual_input = true; /* TODO dither low quality input */
159     const eGPUTextureFormat format = (high_qual_input) ? GPU_RGBA16F : GPU_RGBA8;
160
161     tracing_res[0] = max_ii(1, tracing_res[0]);
162     tracing_res[1] = max_ii(1, tracing_res[1]);
163
164     /* MRT for the shading pass in order to output needed data for the SSR pass. */
165     effects->ssr_specrough_input = DRW_texture_pool_query_2d(
166         size_fs[0], size_fs[1], format, &draw_engine_eevee_type);
167
168     GPU_framebuffer_texture_attach(fbl->main_fb, effects->ssr_specrough_input, 2, 0);
169
170     /* Raytracing output */
171     effects->ssr_hit_output = DRW_texture_pool_query_2d(
172         tracing_res[0], tracing_res[1], GPU_RG16I, &draw_engine_eevee_type);
173     effects->ssr_pdf_output = DRW_texture_pool_query_2d(
174         tracing_res[0], tracing_res[1], GPU_R16F, &draw_engine_eevee_type);
175
176     GPU_framebuffer_ensure_config(&fbl->screen_tracing_fb,
177                                   {GPU_ATTACHMENT_NONE,
178                                    GPU_ATTACHMENT_TEXTURE(effects->ssr_hit_output),
179                                    GPU_ATTACHMENT_TEXTURE(effects->ssr_pdf_output)});
180
181     /* Enable double buffering to be able to read previous frame color */
182     return EFFECT_SSR | EFFECT_NORMAL_BUFFER | EFFECT_DOUBLE_BUFFER |
183            ((use_refraction) ? EFFECT_REFRACT : 0);
184   }
185
186   /* Cleanup to release memory */
187   GPU_FRAMEBUFFER_FREE_SAFE(fbl->screen_tracing_fb);
188   effects->ssr_specrough_input = NULL;
189   effects->ssr_hit_output = NULL;
190   effects->ssr_pdf_output = NULL;
191
192   return 0;
193 }
194
195 void EEVEE_screen_raytrace_cache_init(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
196 {
197   EEVEE_PassList *psl = vedata->psl;
198   EEVEE_StorageList *stl = vedata->stl;
199   EEVEE_TextureList *txl = vedata->txl;
200   EEVEE_EffectsInfo *effects = stl->effects;
201   LightCache *lcache = stl->g_data->light_cache;
202
203   struct GPUBatch *quad = DRW_cache_fullscreen_quad_get();
204
205   if ((effects->enabled_effects & EFFECT_SSR) != 0) {
206     int options = (effects->reflection_trace_full) ? SSR_FULL_TRACE : 0;
207     options |= ((effects->enabled_effects & EFFECT_GTAO) != 0) ? SSR_AO : 0;
208
209     struct GPUShader *trace_shader = eevee_effects_screen_raytrace_shader_get(options);
210     struct GPUShader *resolve_shader = eevee_effects_screen_raytrace_shader_get(SSR_RESOLVE |
211                                                                                 options);
212
213     /** Screen space raytracing overview
214      *
215      * Following Frostbite stochastic SSR.
216      *
217      * - First pass Trace rays across the depth buffer. The hit position and pdf are
218      *   recorded in a RGBA16F render target for each ray (sample).
219      *
220      * - We down-sample the previous frame color buffer.
221      *
222      * - For each final pixel, we gather neighbors rays and choose a color buffer
223      *   mipmap for each ray using its pdf. (filtered importance sampling)
224      *   We then evaluate the lighting from the probes and mix the results together.
225      */
226     DRW_PASS_CREATE(psl->ssr_raytrace, DRW_STATE_WRITE_COLOR);
227     DRWShadingGroup *grp = DRW_shgroup_create(trace_shader, psl->ssr_raytrace);
228     DRW_shgroup_uniform_texture_ref(grp, "depthBuffer", &e_data.depth_src);
229     DRW_shgroup_uniform_texture_ref(grp, "normalBuffer", &effects->ssr_normal_input);
230     DRW_shgroup_uniform_texture_ref(grp, "specroughBuffer", &effects->ssr_specrough_input);
231     DRW_shgroup_uniform_texture_ref(grp, "maxzBuffer", &txl->maxzbuffer);
232     DRW_shgroup_uniform_texture_ref(grp, "planarDepth", &vedata->txl->planar_depth);
233     DRW_shgroup_uniform_texture(grp, "utilTex", EEVEE_materials_get_util_tex());
234     DRW_shgroup_uniform_block(grp, "grid_block", sldata->grid_ubo);
235     DRW_shgroup_uniform_block(grp, "probe_block", sldata->probe_ubo);
236     DRW_shgroup_uniform_block(grp, "planar_block", sldata->planar_ubo);
237     DRW_shgroup_uniform_block(grp, "common_block", sldata->common_ubo);
238     if (!effects->reflection_trace_full) {
239       DRW_shgroup_uniform_ivec2(grp, "halfresOffset", effects->ssr_halfres_ofs, 1);
240     }
241     DRW_shgroup_call(grp, quad, NULL);
242
243     DRW_PASS_CREATE(psl->ssr_resolve, DRW_STATE_WRITE_COLOR | DRW_STATE_BLEND_ADD);
244     grp = DRW_shgroup_create(resolve_shader, psl->ssr_resolve);
245     DRW_shgroup_uniform_texture_ref(grp, "depthBuffer", &e_data.depth_src);
246     DRW_shgroup_uniform_texture_ref(grp, "normalBuffer", &effects->ssr_normal_input);
247     DRW_shgroup_uniform_texture_ref(grp, "specroughBuffer", &effects->ssr_specrough_input);
248     DRW_shgroup_uniform_texture_ref(grp, "probeCubes", &lcache->cube_tx.tex);
249     DRW_shgroup_uniform_texture_ref(grp, "probePlanars", &vedata->txl->planar_pool);
250     DRW_shgroup_uniform_texture_ref(grp, "planarDepth", &vedata->txl->planar_depth);
251     DRW_shgroup_uniform_texture_ref(grp, "hitBuffer", &effects->ssr_hit_output);
252     DRW_shgroup_uniform_texture_ref(grp, "pdfBuffer", &effects->ssr_pdf_output);
253     DRW_shgroup_uniform_texture_ref(grp, "prevColorBuffer", &txl->color_double_buffer);
254     DRW_shgroup_uniform_block(grp, "grid_block", sldata->grid_ubo);
255     DRW_shgroup_uniform_block(grp, "probe_block", sldata->probe_ubo);
256     DRW_shgroup_uniform_block(grp, "planar_block", sldata->planar_ubo);
257     DRW_shgroup_uniform_block(grp, "common_block", sldata->common_ubo);
258     DRW_shgroup_uniform_int(grp, "neighborOffset", &effects->ssr_neighbor_ofs, 1);
259     if ((effects->enabled_effects & EFFECT_GTAO) != 0) {
260       DRW_shgroup_uniform_texture(grp, "utilTex", EEVEE_materials_get_util_tex());
261       DRW_shgroup_uniform_texture_ref(grp, "horizonBuffer", &effects->gtao_horizons);
262     }
263
264     DRW_shgroup_call(grp, quad, NULL);
265   }
266 }
267
268 void EEVEE_refraction_compute(EEVEE_ViewLayerData *UNUSED(sldata), EEVEE_Data *vedata)
269 {
270   EEVEE_FramebufferList *fbl = vedata->fbl;
271   EEVEE_TextureList *txl = vedata->txl;
272   EEVEE_StorageList *stl = vedata->stl;
273   EEVEE_EffectsInfo *effects = stl->effects;
274
275   if ((effects->enabled_effects & EFFECT_REFRACT) != 0) {
276     GPU_framebuffer_blit(fbl->main_fb, 0, fbl->refract_fb, 0, GPU_COLOR_BIT);
277     EEVEE_downsample_buffer(vedata, txl->refract_color, 9);
278
279     /* Restore */
280     GPU_framebuffer_bind(fbl->main_fb);
281   }
282 }
283
284 void EEVEE_reflection_compute(EEVEE_ViewLayerData *UNUSED(sldata), EEVEE_Data *vedata)
285 {
286   EEVEE_PassList *psl = vedata->psl;
287   EEVEE_FramebufferList *fbl = vedata->fbl;
288   EEVEE_StorageList *stl = vedata->stl;
289   EEVEE_TextureList *txl = vedata->txl;
290   EEVEE_EffectsInfo *effects = stl->effects;
291
292   if (((effects->enabled_effects & EFFECT_SSR) != 0) && stl->g_data->valid_double_buffer) {
293     DefaultTextureList *dtxl = DRW_viewport_texture_list_get();
294     e_data.depth_src = dtxl->depth;
295
296     DRW_stats_group_start("SSR");
297
298     /* Raytrace. */
299     GPU_framebuffer_bind(fbl->screen_tracing_fb);
300     DRW_draw_pass(psl->ssr_raytrace);
301
302     EEVEE_downsample_buffer(vedata, txl->color_double_buffer, 9);
303
304     /* Resolve at fullres */
305     int sample = (DRW_state_is_image_render()) ? effects->taa_render_sample :
306                                                  effects->taa_current_sample;
307     /* Doing a neighbor shift only after a few iteration.
308      * We wait for a prime number of cycles to avoid noise correlation.
309      * This reduces variance faster. */
310     effects->ssr_neighbor_ofs = ((sample / 5) % 8) * 4;
311     switch ((sample / 11) % 4) {
312       case 0:
313         effects->ssr_halfres_ofs[0] = 0;
314         effects->ssr_halfres_ofs[1] = 0;
315         break;
316       case 1:
317         effects->ssr_halfres_ofs[0] = 0;
318         effects->ssr_halfres_ofs[1] = 1;
319         break;
320       case 2:
321         effects->ssr_halfres_ofs[0] = 1;
322         effects->ssr_halfres_ofs[1] = 0;
323         break;
324       case 4:
325         effects->ssr_halfres_ofs[0] = 1;
326         effects->ssr_halfres_ofs[1] = 1;
327         break;
328     }
329     GPU_framebuffer_bind(fbl->main_color_fb);
330     DRW_draw_pass(psl->ssr_resolve);
331
332     /* Restore */
333     GPU_framebuffer_bind(fbl->main_fb);
334     DRW_stats_group_end();
335   }
336 }
337
338 void EEVEE_screen_raytrace_free(void)
339 {
340   for (int i = 0; i < SSR_MAX_SHADER; i++) {
341     DRW_SHADER_FREE_SAFE(e_data.ssr_sh[i]);
342   }
343 }