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