Pass EvaluationContext argument everywhere
[blender.git] / source / blender / editors / render / render_opengl.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
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  * The Original Code is Copyright (C) 2008 Blender Foundation.
19  * All rights reserved.
20  *
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 /** \file blender/editors/render/render_opengl.c
26  *  \ingroup edrend
27  */
28
29
30 #include <math.h>
31 #include <string.h>
32 #include <stddef.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_camera_types.h"
37 #include "BLI_math.h"
38 #include "BLI_math_color_blend.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_utildefines.h"
41 #include "BLI_threads.h"
42 #include "BLI_task.h"
43
44 #include "DNA_scene_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_gpencil_types.h"
47
48 #include "BKE_camera.h"
49 #include "BKE_context.h"
50 #include "BKE_global.h"
51 #include "BKE_image.h"
52 #include "BKE_main.h"
53 #include "BKE_report.h"
54 #include "BKE_scene.h"
55 #include "BKE_sequencer.h"
56 #include "BKE_writeavi.h"
57
58 #include "DEG_depsgraph.h"
59
60 #include "WM_api.h"
61 #include "WM_types.h"
62
63 #include "ED_screen.h"
64 #include "ED_view3d.h"
65 #include "ED_gpencil.h"
66
67 #include "RE_pipeline.h"
68 #include "IMB_imbuf_types.h"
69 #include "IMB_imbuf.h"
70 #include "IMB_colormanagement.h"
71
72 #include "RNA_access.h"
73 #include "RNA_define.h"
74
75 #include "GPU_compositing.h"
76 #include "GPU_framebuffer.h"
77 #include "GPU_matrix.h"
78
79 #include "render_intern.h"
80
81 /* Define this to get timing information. */
82 // #undef DEBUG_TIME
83
84 #ifdef DEBUG_TIME
85 #  include "PIL_time.h"
86 #endif
87
88 // TODO(sergey): Find better approximation of the scheduled frames.
89 // For really highres renders it might fail still.
90 #define MAX_SCHEDULED_FRAMES 8
91
92 typedef struct OGLRender {
93         Main *bmain;
94         Render *re;
95         Scene *scene;
96         SceneLayer *scene_layer;
97
98         View3D *v3d;
99         RegionView3D *rv3d;
100         ARegion *ar;
101
102         ScrArea *prevsa;
103         ARegion *prevar;
104
105         int views_len;  /* multi-view views */
106
107         bool is_sequencer;
108         SpaceSeq *sseq;
109         struct {
110                 ImBuf **ibufs_arr;
111         } seq_data;
112
113
114         Image *ima;
115         ImageUser iuser;
116
117         GPUOffScreen *ofs;
118         int ofs_samples;
119         bool ofs_full_samples;
120         GPUFX *fx;
121         int sizex, sizey;
122         int write_still;
123
124         ReportList *reports;
125         bMovieHandle *mh;
126         int cfrao, nfra;
127
128         int totvideos;
129
130         /* quick lookup */
131         int view_id;
132
133         /* wm vars for timer and progress cursor */
134         wmWindowManager *wm;
135         wmWindow *win;
136
137         wmTimer *timer; /* use to check if running modal or not (invoke'd or exec'd)*/
138         void **movie_ctx_arr;
139
140         TaskScheduler *task_scheduler;
141         TaskPool *task_pool;
142         bool pool_ok;
143         bool is_animation;
144         SpinLock reports_lock;
145         unsigned int num_scheduled_frames;
146         ThreadMutex task_mutex;
147         ThreadCondition task_condition;
148
149 #ifdef DEBUG_TIME
150         double time_start;
151 #endif
152 } OGLRender;
153
154 static bool screen_opengl_is_multiview(OGLRender *oglrender)
155 {
156         View3D *v3d = oglrender->v3d;
157         RegionView3D *rv3d = oglrender->rv3d;
158         RenderData *rd = &oglrender->scene->r;
159
160         if ((rd == NULL) || ((!oglrender->is_sequencer) && ((rv3d == NULL) || (v3d == NULL))))
161                 return false;
162
163         return (rd->scemode & R_MULTIVIEW) && ((oglrender->is_sequencer) || (rv3d->persp == RV3D_CAMOB && v3d->camera));
164 }
165
166 static void screen_opengl_views_setup(OGLRender *oglrender)
167 {
168         RenderResult *rr;
169         RenderView *rv;
170         SceneRenderView *srv;
171         bool is_multiview;
172         Object *camera;
173         View3D *v3d = oglrender->v3d;
174
175         RenderData *rd = &oglrender->scene->r;
176
177         rr = RE_AcquireResultWrite(oglrender->re);
178
179         is_multiview = screen_opengl_is_multiview(oglrender);
180
181         if (!is_multiview) {
182                 /* we only have one view when multiview is off */
183                 rv = rr->views.first;
184
185                 if (rv == NULL) {
186                         rv = MEM_callocN(sizeof(RenderView), "new opengl render view");
187                         BLI_addtail(&rr->views, rv);
188                 }
189
190                 while (rv->next) {
191                         RenderView *rv_del = rv->next;
192                         BLI_remlink(&rr->views, rv_del);
193
194                         if (rv_del->rectf)
195                                 MEM_freeN(rv_del->rectf);
196
197                         if (rv_del->rectz)
198                                 MEM_freeN(rv_del->rectz);
199
200                         if (rv_del->rect32)
201                                 MEM_freeN(rv_del->rect32);
202
203                         MEM_freeN(rv_del);
204                 }
205         }
206         else {
207                 if (!oglrender->is_sequencer)
208                         RE_SetOverrideCamera(oglrender->re, V3D_CAMERA_SCENE(oglrender->scene, v3d));
209
210                 /* remove all the views that are not needed */
211                 rv = rr->views.last;
212                 while (rv) {
213                         srv = BLI_findstring(&rd->views, rv->name, offsetof(SceneRenderView, name));
214                         if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
215                                 rv = rv->prev;
216                         }
217                         else {
218                                 RenderView *rv_del = rv;
219                                 rv  = rv_del->prev;
220
221                                 BLI_remlink(&rr->views, rv_del);
222
223                                 if (rv_del->rectf)
224                                         MEM_freeN(rv_del->rectf);
225
226                                 if (rv_del->rectz)
227                                         MEM_freeN(rv_del->rectz);
228
229                                 if (rv_del->rect32)
230                                         MEM_freeN(rv_del->rect32);
231
232                                 MEM_freeN(rv_del);
233                         }
234                 }
235
236                 /* create all the views that are needed */
237                 for (srv = rd->views.first; srv; srv = srv->next) {
238                         if (BKE_scene_multiview_is_render_view_active(rd, srv) == false)
239                                 continue;
240
241                         rv = BLI_findstring(&rr->views, srv->name, offsetof(SceneRenderView, name));
242
243                         if (rv == NULL) {
244                                 rv = MEM_callocN(sizeof(RenderView), "new opengl render view");
245                                 BLI_strncpy(rv->name, srv->name, sizeof(rv->name));
246                                 BLI_addtail(&rr->views, rv);
247                         }
248                 }
249         }
250
251         if (!(is_multiview && BKE_scene_multiview_is_stereo3d(rd)))
252                 oglrender->iuser.flag &= ~IMA_SHOW_STEREO;
253
254         /* will only work for non multiview correctly */
255         if (v3d) {
256                 camera = BKE_camera_multiview_render(oglrender->scene, v3d->camera, "new opengl render view");
257                 BKE_render_result_stamp_info(oglrender->scene, camera, rr, false);
258         }
259         else {
260                 BKE_render_result_stamp_info(oglrender->scene, oglrender->scene->camera, rr, false);
261         }
262
263         RE_ReleaseResult(oglrender->re);
264 }
265
266 static void screen_opengl_render_doit(const bContext *C, OGLRender *oglrender, RenderResult *rr)
267 {
268         Scene *scene = oglrender->scene;
269         SceneLayer *sl = oglrender->scene_layer;
270         ARegion *ar = oglrender->ar;
271         View3D *v3d = oglrender->v3d;
272         RegionView3D *rv3d = oglrender->rv3d;
273         Object *camera = NULL;
274         int sizex = oglrender->sizex;
275         int sizey = oglrender->sizey;
276         const short view_context = (v3d != NULL);
277         bool draw_bgpic = true;
278         bool draw_sky = (scene->r.alphamode == R_ADDSKY);
279         unsigned char *rect = NULL;
280         const char *viewname = RE_GetActiveRenderView(oglrender->re);
281         ImBuf *ibuf_result = NULL;
282         EvaluationContext eval_ctx;
283
284         CTX_data_eval_ctx(C, &eval_ctx);
285
286         if (oglrender->is_sequencer) {
287                 SpaceSeq *sseq = oglrender->sseq;
288                 struct bGPdata *gpd = (sseq && (sseq->flag & SEQ_SHOW_GPENCIL)) ? sseq->gpd : NULL;
289
290                 /* use pre-calculated ImBuf (avoids deadlock), see: */
291                 ImBuf *ibuf = oglrender->seq_data.ibufs_arr[oglrender->view_id];
292
293                 if (ibuf) {
294                         ImBuf *out = IMB_dupImBuf(ibuf);
295                         IMB_freeImBuf(ibuf);
296                         /* OpenGL render is considered to be preview and should be
297                          * as fast as possible. So currently we're making sure sequencer
298                          * result is always byte to simplify color management pipeline.
299                          *
300                          * TODO(sergey): In the case of output to float container (EXR)
301                          * it actually makes sense to keep float buffer instead.
302                          */
303                         if (out->rect_float != NULL) {
304                                 IMB_rect_from_float(out);
305                                 imb_freerectfloatImBuf(out);
306                         }
307                         BLI_assert((oglrender->sizex == ibuf->x) && (oglrender->sizey == ibuf->y));
308                         RE_render_result_rect_from_ibuf(rr, &scene->r, out, oglrender->view_id);
309                         IMB_freeImBuf(out);
310                 }
311                 else if (gpd) {
312                         /* If there are no strips, Grease Pencil still needs a buffer to draw on */
313                         ImBuf *out = IMB_allocImBuf(oglrender->sizex, oglrender->sizey, 32, IB_rect);
314                         RE_render_result_rect_from_ibuf(rr, &scene->r, out, oglrender->view_id);
315                         IMB_freeImBuf(out);
316                 }
317
318                 if (gpd) {
319                         int i;
320                         unsigned char *gp_rect;
321                         unsigned char *render_rect = (unsigned char *)RE_RenderViewGetById(rr, oglrender->view_id)->rect32;
322
323                         GPU_offscreen_bind(oglrender->ofs, true);
324
325                         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
326                         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
327
328                         wmOrtho2(0, sizex, 0, sizey);
329                         gpuTranslate2f(sizex / 2, sizey / 2);
330
331                         G.f |= G_RENDER_OGL;
332                         ED_gpencil_draw_ex(scene, gpd, sizex, sizey, scene->r.cfra, SPACE_SEQ);
333                         G.f &= ~G_RENDER_OGL;
334
335                         gp_rect = MEM_mallocN(sizex * sizey * sizeof(unsigned char) * 4, "offscreen rect");
336                         GPU_offscreen_read_pixels(oglrender->ofs, GL_UNSIGNED_BYTE, gp_rect);
337
338                         for (i = 0; i < sizex * sizey * 4; i += 4) {
339                                 blend_color_mix_byte(&render_rect[i], &render_rect[i], &gp_rect[i]);
340                         }
341                         GPU_offscreen_unbind(oglrender->ofs, true);
342
343                         MEM_freeN(gp_rect);
344                 }
345         }
346         else {
347                 /* shouldnt suddenly give errors mid-render but possible */
348                 char err_out[256] = "unknown";
349                 ImBuf *ibuf_view;
350                 const int alpha_mode = (draw_sky) ? R_ADDSKY : R_ALPHAPREMUL;
351
352                 if (view_context) {
353                         ibuf_view = ED_view3d_draw_offscreen_imbuf(
354                                &eval_ctx, scene, sl, v3d, ar, sizex, sizey,
355                                IB_rect, draw_bgpic,
356                                alpha_mode, oglrender->ofs_samples, oglrender->ofs_full_samples, viewname,
357                                oglrender->fx, oglrender->ofs, err_out);
358
359                         /* for stamp only */
360                         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
361                                 camera = BKE_camera_multiview_render(oglrender->scene, v3d->camera, viewname);
362                         }
363                 }
364                 else {
365                         ibuf_view = ED_view3d_draw_offscreen_imbuf_simple(
366                                 &eval_ctx, scene, sl, scene->camera, oglrender->sizex, oglrender->sizey,
367                                 IB_rect, OB_SOLID, false, true, true,
368                                 alpha_mode, oglrender->ofs_samples, oglrender->ofs_full_samples, viewname,
369                                 oglrender->fx, oglrender->ofs, err_out);
370                         camera = scene->camera;
371                 }
372
373                 if (ibuf_view) {
374                         ibuf_result = ibuf_view;
375                         rect = (unsigned char *)ibuf_view->rect;
376                 }
377                 else {
378                         fprintf(stderr, "%s: failed to get buffer, %s\n", __func__, err_out);
379                 }
380         }
381
382         if (ibuf_result != NULL) {
383                 if ((scene->r.stamp & R_STAMP_ALL) && (scene->r.stamp & R_STAMP_DRAW)) {
384                         BKE_image_stamp_buf(scene, camera, NULL, rect, NULL, rr->rectx, rr->recty, 4);
385                 }
386                 RE_render_result_rect_from_ibuf(rr, &scene->r, ibuf_result, oglrender->view_id);
387                 IMB_freeImBuf(ibuf_result);
388         }
389 }
390
391 static void screen_opengl_render_write(OGLRender *oglrender)
392 {
393         Scene *scene = oglrender->scene;
394         RenderResult *rr;
395         bool ok;
396         char name[FILE_MAX];
397
398         rr = RE_AcquireResultRead(oglrender->re);
399
400         BKE_image_path_from_imformat(
401                 name, scene->r.pic, oglrender->bmain->name, scene->r.cfra,
402                 &scene->r.im_format, (scene->r.scemode & R_EXTENSION) != 0, false, NULL);
403
404         /* write images as individual images or stereo */
405         BKE_render_result_stamp_info(scene, scene->camera, rr, false);
406         ok = RE_WriteRenderViewsImage(oglrender->reports, rr, scene, false, name);
407
408         RE_ReleaseResultImage(oglrender->re);
409
410         if (ok) printf("OpenGL Render written to '%s'\n", name);
411         else printf("OpenGL Render failed to write '%s'\n", name);
412 }
413
414 static void addAlphaOverFloat(float dest[4], const float source[4])
415 {
416         /* d = s + (1-alpha_s)d*/
417         float mul;
418
419         mul = 1.0f - source[3];
420
421         dest[0] = (mul * dest[0]) + source[0];
422         dest[1] = (mul * dest[1]) + source[1];
423         dest[2] = (mul * dest[2]) + source[2];
424         dest[3] = (mul * dest[3]) + source[3];
425
426 }
427
428 /* add renderlayer and renderpass for each grease pencil layer for using in composition */
429 static void add_gpencil_renderpass(const bContext *C, OGLRender *oglrender, RenderResult *rr, RenderView *rv)
430 {
431         bGPdata *gpd = oglrender->scene->gpd;
432         Scene *scene = oglrender->scene;
433
434         /* sanity checks */
435         if (gpd == NULL) {
436                 return;
437         }
438         if (scene == NULL) {
439                 return;
440         }
441         if (BLI_listbase_is_empty(&gpd->layers)) {
442                 return;
443         }
444         if (oglrender->v3d != NULL && (oglrender->v3d->flag2 & V3D_SHOW_GPENCIL) == 0) {
445                 return;
446         }
447
448         /* save old alpha mode */
449         short oldalphamode = scene->r.alphamode;
450         /* set alpha transparent for gp */
451         scene->r.alphamode = R_ALPHAPREMUL;
452         
453         /* saves layer status */
454         short *oldsts = MEM_mallocN(BLI_listbase_count(&gpd->layers) * sizeof(short), "temp_gplayers_flag");
455         int i = 0;
456         for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
457                 oldsts[i] = gpl->flag;
458                 ++i;
459         }
460         /* loop all layers to create separate render */
461         for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
462                 /* dont draw layer if hidden */
463                 if (gpl->flag & GP_LAYER_HIDE)
464                         continue;
465                 /* hide all layer except current */
466                 for (bGPDlayer *gph = gpd->layers.first; gph; gph = gph->next) {
467                         if (gpl != gph) {
468                                 gph->flag |= GP_LAYER_HIDE;
469                         }
470                 }
471
472                 /* render this gp layer */
473                 screen_opengl_render_doit(C, oglrender, rr);
474                 
475                 /* add RendePass composite */
476                 RenderPass *rp = RE_create_gp_pass(rr, gpl->info, rv->name);
477
478                 /* copy image data from rectf */
479                 // XXX: Needs conversion.
480                 unsigned char *src = (unsigned char *)RE_RenderViewGetById(rr, oglrender->view_id)->rect32;
481                 if (src != NULL) {
482                         float *dest = rp->rect;
483
484                         int x, y, rectx, recty;
485                         rectx = rr->rectx;
486                         recty = rr->recty;
487                         for (y = 0; y < recty; y++) {
488                                 for (x = 0; x < rectx; x++) {
489                                         unsigned char *pixSrc = src + 4 * (rectx * y + x);
490                                         if (pixSrc[3] > 0) {
491                                                 float *pixDest = dest + 4 * (rectx * y + x);
492                                                 float float_src[4];
493                                                 srgb_to_linearrgb_uchar4(float_src, pixSrc);
494                                                 addAlphaOverFloat(pixDest, float_src);
495                                         }
496                                 }
497                         }
498                 }
499                 /* back layer status */
500                 i = 0;
501                 for (bGPDlayer *gph = gpd->layers.first; gph; gph = gph->next) {
502                         gph->flag = oldsts[i];
503                         ++i;
504                 }
505         }
506         /* free memory */
507         MEM_freeN(oldsts);
508
509         /* back default alpha mode */
510         scene->r.alphamode = oldalphamode;
511 }
512
513 static void screen_opengl_render_apply(const bContext *C, OGLRender *oglrender)
514 {
515         RenderResult *rr;
516         RenderView *rv;
517         int view_id;
518         ImBuf *ibuf;
519         void *lock;
520
521         if (oglrender->is_sequencer) {
522                 Scene *scene = oglrender->scene;
523
524                 SeqRenderData context;
525                 SpaceSeq *sseq = oglrender->sseq;
526                 int chanshown = sseq ? sseq->chanshown : 0;
527
528                 BKE_sequencer_new_render_data(
529                         oglrender->bmain->eval_ctx, oglrender->bmain, scene,
530                         oglrender->sizex, oglrender->sizey, 100.0f,
531                         &context);
532
533                 for (view_id = 0; view_id < oglrender->views_len; view_id++) {
534                         context.view_id = view_id;
535                         context.gpu_offscreen = oglrender->ofs;
536                         context.gpu_fx = oglrender->fx;
537                         context.gpu_full_samples = oglrender->ofs_full_samples;
538
539                         oglrender->seq_data.ibufs_arr[view_id] = BKE_sequencer_give_ibuf(&context, CFRA, chanshown);
540                 }
541         }
542
543         rr = RE_AcquireResultRead(oglrender->re);
544         for (rv = rr->views.first, view_id = 0; rv; rv = rv->next, view_id++) {
545                 BLI_assert(view_id < oglrender->views_len);
546                 RE_SetActiveRenderView(oglrender->re, rv->name);
547                 oglrender->view_id = view_id;
548                 /* add grease pencil passes. For sequencer, the render does not include renderpasses
549                  * TODO: The sequencer render of grease pencil should be rethought */
550                 if (!oglrender->is_sequencer) {
551                         add_gpencil_renderpass(C, oglrender, rr, rv);
552                 }
553                 /* render composite */
554                 screen_opengl_render_doit(C, oglrender, rr);
555         }
556
557         RE_ReleaseResult(oglrender->re);
558
559         ibuf = BKE_image_acquire_ibuf(oglrender->ima, &oglrender->iuser, &lock);
560         if (ibuf) {
561                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
562         }
563         BKE_image_release_ibuf(oglrender->ima, ibuf, lock);
564
565         if (oglrender->write_still) {
566                 screen_opengl_render_write(oglrender);
567         }
568 }
569
570 static bool screen_opengl_fullsample_enabled(Scene *scene)
571 {
572         if (scene->r.scemode & R_FULL_SAMPLE) {
573                 return true;
574         }
575         else {
576                 /* XXX TODO:
577                  * Technically if the hardware supports MSAA we could keep using Blender 2.7x approach.
578                  * However anti-aliasing without full_sample is not playing well even in 2.7x.
579                  *
580                  * For example, if you enable depth of field, there is aliasing, even if the viewport is fine.
581                  * For 2.8x this is more complicated because so many things rely on shader.
582                  * So until we fix the gpu_framebuffer anti-aliasing suupport we need to force full sample.
583                  */
584                 return true;
585         }
586 }
587
588 static bool screen_opengl_render_init(bContext *C, wmOperator *op)
589 {
590         /* new render clears all callbacks */
591         wmWindowManager *wm = CTX_wm_manager(C);
592         wmWindow *win = CTX_wm_window(C);
593
594         Scene *scene = CTX_data_scene(C);
595         ScrArea *prevsa = CTX_wm_area(C);
596         ARegion *prevar = CTX_wm_region(C);
597         GPUOffScreen *ofs;
598         OGLRender *oglrender;
599         int sizex, sizey;
600         const int samples = (scene->r.mode & R_OSA) ? scene->r.osa : 0;
601         const bool full_samples = (samples != 0) && screen_opengl_fullsample_enabled(scene);
602         bool is_view_context = RNA_boolean_get(op->ptr, "view_context");
603         const bool is_animation = RNA_boolean_get(op->ptr, "animation");
604         const bool is_sequencer = RNA_boolean_get(op->ptr, "sequencer");
605         const bool is_write_still = RNA_boolean_get(op->ptr, "write_still");
606         char err_out[256] = "unknown";
607
608         if (G.background) {
609                 BKE_report(op->reports, RPT_ERROR, "Cannot use OpenGL render in background mode (no opengl context)");
610                 return false;
611         }
612
613         /* only one render job at a time */
614         if (WM_jobs_test(wm, scene, WM_JOB_TYPE_RENDER))
615                 return false;
616
617         if (is_sequencer) {
618                 is_view_context = false;
619         }
620         else {
621                 /* ensure we have a 3d view */
622                 if (!ED_view3d_context_activate(C)) {
623                         RNA_boolean_set(op->ptr, "view_context", false);
624                         is_view_context = false;
625                 }
626
627                 if (!is_view_context && scene->camera == NULL) {
628                         BKE_report(op->reports, RPT_ERROR, "Scene has no camera");
629                         return false;
630                 }
631         }
632
633         if (!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
634                 BKE_report(op->reports, RPT_ERROR, "Cannot write a single file with an animation format selected");
635                 return false;
636         }
637
638         /* stop all running jobs, except screen one. currently previews frustrate Render */
639         WM_jobs_kill_all_except(wm, CTX_wm_screen(C));
640
641         /* create offscreen buffer */
642         sizex = (scene->r.size * scene->r.xsch) / 100;
643         sizey = (scene->r.size * scene->r.ysch) / 100;
644
645         /* corrects render size with actual size, not every card supports non-power-of-two dimensions */
646         ofs = GPU_offscreen_create(sizex, sizey, full_samples ? 0 : samples, err_out);
647
648         if (!ofs) {
649                 BKE_reportf(op->reports, RPT_ERROR, "Failed to create OpenGL off-screen buffer, %s", err_out);
650                 return false;
651         }
652
653         /* allocate opengl render */
654         oglrender = MEM_callocN(sizeof(OGLRender), "OGLRender");
655         op->customdata = oglrender;
656
657         oglrender->ofs = ofs;
658         oglrender->ofs_samples = samples;
659         oglrender->ofs_full_samples = full_samples;
660         oglrender->sizex = sizex;
661         oglrender->sizey = sizey;
662         oglrender->bmain = CTX_data_main(C);
663         oglrender->scene = scene;
664         oglrender->scene_layer = CTX_data_scene_layer(C);
665         oglrender->cfrao = scene->r.cfra;
666
667         oglrender->write_still = is_write_still && !is_animation;
668         oglrender->is_animation = is_animation;
669
670         oglrender->views_len = BKE_scene_multiview_num_views_get(&scene->r);
671
672         oglrender->is_sequencer = is_sequencer;
673         if (is_sequencer) {
674                 oglrender->sseq = CTX_wm_space_seq(C);
675                 ImBuf **ibufs_arr = MEM_callocN(sizeof(*ibufs_arr) * oglrender->views_len, __func__);
676                 oglrender->seq_data.ibufs_arr = ibufs_arr;
677         }
678
679         oglrender->prevsa = prevsa;
680         oglrender->prevar = prevar;
681
682         if (is_view_context) {
683                 ED_view3d_context_user_region(C, &oglrender->v3d, &oglrender->ar); /* so quad view renders camera */
684                 oglrender->rv3d = oglrender->ar->regiondata;
685
686                 /* MUST be cleared on exit */
687                 oglrender->scene->customdata_mask_modal = ED_view3d_datamask(oglrender->scene, oglrender->v3d);
688
689                 /* apply immediately in case we're rendering from a script,
690                  * running notifiers again will overwrite */
691                 oglrender->scene->customdata_mask |= oglrender->scene->customdata_mask_modal;
692
693                 if (oglrender->v3d->fx_settings.fx_flag & (GPU_FX_FLAG_DOF | GPU_FX_FLAG_SSAO)) {
694                         oglrender->fx = GPU_fx_compositor_create();
695                 }
696         }
697
698         /* create render */
699         oglrender->re = RE_NewRender(scene->id.name);
700
701         /* create image and image user */
702         oglrender->ima = BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
703         BKE_image_signal(oglrender->ima, NULL, IMA_SIGNAL_FREE);
704         BKE_image_backup_render(oglrender->scene, oglrender->ima, true);
705
706         oglrender->iuser.scene = scene;
707         oglrender->iuser.ok = 1;
708
709         /* create render result */
710         RE_InitState(oglrender->re, NULL, &scene->r, NULL, sizex, sizey, NULL);
711
712         /* create render views */
713         screen_opengl_views_setup(oglrender);
714
715         /* wm vars */
716         oglrender->wm = wm;
717         oglrender->win = win;
718
719         oglrender->totvideos = 0;
720         oglrender->mh = NULL;
721         oglrender->movie_ctx_arr = NULL;
722
723         if (is_animation) {
724                 TaskScheduler *task_scheduler = BLI_task_scheduler_get();
725                 if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
726                         task_scheduler = BLI_task_scheduler_create(1);
727                         oglrender->task_scheduler = task_scheduler;
728                         oglrender->task_pool = BLI_task_pool_create_background(task_scheduler,
729                                                                                oglrender);
730                 }
731                 else {
732                         oglrender->task_scheduler = NULL;
733                         oglrender->task_pool = BLI_task_pool_create(task_scheduler,
734                                                                     oglrender);
735                 }
736                 oglrender->pool_ok = true;
737                 BLI_spin_init(&oglrender->reports_lock);
738         }
739         else {
740                 oglrender->task_scheduler = NULL;
741                 oglrender->task_pool = NULL;
742         }
743         oglrender->num_scheduled_frames = 0;
744         BLI_mutex_init(&oglrender->task_mutex);
745         BLI_condition_init(&oglrender->task_condition);
746
747 #ifdef DEBUG_TIME
748         oglrender->time_start = PIL_check_seconds_timer();
749 #endif
750
751         return true;
752 }
753
754 static void screen_opengl_render_end(bContext *C, OGLRender *oglrender)
755 {
756         Main *bmain = CTX_data_main(C);
757         Scene *scene = oglrender->scene;
758         int i;
759
760         if (oglrender->is_animation) {
761                 /* Trickery part for movie output:
762                  *
763                  * We MUST write frames in an exact order, so we only let background
764                  * thread to work on that, and main thread is simply waits for that
765                  * thread to do all the dirty work.
766                  *
767                  * After this loop is done work_and_wait() will have nothing to do,
768                  * so we don't run into wrong order of frames written to the stream.
769                  */
770                 if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
771                         BLI_mutex_lock(&oglrender->task_mutex);
772                         while (oglrender->num_scheduled_frames > 0) {
773                                 BLI_condition_wait(&oglrender->task_condition,
774                                                    &oglrender->task_mutex);
775                         }
776                         BLI_mutex_unlock(&oglrender->task_mutex);
777                 }
778                 BLI_task_pool_work_and_wait(oglrender->task_pool);
779                 BLI_task_pool_free(oglrender->task_pool);
780                 /* Depending on various things we might or might not use global scheduler. */
781                 if (oglrender->task_scheduler != NULL) {
782                         BLI_task_scheduler_free(oglrender->task_scheduler);
783                 }
784                 BLI_spin_end(&oglrender->reports_lock);
785         }
786         BLI_mutex_end(&oglrender->task_mutex);
787         BLI_condition_end(&oglrender->task_condition);
788
789 #ifdef DEBUG_TIME
790         printf("Total render time: %f\n", PIL_check_seconds_timer() - oglrender->time_start);
791 #endif
792
793         if (oglrender->mh) {
794                 if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
795                         for (i = 0; i < oglrender->totvideos; i++) {
796                                 oglrender->mh->end_movie(oglrender->movie_ctx_arr[i]);
797                                 oglrender->mh->context_free(oglrender->movie_ctx_arr[i]);
798                         }
799                 }
800
801                 if (oglrender->movie_ctx_arr) {
802                         MEM_freeN(oglrender->movie_ctx_arr);
803                 }
804         }
805
806         if (oglrender->timer) { /* exec will not have a timer */
807                 scene->r.cfra = oglrender->cfrao;
808                 BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene);
809
810                 WM_event_remove_timer(oglrender->wm, oglrender->win, oglrender->timer);
811         }
812
813         WM_cursor_modal_restore(oglrender->win);
814
815         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, oglrender->scene);
816
817         if (oglrender->fx)
818                 GPU_fx_compositor_destroy(oglrender->fx);
819
820         GPU_offscreen_free(oglrender->ofs);
821
822         if (oglrender->is_sequencer) {
823                 MEM_freeN(oglrender->seq_data.ibufs_arr);
824         }
825
826         oglrender->scene->customdata_mask_modal = 0;
827
828         CTX_wm_area_set(C, oglrender->prevsa);
829         CTX_wm_region_set(C, oglrender->prevar);
830
831         MEM_freeN(oglrender);
832 }
833
834 static void screen_opengl_render_cancel(bContext *C, wmOperator *op)
835 {
836         screen_opengl_render_end(C, op->customdata);
837 }
838
839 /* share between invoke and exec */
840 static bool screen_opengl_render_anim_initialize(bContext *C, wmOperator *op)
841 {
842         /* initialize animation */
843         OGLRender *oglrender;
844         Scene *scene;
845
846         oglrender = op->customdata;
847         scene = oglrender->scene;
848         oglrender->totvideos = BKE_scene_multiview_num_videos_get(&scene->r);
849
850         oglrender->reports = op->reports;
851
852         if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
853                 size_t width, height;
854                 int i;
855
856                 BKE_scene_multiview_videos_dimensions_get(&scene->r, oglrender->sizex, oglrender->sizey, &width, &height);
857                 oglrender->mh = BKE_movie_handle_get(scene->r.im_format.imtype);
858
859                 if (oglrender->mh == NULL) {
860                         BKE_report(oglrender->reports, RPT_ERROR, "Movie format unsupported");
861                         screen_opengl_render_end(C, oglrender);
862                         return false;
863                 }
864
865                 oglrender->movie_ctx_arr = MEM_mallocN(sizeof(void *) * oglrender->totvideos, "Movies");
866
867                 for (i = 0; i < oglrender->totvideos; i++) {
868                         const char *suffix = BKE_scene_multiview_view_id_suffix_get(&scene->r, i);
869
870                         oglrender->movie_ctx_arr[i] = oglrender->mh->context_create();
871                         if (!oglrender->mh->start_movie(oglrender->movie_ctx_arr[i], scene, &scene->r, oglrender->sizex,
872                                                         oglrender->sizey, oglrender->reports, PRVRANGEON != 0, suffix))
873                         {
874                                 screen_opengl_render_end(C, oglrender);
875                                 return false;
876                         }
877                 }
878         }
879
880         oglrender->cfrao = scene->r.cfra;
881         oglrender->nfra = PSFRA;
882         scene->r.cfra = PSFRA;
883
884         return true;
885 }
886
887 typedef struct WriteTaskData {
888         RenderResult *rr;
889         Scene tmp_scene;
890 } WriteTaskData;
891
892 static void write_result_func(TaskPool * __restrict pool,
893                               void *task_data_v,
894                               int UNUSED(thread_id))
895 {
896         OGLRender *oglrender = (OGLRender *) BLI_task_pool_userdata(pool);
897         WriteTaskData *task_data = (WriteTaskData *) task_data_v;
898         Scene *scene = &task_data->tmp_scene;
899         RenderResult *rr = task_data->rr;
900         const bool is_movie = BKE_imtype_is_movie(scene->r.im_format.imtype);
901         const int cfra = scene->r.cfra;
902         bool ok;
903         /* Don't attempt to write if we've got an error. */
904         if (!oglrender->pool_ok) {
905                 RE_FreeRenderResult(rr);
906                 BLI_mutex_lock(&oglrender->task_mutex);
907                 oglrender->num_scheduled_frames--;
908                 BLI_condition_notify_all(&oglrender->task_condition);
909                 BLI_mutex_unlock(&oglrender->task_mutex);
910                 return;
911         }
912         /* Construct local thread0safe copy of reports structure which we can
913          * safely pass to the underlying functions.
914          */
915         ReportList reports;
916         BKE_reports_init(&reports, oglrender->reports->flag & ~RPT_PRINT);
917         /* Do actual save logic here, depending on the file format.
918          *
919          * NOTE: We have to construct temporary scene with proper scene->r.cfra.
920          * This is because underlying calls do not use r.cfra but use scene
921          * for that.
922          */
923         if (is_movie) {
924                 ok = RE_WriteRenderViewsMovie(&reports,
925                                               rr,
926                                               scene,
927                                               &scene->r,
928                                               oglrender->mh,
929                                               oglrender->movie_ctx_arr,
930                                               oglrender->totvideos,
931                                               PRVRANGEON != 0);
932         }
933         else {
934                 /* TODO(sergey): We can in theory save some CPU ticks here because we
935                  * calculate file name again here.
936                  */
937                 char name[FILE_MAX];
938                 BKE_image_path_from_imformat(name,
939                                              scene->r.pic,
940                                              oglrender->bmain->name,
941                                              cfra,
942                                              &scene->r.im_format,
943                                              (scene->r.scemode & R_EXTENSION) != 0,
944                                              true,
945                                              NULL);
946
947                 BKE_render_result_stamp_info(scene, scene->camera, rr, false);
948                 ok = RE_WriteRenderViewsImage(NULL, rr, scene, true, name);
949                 if (!ok) {
950                         BKE_reportf(&reports,
951                                     RPT_ERROR,
952                                     "Write error: cannot save %s",
953                                     name);
954                 }
955         }
956         if (reports.list.first != NULL) {
957                 BLI_spin_lock(&oglrender->reports_lock);
958                 for (Report *report = reports.list.first;
959                      report != NULL;
960                      report = report->next)
961                 {
962                         BKE_report(oglrender->reports,
963                                    report->type,
964                                    report->message);
965                 }
966                 BLI_spin_unlock(&oglrender->reports_lock);
967         }
968         if (!ok) {
969                 oglrender->pool_ok = false;
970         }
971         RE_FreeRenderResult(rr);
972         BLI_mutex_lock(&oglrender->task_mutex);
973         oglrender->num_scheduled_frames--;
974         BLI_condition_notify_all(&oglrender->task_condition);
975         BLI_mutex_unlock(&oglrender->task_mutex);
976 }
977
978 static bool schedule_write_result(OGLRender *oglrender, RenderResult *rr)
979 {
980         if (!oglrender->pool_ok) {
981                 RE_FreeRenderResult(rr);
982                 return false;
983         }
984         Scene *scene = oglrender->scene;
985         WriteTaskData *task_data = MEM_mallocN(sizeof(WriteTaskData), "write task data");
986         task_data->rr = rr;
987         task_data->tmp_scene = *scene;
988         BLI_mutex_lock(&oglrender->task_mutex);
989         oglrender->num_scheduled_frames++;
990         if (oglrender->num_scheduled_frames > MAX_SCHEDULED_FRAMES) {
991                 BLI_condition_wait(&oglrender->task_condition,
992                                    &oglrender->task_mutex);
993         }
994         BLI_mutex_unlock(&oglrender->task_mutex);
995         BLI_task_pool_push(oglrender->task_pool,
996                            write_result_func,
997                            task_data,
998                            true,
999                            TASK_PRIORITY_LOW);
1000         return true;
1001 }
1002
1003 static bool screen_opengl_render_anim_step(bContext *C, wmOperator *op)
1004 {
1005         Main *bmain = CTX_data_main(C);
1006         OGLRender *oglrender = op->customdata;
1007         Scene *scene = oglrender->scene;
1008         char name[FILE_MAX];
1009         bool ok = false;
1010         const bool view_context = (oglrender->v3d != NULL);
1011         bool is_movie;
1012         RenderResult *rr;
1013
1014         /* go to next frame */
1015         if (CFRA < oglrender->nfra)
1016                 CFRA++;
1017         while (CFRA < oglrender->nfra) {
1018                 BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene);
1019                 CFRA++;
1020         }
1021
1022         is_movie = BKE_imtype_is_movie(scene->r.im_format.imtype);
1023
1024         if (!is_movie) {
1025                 BKE_image_path_from_imformat(
1026                         name, scene->r.pic, oglrender->bmain->name, scene->r.cfra,
1027                         &scene->r.im_format, (scene->r.scemode & R_EXTENSION) != 0, true, NULL);
1028
1029                 if ((scene->r.mode & R_NO_OVERWRITE) && BLI_exists(name)) {
1030                         BLI_spin_lock(&oglrender->reports_lock);
1031                         BKE_reportf(op->reports, RPT_INFO, "Skipping existing frame \"%s\"", name);
1032                         BLI_spin_unlock(&oglrender->reports_lock);
1033                         ok = true;
1034                         goto finally;
1035                 }
1036         }
1037
1038         WM_cursor_time(oglrender->win, scene->r.cfra);
1039
1040         BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene);
1041
1042         if (view_context) {
1043                 if (oglrender->rv3d->persp == RV3D_CAMOB && oglrender->v3d->camera && oglrender->v3d->scenelock) {
1044                         /* since BKE_scene_update_for_newframe() is used rather
1045                          * then ED_update_for_newframe() the camera needs to be set */
1046                         if (BKE_scene_camera_switch_update(scene)) {
1047                                 oglrender->v3d->camera = scene->camera;
1048                         }
1049                 }
1050         }
1051         else {
1052                 BKE_scene_camera_switch_update(scene);
1053         }
1054
1055         /* render into offscreen buffer */
1056         screen_opengl_render_apply(C, oglrender);
1057
1058         /* save to disk */
1059         rr = RE_AcquireResultRead(oglrender->re);
1060         RenderResult *new_rr = RE_DuplicateRenderResult(rr);
1061         RE_ReleaseResult(oglrender->re);
1062
1063         ok = schedule_write_result(oglrender, new_rr);
1064
1065 finally:  /* Step the frame and bail early if needed */
1066
1067         /* go to next frame */
1068         oglrender->nfra += scene->r.frame_step;
1069
1070         /* stop at the end or on error */
1071         if (CFRA >= PEFRA || !ok) {
1072                 screen_opengl_render_end(C, op->customdata);
1073                 return 0;
1074         }
1075
1076         return 1;
1077 }
1078
1079
1080 static int screen_opengl_render_modal(bContext *C, wmOperator *op, const wmEvent *event)
1081 {
1082         OGLRender *oglrender = op->customdata;
1083         const bool anim = RNA_boolean_get(op->ptr, "animation");
1084         bool ret;
1085
1086         switch (event->type) {
1087                 case ESCKEY:
1088                         /* cancel */
1089                         oglrender->pool_ok = false;  /* Flag pool for cancel. */
1090                         screen_opengl_render_end(C, op->customdata);
1091                         return OPERATOR_FINISHED;
1092                 case TIMER:
1093                         /* render frame? */
1094                         if (oglrender->timer == event->customdata)
1095                                 break;
1096                         ATTR_FALLTHROUGH;
1097                 default:
1098                         /* nothing to do */
1099                         return OPERATOR_RUNNING_MODAL;
1100         }
1101
1102         /* run first because screen_opengl_render_anim_step can free oglrender */
1103         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, oglrender->scene);
1104         
1105         if (anim == 0) {
1106                 screen_opengl_render_apply(C, op->customdata);
1107                 screen_opengl_render_end(C, op->customdata);
1108                 return OPERATOR_FINISHED;
1109         }
1110         else {
1111                 ret = screen_opengl_render_anim_step(C, op);
1112         }
1113
1114         /* stop at the end or on error */
1115         if (ret == false) {
1116                 return OPERATOR_FINISHED;
1117         }
1118
1119         return OPERATOR_RUNNING_MODAL;
1120 }
1121
1122 static int screen_opengl_render_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1123 {
1124         OGLRender *oglrender;
1125         const bool anim = RNA_boolean_get(op->ptr, "animation");
1126
1127         if (!screen_opengl_render_init(C, op))
1128                 return OPERATOR_CANCELLED;
1129
1130         if (anim) {
1131                 if (!screen_opengl_render_anim_initialize(C, op))
1132                         return OPERATOR_CANCELLED;
1133         }
1134         
1135         oglrender = op->customdata;
1136         render_view_open(C, event->x, event->y, op->reports);
1137         
1138         /* view may be changed above (R_OUTPUT_WINDOW) */
1139         oglrender->win = CTX_wm_window(C);
1140
1141         WM_event_add_modal_handler(C, op);
1142         oglrender->timer = WM_event_add_timer(oglrender->wm, oglrender->win, TIMER, 0.01f);
1143         
1144         return OPERATOR_RUNNING_MODAL;
1145 }
1146
1147 /* executes blocking render */
1148 static int screen_opengl_render_exec(bContext *C, wmOperator *op)
1149 {
1150         const bool is_animation = RNA_boolean_get(op->ptr, "animation");
1151
1152         if (!screen_opengl_render_init(C, op))
1153                 return OPERATOR_CANCELLED;
1154
1155         if (!is_animation) { /* same as invoke */
1156                 /* render image */
1157                 screen_opengl_render_apply(C, op->customdata);
1158                 screen_opengl_render_end(C, op->customdata);
1159
1160                 return OPERATOR_FINISHED;
1161         }
1162         else {
1163                 bool ret = true;
1164
1165                 if (!screen_opengl_render_anim_initialize(C, op))
1166                         return OPERATOR_CANCELLED;
1167
1168                 while (ret) {
1169                         ret = screen_opengl_render_anim_step(C, op);
1170                 }
1171         }
1172
1173         /* no redraw needed, we leave state as we entered it */
1174 //      ED_update_for_newframe(C, 1);
1175         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, CTX_data_scene(C));
1176
1177         return OPERATOR_FINISHED;
1178 }
1179
1180 void RENDER_OT_opengl(wmOperatorType *ot)
1181 {
1182         PropertyRNA *prop;
1183
1184         /* identifiers */
1185         ot->name = "OpenGL Render";
1186         ot->description = "OpenGL render active viewport";
1187         ot->idname = "RENDER_OT_opengl";
1188
1189         /* api callbacks */
1190         ot->invoke = screen_opengl_render_invoke;
1191         ot->exec = screen_opengl_render_exec; /* blocking */
1192         ot->modal = screen_opengl_render_modal;
1193         ot->cancel = screen_opengl_render_cancel;
1194
1195         ot->poll = ED_operator_screenactive;
1196
1197         prop = RNA_def_boolean(ot->srna, "animation", 0, "Animation", "Render files from the animation range of this scene");
1198         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1199         prop = RNA_def_boolean(ot->srna, "sequencer", 0, "Sequencer", "Render using the sequencer's OpenGL display");
1200         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1201         prop = RNA_def_boolean(ot->srna, "write_still", 0, "Write Image", "Save rendered the image to the output path (used only when animation is disabled)");
1202         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1203         prop = RNA_def_boolean(ot->srna, "view_context", 1, "View Context", "Use the current 3D view for rendering, else use scene settings");
1204         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1205
1206 }
1207
1208 /* function for getting an opengl buffer from a View3D, used by sequencer */
1209 // extern void *sequencer_view3d_cb;