GP: Create Framebuffer textures only if needed
[blender.git] / source / blender / draw / engines / gpencil / gpencil_engine.c
1 /*
2  * Copyright 2017, 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): Antonio Vazquez
19  *
20  */
21
22 /** \file blender/draw/engines/gpencil/gpencil_engine.c
23  *  \ingroup draw
24  */
25 #include "DRW_engine.h"
26 #include "DRW_render.h"
27
28 #include "BKE_camera.h"
29 #include "BKE_object.h"
30 #include "BKE_paint.h"
31 #include "BKE_gpencil.h"
32 #include "BKE_shader_fx.h"
33
34 #include "DNA_gpencil_types.h"
35 #include "DNA_view3d_types.h"
36
37 #include "draw_mode_engines.h"
38
39 #include "UI_resources.h"
40
41 #include "GPU_texture.h"
42
43 #include "gpencil_engine.h"
44
45 #include "DEG_depsgraph_query.h"
46
47 #include "ED_screen.h"
48 #include "ED_gpencil.h"
49
50 #include "WM_api.h"
51
52 extern char datatoc_gpencil_fill_vert_glsl[];
53 extern char datatoc_gpencil_fill_frag_glsl[];
54 extern char datatoc_gpencil_stroke_vert_glsl[];
55 extern char datatoc_gpencil_stroke_geom_glsl[];
56 extern char datatoc_gpencil_stroke_frag_glsl[];
57 extern char datatoc_gpencil_zdepth_mix_frag_glsl[];
58 extern char datatoc_gpencil_simple_mix_frag_glsl[];
59 extern char datatoc_gpencil_point_vert_glsl[];
60 extern char datatoc_gpencil_point_geom_glsl[];
61 extern char datatoc_gpencil_point_frag_glsl[];
62 extern char datatoc_gpencil_background_frag_glsl[];
63 extern char datatoc_gpencil_paper_frag_glsl[];
64 extern char datatoc_gpencil_edit_point_vert_glsl[];
65 extern char datatoc_gpencil_edit_point_geom_glsl[];
66 extern char datatoc_gpencil_edit_point_frag_glsl[];
67 extern char datatoc_gpencil_blend_frag_glsl[];
68
69 /* *********** STATIC *********** */
70 static GPENCIL_e_data e_data = {NULL}; /* Engine data */
71
72 /* *********** FUNCTIONS *********** */
73
74 /* create a multisample buffer if not present */
75 void DRW_gpencil_multisample_ensure(GPENCIL_Data *vedata, int rect_w, int rect_h)
76 {
77         GPENCIL_FramebufferList *fbl = vedata->fbl;
78         GPENCIL_StorageList *stl = ((GPENCIL_Data *)vedata)->stl;
79         GPENCIL_TextureList *txl = ((GPENCIL_Data *)vedata)->txl;
80
81         short samples = stl->storage->multisamples;
82
83         if (samples > 0) {
84                 if (!fbl->multisample_fb) {
85                         fbl->multisample_fb = GPU_framebuffer_create();
86                         if (fbl->multisample_fb) {
87                                 if (txl->multisample_color == NULL) {
88                                         txl->multisample_color = GPU_texture_create_2D_multisample(
89                                                 rect_w, rect_h, GPU_RGBA16F, NULL, samples, NULL);
90                                 }
91                                 if (txl->multisample_depth == NULL) {
92                                         txl->multisample_depth = GPU_texture_create_2D_multisample(
93                                                 rect_w, rect_h, GPU_DEPTH_COMPONENT24, NULL, samples, NULL);
94                                 }
95                                 GPU_framebuffer_ensure_config(
96                                         &fbl->multisample_fb, {
97                                             GPU_ATTACHMENT_TEXTURE(txl->multisample_depth),
98                                             GPU_ATTACHMENT_TEXTURE(txl->multisample_color)
99                                         });
100                         }
101                 }
102         }
103 }
104
105 static void GPENCIL_create_framebuffers(void *vedata)
106 {
107         GPENCIL_FramebufferList *fbl = ((GPENCIL_Data *)vedata)->fbl;
108         GPENCIL_StorageList *stl = ((GPENCIL_Data *)vedata)->stl;
109
110         /* Go full 32bits for rendering */
111         GPUTextureFormat fb_format = DRW_state_is_image_render() ? GPU_RGBA32F : GPU_RGBA16F;
112
113         if (DRW_state_is_fbo()) {
114                 const float *viewport_size = DRW_viewport_size_get();
115                 const int size[2] = { (int)viewport_size[0], (int)viewport_size[1] };
116
117                 /* create multiframe framebuffer for AA */
118                 if ((stl->storage->framebuffer_flag & GP_FRAMEBUFFER_MULTISAMPLE) &&
119                         (stl->storage->multisamples > 0))
120                 {
121                         DRW_gpencil_multisample_ensure(vedata, size[0], size[1]);
122                 }
123
124                 /* Framebufers for basic object drawing */
125                 if (stl->storage->framebuffer_flag & GP_FRAMEBUFFER_BASIC) {
126                         /* temp textures for ping-pong buffers */
127                         e_data.temp_depth_tx_a = DRW_texture_pool_query_2D(
128                                 size[0], size[1], GPU_DEPTH_COMPONENT24,
129                                 &draw_engine_gpencil_type);
130                         e_data.temp_color_tx_a = DRW_texture_pool_query_2D(size[0], size[1], fb_format,
131                                 &draw_engine_gpencil_type);
132                         GPU_framebuffer_ensure_config(
133                                 &fbl->temp_fb_a, {
134                                         GPU_ATTACHMENT_TEXTURE(e_data.temp_depth_tx_a),
135                                         GPU_ATTACHMENT_TEXTURE(e_data.temp_color_tx_a)
136                                 });
137
138                         e_data.temp_depth_tx_b = DRW_texture_pool_query_2D(
139                                 size[0], size[1], GPU_DEPTH_COMPONENT24,
140                                 &draw_engine_gpencil_type);
141                         e_data.temp_color_tx_b = DRW_texture_pool_query_2D(
142                                 size[0], size[1], fb_format,
143                                 &draw_engine_gpencil_type);
144                         GPU_framebuffer_ensure_config(
145                                 &fbl->temp_fb_b, {
146                                         GPU_ATTACHMENT_TEXTURE(e_data.temp_depth_tx_b),
147                                         GPU_ATTACHMENT_TEXTURE(e_data.temp_color_tx_b)
148                                 });
149
150                         /* used for FX effects and Layer blending */
151                         e_data.temp_depth_tx_fx = DRW_texture_pool_query_2D(
152                                 size[0], size[1], GPU_DEPTH_COMPONENT24,
153                                 &draw_engine_gpencil_type);
154                         e_data.temp_color_tx_fx = DRW_texture_pool_query_2D(
155                                 size[0], size[1], fb_format,
156                                 &draw_engine_gpencil_type);
157                         GPU_framebuffer_ensure_config(
158                                 &fbl->temp_fb_fx, {
159                                         GPU_ATTACHMENT_TEXTURE(e_data.temp_depth_tx_fx),
160                                         GPU_ATTACHMENT_TEXTURE(e_data.temp_color_tx_fx),
161                                 });
162                 }
163
164                 /* background framebuffer to speed up drawing process (always 16 bits) */
165                 if (stl->storage->framebuffer_flag & GP_FRAMEBUFFER_DRAW) {
166                         e_data.background_depth_tx = DRW_texture_pool_query_2D(
167                                 size[0], size[1], GPU_DEPTH_COMPONENT24,
168                                 &draw_engine_gpencil_type);
169                         e_data.background_color_tx = DRW_texture_pool_query_2D(
170                                 size[0], size[1], GPU_RGBA32F,
171                                 &draw_engine_gpencil_type);
172                         GPU_framebuffer_ensure_config(
173                                 &fbl->background_fb, {
174                                         GPU_ATTACHMENT_TEXTURE(e_data.background_depth_tx),
175                                         GPU_ATTACHMENT_TEXTURE(e_data.background_color_tx)
176                                 });
177                 }
178         }
179 }
180
181 static void GPENCIL_create_shaders(void)
182 {
183         /* normal fill shader */
184         if (!e_data.gpencil_fill_sh) {
185                 e_data.gpencil_fill_sh = DRW_shader_create(
186                         datatoc_gpencil_fill_vert_glsl, NULL,
187                         datatoc_gpencil_fill_frag_glsl, NULL);
188         }
189
190         /* normal stroke shader using geometry to display lines (line mode) */
191         if (!e_data.gpencil_stroke_sh) {
192                 e_data.gpencil_stroke_sh = DRW_shader_create(
193                         datatoc_gpencil_stroke_vert_glsl,
194                         datatoc_gpencil_stroke_geom_glsl,
195                         datatoc_gpencil_stroke_frag_glsl,
196                         NULL);
197         }
198
199         /* dot/rectangle mode for normal strokes using geometry */
200         if (!e_data.gpencil_point_sh) {
201                 e_data.gpencil_point_sh = DRW_shader_create(
202                         datatoc_gpencil_point_vert_glsl,
203                         datatoc_gpencil_point_geom_glsl,
204                         datatoc_gpencil_point_frag_glsl,
205                         NULL);
206         }
207         /* used for edit points or strokes with one point only */
208         if (!e_data.gpencil_edit_point_sh) {
209                 e_data.gpencil_edit_point_sh = DRW_shader_create(
210                         datatoc_gpencil_edit_point_vert_glsl,
211                         datatoc_gpencil_edit_point_geom_glsl,
212                         datatoc_gpencil_edit_point_frag_glsl, NULL);
213         }
214
215         /* used for edit lines for edit modes */
216         if (!e_data.gpencil_line_sh) {
217                 e_data.gpencil_line_sh = GPU_shader_get_builtin_shader(GPU_SHADER_3D_FLAT_COLOR);
218         }
219
220         /* used to filling during drawing */
221         if (!e_data.gpencil_drawing_fill_sh) {
222                 e_data.gpencil_drawing_fill_sh = GPU_shader_get_builtin_shader(GPU_SHADER_3D_SMOOTH_COLOR);
223         }
224
225         /* full screen for mix zdepth*/
226         if (!e_data.gpencil_fullscreen_sh) {
227                 e_data.gpencil_fullscreen_sh = DRW_shader_create_fullscreen(datatoc_gpencil_zdepth_mix_frag_glsl, NULL);
228         }
229         if (!e_data.gpencil_simple_fullscreen_sh) {
230                 e_data.gpencil_simple_fullscreen_sh = DRW_shader_create_fullscreen(datatoc_gpencil_simple_mix_frag_glsl, NULL);
231         }
232
233         /* blend */
234         if (!e_data.gpencil_blend_fullscreen_sh) {
235                 e_data.gpencil_blend_fullscreen_sh = DRW_shader_create_fullscreen(datatoc_gpencil_blend_frag_glsl, NULL);
236         }
237
238         /* shaders for use when drawing */
239         if (!e_data.gpencil_background_sh) {
240                 e_data.gpencil_background_sh = DRW_shader_create_fullscreen(datatoc_gpencil_background_frag_glsl, NULL);
241         }
242         if (!e_data.gpencil_paper_sh) {
243                 e_data.gpencil_paper_sh = DRW_shader_create_fullscreen(datatoc_gpencil_paper_frag_glsl, NULL);
244         }
245 }
246
247 void GPENCIL_engine_init(void *vedata)
248 {
249         GPENCIL_StorageList *stl = ((GPENCIL_Data *)vedata)->stl;
250         /* init storage */
251         if (!stl->storage) {
252                 stl->storage = MEM_callocN(sizeof(GPENCIL_Storage), "GPENCIL_Storage");
253
254                 /* unit matrix */
255                 unit_m4(stl->storage->unit_matrix);
256         }
257
258         stl->storage->multisamples = U.gpencil_multisamples;
259
260         /* create shaders */
261         GPENCIL_create_shaders();
262         GPENCIL_create_fx_shaders(&e_data);
263
264         /* blank texture used if no texture defined for fill shader */
265         if (!e_data.gpencil_blank_texture) {
266                 float rect[16][16][4] = {{{0.0f}}};
267                 e_data.gpencil_blank_texture = DRW_texture_create_2D(16, 16, GPU_RGBA8, DRW_TEX_FILTER, (float *)rect);
268         }
269 }
270
271 static void GPENCIL_engine_free(void)
272 {
273         /* only free custom shaders, builtin shaders are freed in blender close */
274         DRW_SHADER_FREE_SAFE(e_data.gpencil_fill_sh);
275         DRW_SHADER_FREE_SAFE(e_data.gpencil_stroke_sh);
276         DRW_SHADER_FREE_SAFE(e_data.gpencil_point_sh);
277         DRW_SHADER_FREE_SAFE(e_data.gpencil_edit_point_sh);
278         DRW_SHADER_FREE_SAFE(e_data.gpencil_fullscreen_sh);
279         DRW_SHADER_FREE_SAFE(e_data.gpencil_simple_fullscreen_sh);
280         DRW_SHADER_FREE_SAFE(e_data.gpencil_blend_fullscreen_sh);
281         DRW_SHADER_FREE_SAFE(e_data.gpencil_background_sh);
282         DRW_SHADER_FREE_SAFE(e_data.gpencil_paper_sh);
283
284         DRW_TEXTURE_FREE_SAFE(e_data.gpencil_blank_texture);
285
286         GPU_BATCH_DISCARD_SAFE(e_data.batch_buffer_stroke);
287         MEM_SAFE_FREE(e_data.batch_buffer_stroke);
288
289         GPU_BATCH_DISCARD_SAFE(e_data.batch_buffer_fill);
290         MEM_SAFE_FREE(e_data.batch_buffer_fill);
291
292         GPU_BATCH_DISCARD_SAFE(e_data.batch_grid);
293         MEM_SAFE_FREE(e_data.batch_grid);
294
295         /* effects */
296         GPENCIL_delete_fx_shaders(&e_data);
297 }
298
299 void GPENCIL_cache_init(void *vedata)
300 {
301         GPENCIL_PassList *psl = ((GPENCIL_Data *)vedata)->psl;
302         GPENCIL_StorageList *stl = ((GPENCIL_Data *)vedata)->stl;
303         const DRWContextState *draw_ctx = DRW_context_state_get();
304         Scene *scene = draw_ctx->scene;
305         View3D *v3d = draw_ctx->v3d;
306
307         /* Special handling for when active object is GP object (e.g. for draw mode) */
308         Object *obact = draw_ctx->obact;
309         bGPdata *obact_gpd = NULL;
310         MaterialGPencilStyle *gp_style = NULL;
311
312         if (obact && (obact->type == OB_GPENCIL) && (obact->data)) {
313                 obact_gpd = (bGPdata *)obact->data;
314                 gp_style = BKE_material_gpencil_settings_get(obact, obact->actcol);
315         }
316
317         if (!stl->g_data) {
318                 /* Alloc transient pointers */
319                 stl->g_data = MEM_mallocN(sizeof(g_data), "g_data");
320                 stl->storage->xray = GP_XRAY_FRONT; /* used for drawing */
321                 stl->storage->stroke_style = GP_STYLE_STROKE_STYLE_SOLID; /* used for drawing */
322         }
323         stl->storage->tonemapping = 0;
324
325         stl->g_data->shgrps_edit_line = NULL;
326         stl->g_data->shgrps_edit_point = NULL;
327
328         if (!stl->shgroups) {
329                 /* Alloc maximum size because count strokes is very slow and can be very complex due onion skinning.
330                  */
331                 stl->shgroups = MEM_mallocN(sizeof(GPENCIL_shgroup) * GPENCIL_MAX_SHGROUPS, "GPENCIL_shgroup");
332         }
333
334         /* init gp objects cache */
335         stl->g_data->gp_cache_used = 0;
336         stl->g_data->gp_cache_size = 0;
337         stl->g_data->gp_object_cache = NULL;
338
339         {
340                 /* Stroke pass */
341                 psl->stroke_pass = DRW_pass_create(
342                         "GPencil Stroke Pass",
343                         DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_ALWAYS | DRW_STATE_BLEND);
344                 stl->storage->shgroup_id = 0;
345
346                 /* edit pass */
347                 psl->edit_pass = DRW_pass_create(
348                         "GPencil Edit Pass",
349                         DRW_STATE_WRITE_COLOR | DRW_STATE_BLEND);
350
351                 /* detect if playing animation */
352                 if (draw_ctx->evil_C) {
353
354                         bool playing = ED_screen_animation_playing(CTX_wm_manager(draw_ctx->evil_C)) != NULL;
355                         if (playing != stl->storage->is_playing) {
356                                 stl->storage->reset_cache = true;
357                         }
358                         stl->storage->is_playing = playing;
359                 }
360                 else {
361                         stl->storage->is_playing = false;
362                         stl->storage->reset_cache = false;
363                 }
364                 /* save render state */
365                 stl->storage->is_render = DRW_state_is_image_render();
366                 stl->storage->is_mat_preview = (bool)stl->storage->is_render && STREQ(scene->id.name + 2, "preview");
367
368                 if (obact_gpd) {
369                         /* for some reason, when press play there is a delay in the animation flag check
370                          * and this produces errors. To be sure, we set cache as dirty because the frame
371                          * is changing.
372                          */
373                         if (stl->storage->is_playing == true) {
374                                 obact_gpd->flag |= GP_DATA_CACHE_IS_DIRTY;
375                         }
376                         /* if render, set as dirty to update all data */
377                         else if (stl->storage->is_render == true) {
378                                 obact_gpd->flag |= GP_DATA_CACHE_IS_DIRTY;
379                         }
380                 }
381
382                 /* save simplify flags (can change while drawing, so it's better to save) */
383                 stl->storage->simplify_fill = GP_SIMPLIFY_FILL(scene, stl->storage->is_playing);
384                 stl->storage->simplify_modif = GP_SIMPLIFY_MODIF(scene, stl->storage->is_playing);
385                 stl->storage->simplify_fx = GP_SIMPLIFY_FX(scene, stl->storage->is_playing);
386                 stl->storage->simplify_blend = GP_SIMPLIFY_BLEND(scene, stl->storage->is_playing);
387
388                 /* save pixsize */
389                 stl->storage->pixsize = DRW_viewport_pixelsize_get();
390                 if ((!DRW_state_is_opengl_render()) && (stl->storage->is_render)) {
391                         stl->storage->pixsize = &stl->storage->render_pixsize;
392                 }
393
394                 /* detect if painting session */
395                 if ((obact_gpd) &&
396                     (obact_gpd->flag & GP_DATA_STROKE_PAINTMODE) &&
397                     (stl->storage->is_playing == false))
398                 {
399                         /* need the original to avoid cow overhead while drawing */
400                         bGPdata *gpd_orig = (bGPdata *)DEG_get_original_id(&obact_gpd->id);
401                         if (((gpd_orig->runtime.sbuffer_sflag & GP_STROKE_ERASER) == 0) &&
402                             (gpd_orig->runtime.sbuffer_size > 0) &&
403                             ((gpd_orig->flag & GP_DATA_STROKE_POLYGON) == 0))
404                         {
405                                 stl->g_data->session_flag |= GP_DRW_PAINT_PAINTING;
406                         }
407                         else {
408                                 stl->g_data->session_flag = GP_DRW_PAINT_IDLE;
409                         }
410                 }
411                 else {
412                         /* if not drawing mode */
413                         stl->g_data->session_flag = GP_DRW_PAINT_HOLD;
414                 }
415
416                 if (gp_style) {
417                         stl->storage->stroke_style = gp_style->stroke_style;
418                         stl->storage->color_type = GPENCIL_COLOR_SOLID;
419                         if (gp_style->stroke_style == GP_STYLE_STROKE_STYLE_TEXTURE) {
420                                 stl->storage->color_type = GPENCIL_COLOR_TEXTURE;
421                                 if (gp_style->flag & GP_STYLE_STROKE_PATTERN) {
422                                         stl->storage->color_type = GPENCIL_COLOR_PATTERN;
423                                 }
424                         }
425                 }
426                 else {
427                         stl->storage->stroke_style = GP_STYLE_STROKE_STYLE_SOLID;
428                         stl->storage->color_type = GPENCIL_COLOR_SOLID;
429                 }
430
431                 /* drawing buffer pass for drawing the stroke that is being drawing by the user. The data
432                  * is stored in sbuffer
433                  */
434                 psl->drawing_pass = DRW_pass_create(
435                         "GPencil Drawing Pass",
436                         DRW_STATE_WRITE_COLOR | DRW_STATE_BLEND | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_ALWAYS);
437
438                 /* full screen pass to combine the result with default framebuffer */
439                 struct GPUBatch *quad = DRW_cache_fullscreen_quad_get();
440                 psl->mix_pass = DRW_pass_create(
441                         "GPencil Mix Pass",
442                         DRW_STATE_WRITE_COLOR | DRW_STATE_BLEND | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS);
443                 DRWShadingGroup *mix_shgrp = DRW_shgroup_create(e_data.gpencil_fullscreen_sh, psl->mix_pass);
444                 DRW_shgroup_call_add(mix_shgrp, quad, NULL);
445                 DRW_shgroup_uniform_texture_ref(mix_shgrp, "strokeColor", &e_data.input_color_tx);
446                 DRW_shgroup_uniform_texture_ref(mix_shgrp, "strokeDepth", &e_data.input_depth_tx);
447                 DRW_shgroup_uniform_int(mix_shgrp, "tonemapping", &stl->storage->tonemapping, 1);
448
449                 /* mix pass no blend used to copy between passes. A separated pass is required
450                  * because if mix_pass is used, the acumulation of blend degrade the colors.
451                  *
452                  * This pass is used too to take the snapshot used for background_pass. This image
453                  * will be used as the background while the user is drawing.
454                  */
455                 psl->mix_pass_noblend = DRW_pass_create(
456                         "GPencil Mix Pass no blend",
457                         DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS);
458                 DRWShadingGroup *mix_shgrp_noblend = DRW_shgroup_create(e_data.gpencil_fullscreen_sh, psl->mix_pass_noblend);
459                 DRW_shgroup_call_add(mix_shgrp_noblend, quad, NULL);
460                 DRW_shgroup_uniform_texture_ref(mix_shgrp_noblend, "strokeColor", &e_data.input_color_tx);
461                 DRW_shgroup_uniform_texture_ref(mix_shgrp_noblend, "strokeDepth", &e_data.input_depth_tx);
462                 DRW_shgroup_uniform_int(mix_shgrp_noblend, "tonemapping", &stl->storage->tonemapping, 1);
463
464                 /* Painting session pass (used only to speedup while the user is drawing )
465                  * This pass is used to show the snapshot of the current grease pencil strokes captured
466                  * when the user starts to draw (see comments above).
467                  * In this way, the previous strokes don't need to be redraw and the drawing process
468                  * is far to agile.
469                  */
470                 psl->background_pass = DRW_pass_create(
471                         "GPencil Background Painting Session Pass",
472                         DRW_STATE_WRITE_COLOR | DRW_STATE_BLEND | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS);
473                 DRWShadingGroup *background_shgrp = DRW_shgroup_create(e_data.gpencil_background_sh, psl->background_pass);
474                 DRW_shgroup_call_add(background_shgrp, quad, NULL);
475                 DRW_shgroup_uniform_texture_ref(background_shgrp, "strokeColor", &e_data.background_color_tx);
476                 DRW_shgroup_uniform_texture_ref(background_shgrp, "strokeDepth", &e_data.background_depth_tx);
477
478                 /* pass for drawing paper (only if viewport)
479                  * In render, the v3d is null so the paper is disabled
480                  * The paper is way to isolate the drawing in complex scene and to have a cleaner
481                  * drawing area.
482                  */
483                 if (v3d) {
484                         psl->paper_pass = DRW_pass_create(
485                                 "GPencil Paper Pass",
486                                 DRW_STATE_WRITE_COLOR | DRW_STATE_BLEND);
487                         DRWShadingGroup *paper_shgrp = DRW_shgroup_create(e_data.gpencil_paper_sh, psl->paper_pass);
488                         DRW_shgroup_call_add(paper_shgrp, quad, NULL);
489                         DRW_shgroup_uniform_vec3(paper_shgrp, "color", v3d->shading.background_color, 1);
490                         DRW_shgroup_uniform_float(paper_shgrp, "opacity", &v3d->overlay.gpencil_paper_opacity, 1);
491                 }
492
493                 /* grid pass */
494                 if (v3d) {
495                         psl->grid_pass = DRW_pass_create(
496                                 "GPencil Grid Pass",
497                                 DRW_STATE_WRITE_COLOR | DRW_STATE_BLEND | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_ALWAYS);
498                         stl->g_data->shgrps_grid = DRW_shgroup_create(e_data.gpencil_line_sh, psl->grid_pass);
499                 }
500
501                 /* blend layers pass */
502                 psl->blend_pass = DRW_pass_create(
503                         "GPencil Blend Layers Pass",
504                         DRW_STATE_WRITE_COLOR | DRW_STATE_BLEND | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS);
505                 DRWShadingGroup *blend_shgrp = DRW_shgroup_create(e_data.gpencil_blend_fullscreen_sh, psl->blend_pass);
506                 DRW_shgroup_call_add(blend_shgrp, quad, NULL);
507                 DRW_shgroup_uniform_texture_ref(blend_shgrp, "strokeColor", &e_data.temp_color_tx_a);
508                 DRW_shgroup_uniform_texture_ref(blend_shgrp, "strokeDepth", &e_data.temp_depth_tx_a);
509                 DRW_shgroup_uniform_texture_ref(blend_shgrp, "blendColor", &e_data.temp_color_tx_fx);
510                 DRW_shgroup_uniform_texture_ref(blend_shgrp, "blendDepth", &e_data.temp_depth_tx_fx);
511                 DRW_shgroup_uniform_int(blend_shgrp, "mode", &stl->storage->blend_mode, 1);
512                 DRW_shgroup_uniform_int(blend_shgrp, "clamp_layer", &stl->storage->clamp_layer, 1);
513                 DRW_shgroup_uniform_float(blend_shgrp, "blend_opacity", &stl->storage->blend_opacity, 1);
514                 DRW_shgroup_uniform_int(mix_shgrp, "tonemapping", &stl->storage->tonemapping, 1);
515
516                 /* create effects passes */
517                 if (!stl->storage->simplify_fx) {
518                         GPENCIL_create_fx_passes(psl);
519                 }
520         }
521 }
522
523 static void gpencil_add_draw_data(void *vedata, Object *ob)
524 {
525         GPENCIL_StorageList *stl = ((GPENCIL_Data *)vedata)->stl;
526         bGPdata *gpd = (bGPdata *)ob->data;
527         const bool is_multiedit = (bool)GPENCIL_MULTIEDIT_SESSIONS_ON(gpd);
528
529         int i = stl->g_data->gp_cache_used - 1;
530         tGPencilObjectCache *cache_ob = &stl->g_data->gp_object_cache[i];
531
532         if (!cache_ob->is_dup_ob) {
533                 /* fill shading groups */
534                 if (!is_multiedit) {
535                         DRW_gpencil_populate_datablock(&e_data, vedata, ob, cache_ob);
536                 }
537                 else {
538                         DRW_gpencil_populate_multiedit(&e_data, vedata, ob, cache_ob);
539                 }
540         }
541
542         /* FX passses */
543         cache_ob->has_fx = false;
544         if ((!stl->storage->simplify_fx) &&
545             (BKE_shaderfx_has_gpencil(ob)))
546         {
547                 cache_ob->has_fx = true;
548                 if ((!stl->storage->simplify_fx) && (!is_multiedit)) {
549                         DRW_gpencil_fx_prepare(&e_data, vedata, cache_ob);
550                 }
551         }
552
553 }
554
555 void GPENCIL_cache_populate(void *vedata, Object *ob)
556 {
557         /* object must be visible */
558         if (!DRW_object_is_visible_in_active_context(ob)) {
559                 return;
560         }
561
562         GPENCIL_StorageList *stl = ((GPENCIL_Data *)vedata)->stl;
563         const DRWContextState *draw_ctx = DRW_context_state_get();
564         Scene *scene = draw_ctx->scene;
565         ToolSettings *ts = scene->toolsettings;
566         View3D *v3d = draw_ctx->v3d;
567
568         if (ob->type == OB_GPENCIL && ob->data) {
569                 bGPdata *gpd = (bGPdata *)ob->data;
570
571                 /* enable multisample and basic framebuffer creation */
572                 stl->storage->framebuffer_flag |= GP_FRAMEBUFFER_MULTISAMPLE;
573                 stl->storage->framebuffer_flag |= GP_FRAMEBUFFER_BASIC;
574
575                 /* when start/stop animation the cache must be set as dirty to reset all data */
576                 if (stl->storage->reset_cache) {
577                         gpd->flag |= GP_DATA_CACHE_IS_DIRTY;
578                         stl->storage->reset_cache = false;
579                 }
580
581                 if ((stl->g_data->session_flag & GP_DRW_PAINT_READY) == 0) {
582
583                         /* save gp objects for drawing later */
584                         stl->g_data->gp_object_cache = gpencil_object_cache_add(
585                                 stl->g_data->gp_object_cache, ob,
586                                 &stl->g_data->gp_cache_size, &stl->g_data->gp_cache_used);
587
588                         /* load drawing data */
589                         gpencil_add_draw_data(vedata, ob);
590                 }
591
592                 /* draw current painting strokes
593                 * (only if region is equal to originated paint region)
594                 */
595                 if ((draw_ctx->obact == ob) &&
596                     ((gpd->runtime.ar == NULL) || (gpd->runtime.ar == draw_ctx->ar)))
597                 {
598                         DRW_gpencil_populate_buffer_strokes(&e_data, vedata, ts, ob);
599                 }
600
601                 /* grid */
602                 if ((v3d) &&
603                     ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) &&
604                     (v3d->gp_flag & V3D_GP_SHOW_GRID) &&
605                     (ob->type == OB_GPENCIL) && (ob == draw_ctx->obact))
606                 {
607                         GPU_BATCH_DISCARD_SAFE(e_data.batch_grid);
608                         MEM_SAFE_FREE(e_data.batch_grid);
609
610                         e_data.batch_grid = DRW_gpencil_get_grid(ob);
611
612                         /* define grid orientation */
613                         if (ts->gp_sculpt.lock_axis != GP_LOCKAXIS_VIEW) {
614                                 copy_m4_m4(stl->storage->grid_matrix, ob->obmat);
615                         }
616                         else {
617                                 /* align always to view */
618                                 invert_m4_m4(stl->storage->grid_matrix, draw_ctx->rv3d->viewmat);
619                                 /* copy ob location */
620                                 copy_v3_v3(stl->storage->grid_matrix[3], ob->obmat[3]);
621                         }
622
623                         DRW_shgroup_call_add(
624                                 stl->g_data->shgrps_grid,
625                                 e_data.batch_grid,
626                                 stl->storage->grid_matrix);
627                 }
628         }
629 }
630
631 void GPENCIL_cache_finish(void *vedata)
632 {
633         GPENCIL_StorageList *stl = ((GPENCIL_Data *)vedata)->stl;
634
635         /* draw particles */
636         DRW_gpencil_populate_particles(&e_data, vedata);
637
638         if (stl->g_data->session_flag & (GP_DRW_PAINT_IDLE | GP_DRW_PAINT_FILLING)) {
639                 stl->storage->framebuffer_flag |= GP_FRAMEBUFFER_DRAW;
640         }
641
642         /* create framebuffers */
643         GPENCIL_create_framebuffers(vedata);
644
645 }
646
647 /* helper function to sort inverse gpencil objects using qsort */
648 static int gpencil_object_cache_compare_zdepth(const void *a1, const void *a2)
649 {
650         const tGPencilObjectCache *ps1 = a1, *ps2 = a2;
651
652         if (ps1->zdepth < ps2->zdepth) return 1;
653         else if (ps1->zdepth > ps2->zdepth) return -1;
654
655         return 0;
656 }
657
658 /* prepare a texture with full viewport screenshot for fast drawing */
659 static void gpencil_prepare_fast_drawing(
660         GPENCIL_StorageList *stl, DefaultFramebufferList *dfbl,
661         GPENCIL_FramebufferList *fbl, DRWPass *pass,
662         const float clearcol[4])
663 {
664         if (stl->g_data->session_flag & (GP_DRW_PAINT_IDLE | GP_DRW_PAINT_FILLING)) {
665                 GPU_framebuffer_bind(fbl->background_fb);
666                 /* clean only in first loop cycle */
667                 if (stl->g_data->session_flag & GP_DRW_PAINT_IDLE) {
668                         GPU_framebuffer_clear_color_depth(fbl->background_fb, clearcol, 1.0f);
669                         stl->g_data->session_flag = GP_DRW_PAINT_FILLING;
670                 }
671                 /* repeat pass to fill temp texture */
672                 DRW_draw_pass(pass);
673                 /* set default framebuffer again */
674                 GPU_framebuffer_bind(dfbl->default_fb);
675         }
676 }
677
678 static void gpencil_free_obj_runtime(GPENCIL_StorageList *stl)
679 {
680         /* reset all cache flags */
681         for (int i = 0; i < stl->g_data->gp_cache_used; i++) {
682                 tGPencilObjectCache *cache_ob = &stl->g_data->gp_object_cache[i];
683                 bGPdata *gpd = cache_ob->gpd;
684                 gpd->flag &= ~GP_DATA_CACHE_IS_DIRTY;
685
686                 /* free shgrp array */
687                 cache_ob->tot_layers = 0;
688                 MEM_SAFE_FREE(cache_ob->shgrp_array);
689         }
690
691         /* free the cache itself */
692         MEM_SAFE_FREE(stl->g_data->gp_object_cache);
693 }
694
695 static void gpencil_draw_pass_range(
696         GPENCIL_FramebufferList *fbl, GPENCIL_StorageList *stl,
697         GPENCIL_PassList *psl, GPENCIL_TextureList *txl,
698         GPUFrameBuffer *fb,
699         DRWShadingGroup *init_shgrp, DRWShadingGroup *end_shgrp, bool multi)
700 {
701         if (init_shgrp == NULL) {
702                 return;
703         }
704
705         /* previews don't use AA */
706         if ((!stl->storage->is_mat_preview) && (multi)) {
707                 MULTISAMPLE_GP_SYNC_ENABLE(stl->storage->multisamples, fbl);
708         }
709
710         DRW_draw_pass_subset(
711                 psl->stroke_pass, init_shgrp, end_shgrp);
712
713         if ((!stl->storage->is_mat_preview) && (multi)) {
714                 MULTISAMPLE_GP_SYNC_DISABLE(stl->storage->multisamples, fbl, fb, txl);
715         }
716
717 }
718
719 /* draw scene */
720 void GPENCIL_draw_scene(void *ved)
721 {
722         GPENCIL_Data *vedata = (GPENCIL_Data *)ved;
723         GPENCIL_StorageList *stl = ((GPENCIL_Data *)vedata)->stl;
724
725         GPENCIL_PassList *psl = ((GPENCIL_Data *)vedata)->psl;
726         GPENCIL_FramebufferList *fbl = ((GPENCIL_Data *)vedata)->fbl;
727         DefaultFramebufferList *dfbl = DRW_viewport_framebuffer_list_get();
728         GPENCIL_TextureList *txl = ((GPENCIL_Data *)vedata)->txl;
729
730         tGPencilObjectCache *cache_ob;
731         tGPencilObjectCache_shgrp *array_elm = NULL;
732         DRWShadingGroup *init_shgrp = NULL;
733         DRWShadingGroup *end_shgrp = NULL;
734
735         const float clearcol[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
736
737         const DRWContextState *draw_ctx = DRW_context_state_get();
738         View3D *v3d = draw_ctx->v3d;
739         Object *obact = draw_ctx->obact;
740         const bool playing = stl->storage->is_playing;
741         const bool is_render = stl->storage->is_render;
742         bGPdata *gpd_act = (obact) && (obact->type == OB_GPENCIL) ? (bGPdata *)obact->data : NULL;
743         const bool is_edit = GPENCIL_ANY_EDIT_MODE(gpd_act);
744
745         /* paper pass to display a comfortable area to draw over complex scenes with geometry */
746         if ((!is_render) && (obact) && (obact->type == OB_GPENCIL)) {
747                 if (((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) &&
748                     (v3d->gp_flag & V3D_GP_SHOW_PAPER))
749                 {
750                         DRW_draw_pass(psl->paper_pass);
751                 }
752         }
753
754         /* if we have a painting session, we use fast viewport drawing method */
755         if ((!is_render) && (stl->g_data->session_flag & GP_DRW_PAINT_PAINTING)) {
756                 GPU_framebuffer_bind(dfbl->default_fb);
757
758                 MULTISAMPLE_GP_SYNC_ENABLE(stl->storage->multisamples, fbl);
759
760                 DRW_draw_pass(psl->background_pass);
761                 DRW_draw_pass(psl->drawing_pass);
762
763                 MULTISAMPLE_GP_SYNC_DISABLE(stl->storage->multisamples, fbl, dfbl->default_fb, txl);
764
765                 /* free memory */
766                 gpencil_free_obj_runtime(stl);
767
768                 /* grid pass */
769                 if ((!is_render) && (obact) && (obact->type == OB_GPENCIL)) {
770                         if (((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) &&
771                             (v3d->gp_flag & V3D_GP_SHOW_GRID))
772                         {
773                                 DRW_draw_pass(psl->grid_pass);
774                         }
775                 }
776
777                 return;
778         }
779
780         if (DRW_state_is_fbo()) {
781
782                 /* Draw all pending objects */
783                 if (stl->g_data->gp_cache_used > 0) {
784
785                         /* sort by zdepth */
786                         qsort(stl->g_data->gp_object_cache, stl->g_data->gp_cache_used,
787                               sizeof(tGPencilObjectCache), gpencil_object_cache_compare_zdepth);
788
789                         for (int i = 0; i < stl->g_data->gp_cache_used; i++) {
790                                 cache_ob = &stl->g_data->gp_object_cache[i];
791                                 bGPdata *gpd = cache_ob->gpd;
792                                 init_shgrp = NULL;
793                                 /* Render stroke in separated framebuffer */
794                                 GPU_framebuffer_bind(fbl->temp_fb_a);
795                                 GPU_framebuffer_clear_color_depth(fbl->temp_fb_a, clearcol, 1.0f);
796
797                                 /* Stroke Pass:
798                                  * draw only a subset that usually starts with a fill and ends with stroke
799                                  */
800                                 bool use_blend = false;
801                                 if (cache_ob->tot_layers > 0) {
802                                         for (int e = 0; e < cache_ob->tot_layers; e++) {
803                                                 bool is_last = e == cache_ob->tot_layers - 1 ? true : false;
804                                                 array_elm = &cache_ob->shgrp_array[e];
805
806                                                 if (((array_elm->mode == eGplBlendMode_Normal) &&
807                                                      (!use_blend) && (!array_elm->clamp_layer)) ||
808                                                     (e == 0))
809                                                 {
810                                                         if (init_shgrp == NULL) {
811                                                                 init_shgrp = array_elm->init_shgrp;
812                                                         }
813                                                         end_shgrp = array_elm->end_shgrp;
814                                                 }
815                                                 else {
816                                                         use_blend = true;
817                                                         /* draw pending groups */
818                                                         gpencil_draw_pass_range(
819                                                                 fbl, stl, psl, txl, fbl->temp_fb_a,
820                                                                 init_shgrp, end_shgrp, is_last);
821
822                                                         /* draw current group in separated texture */
823                                                         init_shgrp = array_elm->init_shgrp;
824                                                         end_shgrp = array_elm->end_shgrp;
825
826                                                         GPU_framebuffer_bind(fbl->temp_fb_fx);
827                                                         GPU_framebuffer_clear_color_depth(fbl->temp_fb_fx, clearcol, 1.0f);
828                                                         gpencil_draw_pass_range(
829                                                                 fbl, stl, psl, txl, fbl->temp_fb_fx,
830                                                                 init_shgrp, end_shgrp,
831                                                                 is_last);
832
833                                                         /* Blend A texture and FX texture */
834                                                         GPU_framebuffer_bind(fbl->temp_fb_b);
835                                                         GPU_framebuffer_clear_color_depth(fbl->temp_fb_b, clearcol, 1.0f);
836                                                         stl->storage->blend_mode = array_elm->mode;
837                                                         stl->storage->clamp_layer = (int)array_elm->clamp_layer;
838                                                         stl->storage->blend_opacity = array_elm->blend_opacity;
839                                                         stl->storage->tonemapping = stl->storage->is_render ? 1 : 0;
840                                                         DRW_draw_pass(psl->blend_pass);
841                                                         stl->storage->tonemapping = 0;
842
843                                                         /* Copy B texture to A texture to follow loop */
844                                                         e_data.input_depth_tx = e_data.temp_depth_tx_b;
845                                                         e_data.input_color_tx = e_data.temp_color_tx_b;
846
847                                                         GPU_framebuffer_bind(fbl->temp_fb_a);
848                                                         GPU_framebuffer_clear_color_depth(fbl->temp_fb_a, clearcol, 1.0f);
849                                                         DRW_draw_pass(psl->mix_pass_noblend);
850
851                                                         /* prepare next group */
852                                                         init_shgrp = NULL;
853                                                 }
854
855                                         }
856                                         /* last group */
857                                         gpencil_draw_pass_range(
858                                                 fbl, stl, psl, txl, fbl->temp_fb_a,
859                                                 init_shgrp, end_shgrp,
860                                                 true);
861                                 }
862
863                                 /* Current buffer drawing */
864                                 if ((!is_render) && (cache_ob->is_dup_ob == false)) {
865                                         DRW_draw_pass(psl->drawing_pass);
866                                 }
867                                 /* fx passes */
868                                 if (cache_ob->has_fx == true) {
869                                         stl->storage->tonemapping = 0;
870                                         DRW_gpencil_fx_draw(&e_data, vedata, cache_ob);
871                                 }
872
873                                 e_data.input_depth_tx = e_data.temp_depth_tx_a;
874                                 e_data.input_color_tx = e_data.temp_color_tx_a;
875
876                                 /* Combine with scene buffer */
877                                 if ((!is_render) || (fbl->main == NULL)) {
878                                         GPU_framebuffer_bind(dfbl->default_fb);
879                                 }
880                                 else {
881                                         GPU_framebuffer_bind(fbl->main);
882                                 }
883                                 /* tonemapping */
884                                 stl->storage->tonemapping = stl->storage->is_render ? 1 : 0;
885
886                                 DRW_draw_pass(psl->mix_pass);
887
888                                 /* prepare for fast drawing */
889                                 if (!is_render) {
890                                         if (!playing) {
891                                                 gpencil_prepare_fast_drawing(stl, dfbl, fbl, psl->mix_pass_noblend, clearcol);
892                                         }
893                                 }
894                                 else {
895                                         /* if render, the cache must be dirty for next loop */
896                                         gpd->flag |= GP_DATA_CACHE_IS_DIRTY;
897                                 }
898                         }
899                         /* edit points */
900                         if ((!is_render) && (!playing) && (is_edit)) {
901                                 DRW_draw_pass(psl->edit_pass);
902                         }
903                 }
904                 /* grid pass */
905                 if ((!is_render) && (obact) && (obact->type == OB_GPENCIL)) {
906                         if (((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) &&
907                             (v3d->gp_flag & V3D_GP_SHOW_GRID))
908                         {
909                                 DRW_draw_pass(psl->grid_pass);
910                         }
911                 }
912         }
913         /* free memory */
914         gpencil_free_obj_runtime(stl);
915
916         /* reset  */
917         if (DRW_state_is_fbo()) {
918                 /* attach again default framebuffer */
919                 if (!is_render) {
920                         GPU_framebuffer_bind(dfbl->default_fb);
921                 }
922
923                 /* the temp texture is ready. Now we can use fast screen drawing */
924                 if (stl->g_data->session_flag & GP_DRW_PAINT_FILLING) {
925                         stl->g_data->session_flag = GP_DRW_PAINT_READY;
926                 }
927         }
928 }
929
930 static const DrawEngineDataSize GPENCIL_data_size = DRW_VIEWPORT_DATA_SIZE(GPENCIL_Data);
931
932 DrawEngineType draw_engine_gpencil_type = {
933         NULL, NULL,
934         N_("GpencilMode"),
935         &GPENCIL_data_size,
936         &GPENCIL_engine_init,
937         &GPENCIL_engine_free,
938         &GPENCIL_cache_init,
939         &GPENCIL_cache_populate,
940         &GPENCIL_cache_finish,
941         NULL,
942         &GPENCIL_draw_scene,
943         NULL,
944         NULL,
945         &GPENCIL_render_to_image,
946 };