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