Eevee: Fix Missing alpha when rendering with DOF
[blender.git] / source / blender / draw / engines / eevee / eevee_depth_of_field.c
1 /*
2  * Copyright 2016, Blender Foundation.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Blender Institute
19  *
20  */
21
22 /** \file eevee_depth_of_field.c
23  *  \ingroup draw_engine
24  *
25  * Depth of field post process effect.
26  */
27
28 #include "DRW_render.h"
29
30 #include "BLI_dynstr.h"
31 #include "BLI_rand.h"
32
33 #include "DNA_anim_types.h"
34 #include "DNA_camera_types.h"
35 #include "DNA_object_force_types.h"
36 #include "DNA_screen_types.h"
37 #include "DNA_view3d_types.h"
38 #include "DNA_world_types.h"
39
40 #include "BKE_global.h" /* for G.debug_value */
41 #include "BKE_camera.h"
42 #include "BKE_mesh.h"
43 #include "BKE_object.h"
44 #include "BKE_animsys.h"
45 #include "BKE_screen.h"
46
47 #include "DEG_depsgraph.h"
48 #include "DEG_depsgraph_query.h"
49
50 #include "eevee_private.h"
51 #include "GPU_extensions.h"
52 #include "GPU_framebuffer.h"
53 #include "GPU_texture.h"
54
55 #include "ED_screen.h"
56
57 static struct {
58         /* Depth Of Field */
59         struct GPUShader *dof_downsample_sh[2];
60         struct GPUShader *dof_scatter_sh[2];
61         struct GPUShader *dof_resolve_sh[2];
62 } e_data = {NULL}; /* Engine data */
63
64 extern char datatoc_effect_dof_vert_glsl[];
65 extern char datatoc_effect_dof_frag_glsl[];
66
67 static void eevee_create_shader_depth_of_field(const bool use_alpha)
68 {
69         e_data.dof_downsample_sh[use_alpha] = DRW_shader_create_fullscreen(
70                 datatoc_effect_dof_frag_glsl, use_alpha ?
71                                               "#define USE_ALPHA_DOF\n"
72                                               "#define STEP_DOWNSAMPLE\n" :
73                                               "#define STEP_DOWNSAMPLE\n");
74         e_data.dof_scatter_sh[use_alpha] = DRW_shader_create(
75                 datatoc_effect_dof_vert_glsl, NULL,
76                 datatoc_effect_dof_frag_glsl, use_alpha ?
77                                               "#define USE_ALPHA_DOF\n"
78                                               "#define STEP_SCATTER\n" :
79                                               "#define STEP_SCATTER\n");
80         e_data.dof_resolve_sh[use_alpha] = DRW_shader_create_fullscreen(
81                 datatoc_effect_dof_frag_glsl, use_alpha ?
82                                               "#define USE_ALPHA_DOF\n"
83                                               "#define STEP_RESOLVE\n" :
84                                               "#define STEP_RESOLVE\n");
85 }
86
87 int EEVEE_depth_of_field_init(EEVEE_ViewLayerData *UNUSED(sldata), EEVEE_Data *vedata, Object *camera)
88 {
89         EEVEE_StorageList *stl = vedata->stl;
90         EEVEE_FramebufferList *fbl = vedata->fbl;
91         EEVEE_EffectsInfo *effects = stl->effects;
92
93         const DRWContextState *draw_ctx = DRW_context_state_get();
94         const Scene *scene_eval = DEG_get_evaluated_scene(draw_ctx->depsgraph);
95
96         if (scene_eval->eevee.flag & SCE_EEVEE_DOF_ENABLED) {
97                 RegionView3D *rv3d = draw_ctx->rv3d;
98                 const bool use_alpha = !DRW_state_draw_background();
99
100                 if (!e_data.dof_downsample_sh[use_alpha]) {
101                         eevee_create_shader_depth_of_field(use_alpha);
102                 }
103
104                 if (camera) {
105                         const float *viewport_size = DRW_viewport_size_get();
106                         Camera *cam = (Camera *)camera->data;
107
108                         /* Retrieve Near and Far distance */
109                         effects->dof_near_far[0] = -cam->clipsta;
110                         effects->dof_near_far[1] = -cam->clipend;
111
112                         int buffer_size[2] = {(int)viewport_size[0] / 2, (int)viewport_size[1] / 2};
113
114                         GPUTextureFormat down_format = DRW_state_draw_background() ? GPU_R11F_G11F_B10F : GPU_RGBA16F;
115
116                         effects->dof_down_near = DRW_texture_pool_query_2D(buffer_size[0], buffer_size[1], down_format,
117                                                                            &draw_engine_eevee_type);
118                         effects->dof_down_far =  DRW_texture_pool_query_2D(buffer_size[0], buffer_size[1], down_format,
119                                                                            &draw_engine_eevee_type);
120                         effects->dof_coc =       DRW_texture_pool_query_2D(buffer_size[0], buffer_size[1], GPU_RG16F,
121                                                                            &draw_engine_eevee_type);
122
123                         GPU_framebuffer_ensure_config(&fbl->dof_down_fb, {
124                                 GPU_ATTACHMENT_NONE,
125                                 GPU_ATTACHMENT_TEXTURE(effects->dof_down_near),
126                                 GPU_ATTACHMENT_TEXTURE(effects->dof_down_far),
127                                 GPU_ATTACHMENT_TEXTURE(effects->dof_coc)
128                         });
129
130                         /* Go full 32bits for rendering and reduce the color artifacts. */
131                         GPUTextureFormat fb_format = DRW_state_is_image_render() ? GPU_RGBA32F : GPU_RGBA16F;
132
133                         effects->dof_blur = DRW_texture_pool_query_2D(buffer_size[0] * 2, buffer_size[1], fb_format,
134                                                                       &draw_engine_eevee_type);
135
136                         GPU_framebuffer_ensure_config(&fbl->dof_scatter_fb, {
137                                 GPU_ATTACHMENT_NONE,
138                                 GPU_ATTACHMENT_TEXTURE(effects->dof_blur),
139                         });
140
141                         if (!DRW_state_draw_background()) {
142                                 effects->dof_blur_alpha = DRW_texture_pool_query_2D(buffer_size[0] * 2, buffer_size[1], GPU_R32F,
143                                                                                     &draw_engine_eevee_type);
144                                 GPU_framebuffer_texture_attach(fbl->dof_scatter_fb, effects->dof_blur_alpha, 1, 0);
145                         }
146
147                         /* Parameters */
148                         /* TODO UI Options */
149                         float fstop = cam->gpu_dof.fstop;
150                         float blades = cam->gpu_dof.num_blades;
151                         float rotation = cam->gpu_dof.rotation;
152                         float ratio = 1.0f / cam->gpu_dof.ratio;
153                         float sensor = BKE_camera_sensor_size(cam->sensor_fit, cam->sensor_x, cam->sensor_y);
154                         float focus_dist = BKE_camera_object_dof_distance(camera);
155                         float focal_len = cam->lens;
156
157                         /* this is factor that converts to the scene scale. focal length and sensor are expressed in mm
158                          * unit.scale_length is how many meters per blender unit we have. We want to convert to blender units though
159                          * because the shader reads coordinates in world space, which is in blender units.
160                          * Note however that focus_distance is already in blender units and shall not be scaled here (see T48157). */
161                         float scale = (scene_eval->unit.system) ? scene_eval->unit.scale_length : 1.0f;
162                         float scale_camera = 0.001f / scale;
163                         /* we want radius here for the aperture number  */
164                         float aperture = 0.5f * scale_camera * focal_len / fstop;
165                         float focal_len_scaled = scale_camera * focal_len;
166                         float sensor_scaled = scale_camera * sensor;
167
168                         if (rv3d != NULL) {
169                                 sensor_scaled *= rv3d->viewcamtexcofac[0];
170                         }
171
172                         effects->dof_params[0] = aperture * fabsf(focal_len_scaled / (focus_dist - focal_len_scaled));
173                         effects->dof_params[1] = -focus_dist;
174                         effects->dof_params[2] = viewport_size[0] / sensor_scaled;
175                         effects->dof_bokeh[0] = rotation;
176                         effects->dof_bokeh[1] = ratio;
177                         effects->dof_bokeh[2] = scene_eval->eevee.bokeh_max_size;
178
179                         /* Precompute values to save instructions in fragment shader. */
180                         effects->dof_bokeh_sides[0] = blades;
181                         effects->dof_bokeh_sides[1] = 2.0f * M_PI / blades;
182                         effects->dof_bokeh_sides[2] = blades / (2.0f * M_PI);
183                         effects->dof_bokeh_sides[3] = cosf(M_PI / blades);
184
185                         return EFFECT_DOF | EFFECT_POST_BUFFER;
186                 }
187         }
188
189         /* Cleanup to release memory */
190         GPU_FRAMEBUFFER_FREE_SAFE(fbl->dof_down_fb);
191         GPU_FRAMEBUFFER_FREE_SAFE(fbl->dof_scatter_fb);
192
193         return 0;
194 }
195
196 void EEVEE_depth_of_field_cache_init(EEVEE_ViewLayerData *UNUSED(sldata), EEVEE_Data *vedata)
197 {
198         EEVEE_PassList *psl = vedata->psl;
199         EEVEE_StorageList *stl = vedata->stl;
200         EEVEE_EffectsInfo *effects = stl->effects;
201         DefaultTextureList *dtxl = DRW_viewport_texture_list_get();
202
203         if ((effects->enabled_effects & EFFECT_DOF) != 0) {
204                 /**  Depth of Field algorithm
205                  *
206                  * Overview :
207                  * - Downsample the color buffer into 2 buffers weighted with
208                  *   CoC values. Also output CoC into a texture.
209                  * - Shoot quads for every pixel and expand it depending on the CoC.
210                  *   Do one pass for near Dof and one pass for far Dof.
211                  * - Finally composite the 2 blurred buffers with the original render.
212                  **/
213                 DRWShadingGroup *grp;
214                 struct GPUBatch *quad = DRW_cache_fullscreen_quad_get();
215                 const bool use_alpha = !DRW_state_draw_background();
216
217                 psl->dof_down = DRW_pass_create("DoF Downsample", DRW_STATE_WRITE_COLOR);
218
219                 grp = DRW_shgroup_create(e_data.dof_downsample_sh[use_alpha], psl->dof_down);
220                 DRW_shgroup_uniform_texture_ref(grp, "colorBuffer", &effects->source_buffer);
221                 DRW_shgroup_uniform_texture_ref(grp, "depthBuffer", &dtxl->depth);
222                 DRW_shgroup_uniform_vec2(grp, "nearFar", effects->dof_near_far, 1);
223                 DRW_shgroup_uniform_vec3(grp, "dofParams", effects->dof_params, 1);
224                 DRW_shgroup_call_add(grp, quad, NULL);
225
226                 psl->dof_scatter = DRW_pass_create("DoF Scatter", DRW_STATE_WRITE_COLOR | DRW_STATE_ADDITIVE_FULL);
227
228                 /* This create an empty batch of N triangles to be positioned
229                  * by the vertex shader 0.4ms against 6ms with instancing */
230                 const float *viewport_size = DRW_viewport_size_get();
231                 const int sprite_len = ((int)viewport_size[0] / 2) * ((int)viewport_size[1] / 2); /* brackets matters */
232                 grp = DRW_shgroup_empty_tri_batch_create(e_data.dof_scatter_sh[use_alpha], psl->dof_scatter, sprite_len);
233                 DRW_shgroup_uniform_texture_ref(grp, "nearBuffer", &effects->dof_down_near);
234                 DRW_shgroup_uniform_texture_ref(grp, "farBuffer", &effects->dof_down_far);
235                 DRW_shgroup_uniform_texture_ref(grp, "cocBuffer", &effects->dof_coc);
236                 DRW_shgroup_uniform_vec4(grp, "bokehParams", effects->dof_bokeh, 2);
237
238                 psl->dof_resolve = DRW_pass_create("DoF Resolve", DRW_STATE_WRITE_COLOR);
239
240                 grp = DRW_shgroup_create(e_data.dof_resolve_sh[use_alpha], psl->dof_resolve);
241                 DRW_shgroup_uniform_texture_ref(grp, "scatterBuffer", &effects->dof_blur);
242                 DRW_shgroup_uniform_texture_ref(grp, "colorBuffer", &effects->source_buffer);
243                 DRW_shgroup_uniform_texture_ref(grp, "depthBuffer", &dtxl->depth);
244                 DRW_shgroup_uniform_vec2(grp, "nearFar", effects->dof_near_far, 1);
245                 DRW_shgroup_uniform_vec3(grp, "dofParams", effects->dof_params, 1);
246                 DRW_shgroup_call_add(grp, quad, NULL);
247
248                 if (use_alpha) {
249                         DRW_shgroup_uniform_texture_ref(grp, "scatterAlphaBuffer", &effects->dof_blur_alpha);
250                 }
251         }
252 }
253
254 void EEVEE_depth_of_field_draw(EEVEE_Data *vedata)
255 {
256         EEVEE_PassList *psl = vedata->psl;
257         EEVEE_TextureList *txl = vedata->txl;
258         EEVEE_FramebufferList *fbl = vedata->fbl;
259         EEVEE_StorageList *stl = vedata->stl;
260         EEVEE_EffectsInfo *effects = stl->effects;
261
262         /* Depth Of Field */
263         if ((effects->enabled_effects & EFFECT_DOF) != 0) {
264                 float clear_col[4] = {0.0f, 0.0f, 0.0f, 0.0f};
265
266                 /* Downsample */
267                 GPU_framebuffer_bind(fbl->dof_down_fb);
268                 DRW_draw_pass(psl->dof_down);
269
270                 /* Scatter */
271                 GPU_framebuffer_bind(fbl->dof_scatter_fb);
272                 GPU_framebuffer_clear_color(fbl->dof_scatter_fb, clear_col);
273                 DRW_draw_pass(psl->dof_scatter);
274
275                 /* Resolve */
276                 GPU_framebuffer_bind(effects->target_buffer);
277                 DRW_draw_pass(psl->dof_resolve);
278                 SWAP_BUFFERS();
279         }
280 }
281
282 void EEVEE_depth_of_field_free(void)
283 {
284         for (int i = 0; i < 2; ++i) {
285                 DRW_SHADER_FREE_SAFE(e_data.dof_downsample_sh[i]);
286                 DRW_SHADER_FREE_SAFE(e_data.dof_scatter_sh[i]);
287                 DRW_SHADER_FREE_SAFE(e_data.dof_resolve_sh[i]);
288         }
289 }