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