Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / render / render_internal.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_internal.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 "BLI_listbase.h"
37 #include "BLI_rect.h"
38 #include "BLI_timecode.h"
39 #include "BLI_math.h"
40 #include "BLI_threads.h"
41 #include "BLI_utildefines.h"
42
43 #include "PIL_time.h"
44
45 #include "BLT_translation.h"
46
47 #include "DNA_object_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_view3d_types.h"
50 #include "DNA_userdef_types.h"
51
52 #include "BKE_blender_undo.h"
53 #include "BKE_blender_version.h"
54 #include "BKE_camera.h"
55 #include "BKE_context.h"
56 #include "BKE_colortools.h"
57 #include "BKE_global.h"
58 #include "BKE_image.h"
59 #include "BKE_library.h"
60 #include "BKE_main.h"
61 #include "BKE_node.h"
62 #include "BKE_object.h"
63 #include "BKE_report.h"
64 #include "BKE_sequencer.h"
65 #include "BKE_screen.h"
66 #include "BKE_scene.h"
67
68 #include "DEG_depsgraph.h"
69
70 #include "WM_api.h"
71 #include "WM_types.h"
72
73 #include "ED_object.h"
74 #include "ED_render.h"
75 #include "ED_screen.h"
76 #include "ED_util.h"
77 #include "ED_view3d.h"
78
79 #include "RE_pipeline.h"
80 #include "RE_engine.h"
81
82 #include "IMB_colormanagement.h"
83 #include "IMB_imbuf_types.h"
84
85 #include "GPU_shader.h"
86
87 #include "BIF_gl.h"
88 #include "BIF_glutil.h"
89
90 #include "RNA_access.h"
91 #include "RNA_define.h"
92
93
94 #include "render_intern.h"
95
96 /* Render Callbacks */
97 static int render_break(void *rjv);
98
99 typedef struct RenderJob {
100         Main *main;
101         Scene *scene;
102         Scene *current_scene;
103         Render *re;
104         SceneRenderLayer *srl;
105         struct Object *camera_override;
106         int lay_override;
107         bool v3d_override;
108         bool anim, write_still;
109         Image *image;
110         ImageUser iuser;
111         bool image_outdated;
112         short *stop;
113         short *do_update;
114         float *progress;
115         ReportList *reports;
116         int orig_layer;
117         int last_layer;
118         ScrArea *sa;
119         ColorManagedViewSettings view_settings;
120         ColorManagedDisplaySettings display_settings;
121         bool supports_glsl_draw;
122         bool interface_locked;
123 } RenderJob;
124
125 /* called inside thread! */
126 static void image_buffer_rect_update(RenderJob *rj, RenderResult *rr, ImBuf *ibuf, ImageUser *iuser, volatile rcti *renrect, const char *viewname)
127 {
128         Scene *scene = rj->scene;
129         const float *rectf = NULL;
130         int ymin, ymax, xmin, xmax;
131         int rymin, rxmin;
132         int linear_stride, linear_offset_x, linear_offset_y;
133         ColorManagedViewSettings *view_settings;
134         ColorManagedDisplaySettings *display_settings;
135
136         /* Exception for exr tiles -- display buffer conversion happens here,
137          * NOT in the color management pipeline.
138          */
139         if (ibuf->userflags & IB_DISPLAY_BUFFER_INVALID &&
140             rr->do_exr_tile == false)
141         {
142                 /* The whole image buffer it so be color managed again anyway. */
143                 return;
144         }
145
146         /* if renrect argument, we only refresh scanlines */
147         if (renrect) {
148                 /* if (ymax == recty), rendering of layer is ready, we should not draw, other things happen... */
149                 if (rr->renlay == NULL || renrect->ymax >= rr->recty)
150                         return;
151
152                 /* xmin here is first subrect x coord, xmax defines subrect width */
153                 xmin = renrect->xmin + rr->crop;
154                 xmax = renrect->xmax - xmin + rr->crop;
155                 if (xmax < 2)
156                         return;
157
158                 ymin = renrect->ymin + rr->crop;
159                 ymax = renrect->ymax - ymin + rr->crop;
160                 if (ymax < 2)
161                         return;
162                 renrect->ymin = renrect->ymax;
163
164         }
165         else {
166                 xmin = ymin = rr->crop;
167                 xmax = rr->rectx - 2 * rr->crop;
168                 ymax = rr->recty - 2 * rr->crop;
169         }
170
171         /* xmin ymin is in tile coords. transform to ibuf */
172         rxmin = rr->tilerect.xmin + xmin;
173         if (rxmin >= ibuf->x) return;
174         rymin = rr->tilerect.ymin + ymin;
175         if (rymin >= ibuf->y) return;
176
177         if (rxmin + xmax > ibuf->x)
178                 xmax = ibuf->x - rxmin;
179         if (rymin + ymax > ibuf->y)
180                 ymax = ibuf->y - rymin;
181
182         if (xmax < 1 || ymax < 1) return;
183
184         /* The thing here is, the logic below (which was default behavior
185          * of how rectf is acquiring since forever) gives float buffer for
186          * composite output only. This buffer can not be used for other
187          * passes obviously.
188          *
189          * We might try finding corresponding for pass buffer in render result
190          * (which is actually missing when rendering with Cycles, who only
191          * writes all the passes when the tile is finished) or use float
192          * buffer from image buffer as reference, which is easier to use and
193          * contains all the data we need anyway.
194          *                                              - sergey -
195          */
196         /* TODO(sergey): Need to check has_combined here? */
197         if (iuser->pass == 0) {
198                 RenderView *rv;
199                 const int view_id = BKE_scene_multiview_view_id_get(&scene->r, viewname);
200                 rv = RE_RenderViewGetById(rr, view_id);
201
202                 /* find current float rect for display, first case is after composite... still weak */
203                 if (rv->rectf)
204                         rectf = rv->rectf;
205                 else {
206                         if (rv->rect32) {
207                                 /* special case, currently only happens with sequencer rendering,
208                                  * which updates the whole frame, so we can only mark display buffer
209                                  * as invalid here (sergey)
210                                  */
211                                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
212                                 return;
213                         }
214                         else {
215                                 if (rr->renlay == NULL) return;
216                                 rectf = RE_RenderLayerGetPass(rr->renlay, RE_PASSNAME_COMBINED, viewname);
217                         }
218                 }
219                 if (rectf == NULL) return;
220
221                 rectf += 4 * (rr->rectx * ymin + xmin);
222                 linear_stride = rr->rectx;
223                 linear_offset_x = rxmin;
224                 linear_offset_y = rymin;
225         }
226         else {
227                 rectf = ibuf->rect_float;
228                 linear_stride = ibuf->x;
229                 linear_offset_x = 0;
230                 linear_offset_y = 0;
231         }
232
233         if (rr->do_exr_tile) {
234                 /* We don't support changing color management settings during rendering
235                  * when using Save Buffers option.
236                  */
237                 view_settings = &rj->view_settings;
238                 display_settings = &rj->display_settings;
239         }
240         else {
241                 view_settings = &scene->view_settings;
242                 display_settings = &scene->display_settings;
243         }
244
245         IMB_partial_display_buffer_update(ibuf, rectf, NULL,
246                                           linear_stride, linear_offset_x, linear_offset_y,
247                                           view_settings, display_settings,
248                                           rxmin, rymin, rxmin + xmax, rymin + ymax,
249                                           rr->do_exr_tile);
250 }
251
252 /* ****************************** render invoking ***************** */
253
254 /* set callbacks, exported to sequence render too.
255  * Only call in foreground (UI) renders. */
256
257 static void screen_render_scene_layer_set(wmOperator *op, Main *mainp, Scene **scene, SceneRenderLayer **srl)
258 {
259         /* single layer re-render */
260         if (RNA_struct_property_is_set(op->ptr, "scene")) {
261                 Scene *scn;
262                 char scene_name[MAX_ID_NAME - 2];
263
264                 RNA_string_get(op->ptr, "scene", scene_name);
265                 scn = (Scene *)BLI_findstring(&mainp->scene, scene_name, offsetof(ID, name) + 2);
266                 
267                 if (scn) {
268                         /* camera switch wont have updated */
269                         scn->r.cfra = (*scene)->r.cfra;
270                         BKE_scene_camera_switch_update(scn);
271
272                         *scene = scn;
273                 }
274         }
275
276         if (RNA_struct_property_is_set(op->ptr, "layer")) {
277                 SceneRenderLayer *rl;
278                 char rl_name[RE_MAXNAME];
279
280                 RNA_string_get(op->ptr, "layer", rl_name);
281                 rl = (SceneRenderLayer *)BLI_findstring(&(*scene)->r.layers, rl_name, offsetof(SceneRenderLayer, name));
282                 
283                 if (rl)
284                         *srl = rl;
285         }
286 }
287
288 /* executes blocking render */
289 static int screen_render_exec(bContext *C, wmOperator *op)
290 {
291         Scene *scene = CTX_data_scene(C);
292         SceneRenderLayer *srl = NULL;
293         Render *re;
294         Image *ima;
295         View3D *v3d = CTX_wm_view3d(C);
296         Main *mainp = CTX_data_main(C);
297         unsigned int lay_override;
298         const bool is_animation = RNA_boolean_get(op->ptr, "animation");
299         const bool is_write_still = RNA_boolean_get(op->ptr, "write_still");
300         struct Object *camera_override = v3d ? V3D_CAMERA_LOCAL(v3d) : NULL;
301
302         /* custom scene and single layer re-render */
303         screen_render_scene_layer_set(op, mainp, &scene, &srl);
304
305         if (!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
306                 BKE_report(op->reports, RPT_ERROR, "Cannot write a single file with an animation format selected");
307                 return OPERATOR_CANCELLED;
308         }
309
310         re = RE_NewRender(scene->id.name);
311         RE_SetDepsgraph(re, CTX_data_depsgraph(C));
312         lay_override = (v3d && v3d->lay != scene->lay) ? v3d->lay : 0;
313
314         G.is_break = false;
315         RE_test_break_cb(re, NULL, render_break);
316
317         ima = BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
318         BKE_image_signal(ima, NULL, IMA_SIGNAL_FREE);
319         BKE_image_backup_render(scene, ima, true);
320
321         /* cleanup sequencer caches before starting user triggered render.
322          * otherwise, invalidated cache entries can make their way into
323          * the output rendering. We can't put that into RE_BlenderFrame,
324          * since sequence rendering can call that recursively... (peter) */
325         BKE_sequencer_cache_cleanup();
326
327         RE_SetReports(re, op->reports);
328
329         BLI_begin_threaded_malloc();
330         if (is_animation)
331                 RE_BlenderAnim(re, mainp, scene, camera_override, lay_override, scene->r.sfra, scene->r.efra, scene->r.frame_step);
332         else
333                 RE_BlenderFrame(re, mainp, scene, srl, camera_override, lay_override, scene->r.cfra, is_write_still);
334         BLI_end_threaded_malloc();
335
336         RE_SetReports(re, NULL);
337
338         // no redraw needed, we leave state as we entered it
339         ED_update_for_newframe(mainp, scene, 1);
340
341         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, scene);
342
343         return OPERATOR_FINISHED;
344 }
345
346 static void render_freejob(void *rjv)
347 {
348         RenderJob *rj = rjv;
349
350         BKE_color_managed_view_settings_free(&rj->view_settings);
351         MEM_freeN(rj);
352 }
353
354 /* str is IMA_MAX_RENDER_TEXT in size */
355 static void make_renderinfo_string(const RenderStats *rs,
356                                    const Scene *scene,
357                                    const bool v3d_override,
358                                    const char *error,
359                                    char *str)
360 {
361         char info_time_str[32]; // used to be extern to header_info.c
362         uintptr_t mem_in_use, mmap_in_use, peak_memory;
363         float megs_used_memory, mmap_used_memory, megs_peak_memory;
364         char *spos = str;
365
366         mem_in_use = MEM_get_memory_in_use();
367         mmap_in_use = MEM_get_mapped_memory_in_use();
368         peak_memory = MEM_get_peak_memory();
369
370         megs_used_memory = (mem_in_use - mmap_in_use) / (1024.0 * 1024.0);
371         mmap_used_memory = (mmap_in_use) / (1024.0 * 1024.0);
372         megs_peak_memory = (peak_memory) / (1024.0 * 1024.0);
373
374         /* local view */
375         if (rs->localview)
376                 spos += sprintf(spos, "%s | ", IFACE_("3D Local View"));
377         else if (v3d_override)
378                 spos += sprintf(spos, "%s | ", IFACE_("3D View"));
379
380         /* frame number */
381         spos += sprintf(spos, IFACE_("Frame:%d "), (scene->r.cfra));
382
383         /* previous and elapsed time */
384         BLI_timecode_string_from_time_simple(info_time_str, sizeof(info_time_str), rs->lastframetime);
385
386         if (rs->infostr && rs->infostr[0]) {
387                 if (rs->lastframetime != 0.0)
388                         spos += sprintf(spos, IFACE_("| Last:%s "), info_time_str);
389                 else
390                         spos += sprintf(spos, "| ");
391
392                 BLI_timecode_string_from_time_simple(info_time_str, sizeof(info_time_str), PIL_check_seconds_timer() - rs->starttime);
393         }
394         else
395                 spos += sprintf(spos, "| ");
396
397         spos += sprintf(spos, IFACE_("Time:%s "), info_time_str);
398
399         /* statistics */
400         if (rs->statstr) {
401                 if (rs->statstr[0]) {
402                         spos += sprintf(spos, "| %s ", rs->statstr);
403                 }
404         }
405         else {
406                 if (rs->totvert || rs->totface || rs->tothalo || rs->totstrand || rs->totlamp)
407                         spos += sprintf(spos, "| ");
408
409                 if (rs->totvert) spos += sprintf(spos, IFACE_("Ve:%d "), rs->totvert);
410                 if (rs->totface) spos += sprintf(spos, IFACE_("Fa:%d "), rs->totface);
411                 if (rs->tothalo) spos += sprintf(spos, IFACE_("Ha:%d "), rs->tothalo);
412                 if (rs->totstrand) spos += sprintf(spos, IFACE_("St:%d "), rs->totstrand);
413                 if (rs->totlamp) spos += sprintf(spos, IFACE_("La:%d "), rs->totlamp);
414
415                 if (rs->mem_peak == 0.0f)
416                         spos += sprintf(spos, IFACE_("| Mem:%.2fM (%.2fM, Peak %.2fM) "),
417                                         megs_used_memory, mmap_used_memory, megs_peak_memory);
418                 else
419                         spos += sprintf(spos, IFACE_("| Mem:%.2fM, Peak: %.2fM "), rs->mem_used, rs->mem_peak);
420
421                 if (rs->curfield)
422                         spos += sprintf(spos, IFACE_("Field %d "), rs->curfield);
423                 if (rs->curblur)
424                         spos += sprintf(spos, IFACE_("Blur %d "), rs->curblur);
425         }
426
427         /* full sample */
428         if (rs->curfsa)
429                 spos += sprintf(spos, IFACE_("| Full Sample %d "), rs->curfsa);
430         
431         /* extra info */
432         if (rs->infostr && rs->infostr[0]) {
433                 spos += sprintf(spos, "| %s ", rs->infostr);
434         }
435         else if (error && error[0]) {
436                 spos += sprintf(spos, "| %s ", error);
437         }
438
439         /* very weak... but 512 characters is quite safe */
440         if (spos >= str + IMA_MAX_RENDER_TEXT)
441                 if (G.debug & G_DEBUG)
442                         printf("WARNING! renderwin text beyond limit\n");
443
444 }
445
446 static void image_renderinfo_cb(void *rjv, RenderStats *rs)
447 {
448         RenderJob *rj = rjv;
449         RenderResult *rr;
450
451         rr = RE_AcquireResultRead(rj->re);
452
453         if (rr) {
454                 /* malloc OK here, stats_draw is not in tile threads */
455                 if (rr->text == NULL)
456                         rr->text = MEM_callocN(IMA_MAX_RENDER_TEXT, "rendertext");
457
458                 make_renderinfo_string(rs, rj->scene, rj->v3d_override,
459                                        rr->error, rr->text);
460         }
461
462         RE_ReleaseResult(rj->re);
463
464         /* make jobs timer to send notifier */
465         *(rj->do_update) = true;
466
467 }
468
469 static void render_progress_update(void *rjv, float progress)
470 {
471         RenderJob *rj = rjv;
472         
473         if (rj->progress && *rj->progress != progress) {
474                 *rj->progress = progress;
475
476                 /* make jobs timer to send notifier */
477                 *(rj->do_update) = true;
478         }
479 }
480
481 /* Not totally reliable, but works fine in most of cases and
482  * in worst case would just make it so extra color management
483  * for the whole render result is applied (which was already
484  * happening already).
485  */
486 static void render_image_update_pass_and_layer(RenderJob *rj, RenderResult *rr, ImageUser *iuser)
487 {
488         wmWindowManager *wm;
489         ScrArea *first_sa = NULL, *matched_sa = NULL;
490
491         /* image window, compo node users */
492         for (wm = rj->main->wm.first; wm && matched_sa == NULL; wm = wm->id.next) { /* only 1 wm */
493                 wmWindow *win;
494                 for (win = wm->windows.first; win && matched_sa == NULL; win = win->next) {
495                         const bScreen *screen = WM_window_get_active_screen(win);
496
497                         for (ScrArea *sa = screen->areabase.first; sa; sa = sa->next) {
498                                 if (sa->spacetype == SPACE_IMAGE) {
499                                         SpaceImage *sima = sa->spacedata.first;
500                                         // sa->spacedata might be empty when toggling fullscreen mode.
501                                         if (sima != NULL && sima->image == rj->image) {
502                                                 if (first_sa == NULL) {
503                                                         first_sa = sa;
504                                                 }
505                                                 if (sa == rj->sa) {
506                                                         matched_sa = sa;
507                                                         break;
508                                                 }
509                                         }
510                                 }
511                         }
512                 }
513         }
514
515         if (matched_sa == NULL) {
516                 matched_sa = first_sa;
517         }
518
519         if (matched_sa) {
520                 SpaceImage *sima = matched_sa->spacedata.first;
521                 RenderResult *main_rr = RE_AcquireResultRead(rj->re);
522
523                 /* TODO(sergey): is there faster way to get the layer index? */
524                 if (rr->renlay) {
525                         int layer = BLI_findstringindex(&main_rr->layers,
526                                                         (char *)rr->renlay->name,
527                                                         offsetof(RenderLayer, name));
528                         if (layer != rj->last_layer) {
529                                 sima->iuser.layer = layer;
530                                 rj->last_layer = layer;
531                         }
532                 }
533
534                 iuser->pass = sima->iuser.pass;
535                 iuser->layer = sima->iuser.layer;
536
537                 RE_ReleaseResult(rj->re);
538         }
539 }
540
541 static void image_rect_update(void *rjv, RenderResult *rr, volatile rcti *renrect)
542 {
543         RenderJob *rj = rjv;
544         Image *ima = rj->image;
545         ImBuf *ibuf;
546         void *lock;
547         const char *viewname = RE_GetActiveRenderView(rj->re);
548
549         /* only update if we are displaying the slot being rendered */
550         if (ima->render_slot != ima->last_render_slot) {
551                 rj->image_outdated = true;
552                 return;
553         }
554         else if (rj->image_outdated) {
555                 /* update entire render */
556                 rj->image_outdated = false;
557                 BKE_image_signal(ima, NULL, IMA_SIGNAL_COLORMANAGE);
558                 *(rj->do_update) = true;
559                 return;
560         }
561         
562         if (rr == NULL)
563                 return;
564         
565         /* update part of render */
566         render_image_update_pass_and_layer(rj, rr, &rj->iuser);
567         ibuf = BKE_image_acquire_ibuf(ima, &rj->iuser, &lock);
568         if (ibuf) {
569                 /* Don't waste time on CPU side color management if
570                  * image will be displayed using GLSL.
571                  *
572                  * Need to update rect if Save Buffers enabled because in
573                  * this case GLSL doesn't have original float buffer to
574                  * operate with.
575                  */
576                 if (rr->do_exr_tile ||
577                     !rj->supports_glsl_draw ||
578                     ibuf->channels == 1 ||
579                     U.image_draw_method != IMAGE_DRAW_METHOD_GLSL)
580                 {
581                         image_buffer_rect_update(rj, rr, ibuf, &rj->iuser, renrect, viewname);
582                 }
583                 
584                 /* make jobs timer to send notifier */
585                 *(rj->do_update) = true;
586         }
587         BKE_image_release_ibuf(ima, ibuf, lock);
588 }
589
590 static void current_scene_update(void *rjv, Scene *scene)
591 {
592         RenderJob *rj = rjv;
593         rj->current_scene = scene;
594         rj->iuser.scene = scene;
595 }
596
597 static void render_startjob(void *rjv, short *stop, short *do_update, float *progress)
598 {
599         RenderJob *rj = rjv;
600
601         rj->stop = stop;
602         rj->do_update = do_update;
603         rj->progress = progress;
604
605         RE_SetReports(rj->re, rj->reports);
606
607         if (rj->anim)
608                 RE_BlenderAnim(rj->re, rj->main, rj->scene, rj->camera_override, rj->lay_override, rj->scene->r.sfra, rj->scene->r.efra, rj->scene->r.frame_step);
609         else
610                 RE_BlenderFrame(rj->re, rj->main, rj->scene, rj->srl, rj->camera_override, rj->lay_override, rj->scene->r.cfra, rj->write_still);
611
612         RE_SetReports(rj->re, NULL);
613 }
614
615 static void render_image_restore_layer(RenderJob *rj)
616 {
617         wmWindowManager *wm;
618
619         /* image window, compo node users */
620         for (wm = rj->main->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
621                 wmWindow *win;
622                 for (win = wm->windows.first; win; win = win->next) {
623                         const bScreen *screen = WM_window_get_active_screen(win);
624
625                         for (ScrArea *sa = screen->areabase.first; sa; sa = sa->next) {
626                                 if (sa == rj->sa) {
627                                         if (sa->spacetype == SPACE_IMAGE) {
628                                                 SpaceImage *sima = sa->spacedata.first;
629                                                 sima->iuser.layer = rj->orig_layer;
630                                         }
631                                         return;
632                                 }
633                         }
634                 }
635         }
636 }
637
638 static void render_endjob(void *rjv)
639 {
640         RenderJob *rj = rjv;
641
642         /* this render may be used again by the sequencer without the active 'Render' where the callbacks
643          * would be re-assigned. assign dummy callbacks to avoid referencing freed renderjobs bug [#24508] */
644         RE_InitRenderCB(rj->re);
645
646         if (rj->main != G.main)
647                 BKE_main_free(rj->main);
648
649         /* else the frame will not update for the original value */
650         if (rj->anim && !(rj->scene->r.scemode & R_NO_FRAME_UPDATE)) {
651                 /* possible this fails of loading new file while rendering */
652                 if (G.main->wm.first) {
653                         ED_update_for_newframe(G.main, rj->scene, 1);
654                 }
655         }
656         
657         /* XXX above function sets all tags in nodes */
658         ntreeCompositClearTags(rj->scene->nodetree);
659         
660         /* potentially set by caller */
661         rj->scene->r.scemode &= ~R_NO_FRAME_UPDATE;
662         
663         if (rj->srl) {
664                 nodeUpdateID(rj->scene->nodetree, &rj->scene->id);
665                 WM_main_add_notifier(NC_NODE | NA_EDITED, rj->scene);
666         }
667
668         if (rj->sa) {
669                 render_image_restore_layer(rj);
670         }
671
672         /* XXX render stability hack */
673         G.is_rendering = false;
674         WM_main_add_notifier(NC_SCENE | ND_RENDER_RESULT, NULL);
675
676         /* Partial render result will always update display buffer
677          * for first render layer only. This is nice because you'll
678          * see render progress during rendering, but it ends up in
679          * wrong display buffer shown after rendering.
680          *
681          * The code below will mark display buffer as invalid after
682          * rendering in case multiple layers were rendered, which
683          * ensures display buffer matches render layer after
684          * rendering.
685          *
686          * Perhaps proper way would be to toggle active render
687          * layer in image editor and job, so we always display
688          * layer being currently rendered. But this is not so much
689          * trivial at this moment, especially because of external
690          * engine API, so lets use simple and robust way for now
691          *                                          - sergey -
692          */
693         if (rj->scene->r.layers.first != rj->scene->r.layers.last ||
694             rj->image_outdated)
695         {
696                 void *lock;
697                 Image *ima = rj->image;
698                 ImBuf *ibuf = BKE_image_acquire_ibuf(ima, &rj->iuser, &lock);
699
700                 if (ibuf)
701                         ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
702
703                 BKE_image_release_ibuf(ima, ibuf, lock);
704         }
705
706         /* Finally unlock the user interface (if it was locked). */
707         if (rj->interface_locked) {
708                 Scene *scene;
709
710                 /* Interface was locked, so window manager couldn't have been changed
711                  * and using one from Global will unlock exactly the same manager as
712                  * was locked before running the job.
713                  */
714                 WM_set_locked_interface(G.main->wm.first, false);
715
716                 /* We've freed all the derived caches before rendering, which is
717                  * effectively the same as if we re-loaded the file.
718                  *
719                  * So let's not try being smart here and just reset all updated
720                  * scene layers and use generic DAG_on_visible_update.
721                  */
722                 for (scene = G.main->scene.first; scene; scene = scene->id.next) {
723                         scene->lay_updated = 0;
724                 }
725
726                 DEG_on_visible_update(G.main, false);
727         }
728 }
729
730 /* called by render, check job 'stop' value or the global */
731 static int render_breakjob(void *rjv)
732 {
733         RenderJob *rj = rjv;
734
735         if (G.is_break)
736                 return 1;
737         if (rj->stop && *(rj->stop))
738                 return 1;
739         return 0;
740 }
741
742 /* for exec() when there is no render job
743  * note: this wont check for the escape key being pressed, but doing so isnt threadsafe */
744 static int render_break(void *UNUSED(rjv))
745 {
746         if (G.is_break)
747                 return 1;
748         return 0;
749 }
750
751 /* runs in thread, no cursor setting here works. careful with notifiers too (malloc conflicts) */
752 /* maybe need a way to get job send notifer? */
753 static void render_drawlock(void *rjv, int lock)
754 {
755         RenderJob *rj = rjv;
756
757         /* If interface is locked, renderer callback shall do nothing. */
758         if (!rj->interface_locked) {
759                 BKE_spacedata_draw_locks(lock);
760         }
761 }
762
763 /* catch esc */
764 static int screen_render_modal(bContext *C, wmOperator *op, const wmEvent *event)
765 {
766         Scene *scene = (Scene *) op->customdata;
767
768         /* no running blender, remove handler and pass through */
769         if (0 == WM_jobs_test(CTX_wm_manager(C), scene, WM_JOB_TYPE_RENDER)) {
770                 return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH;
771         }
772
773         /* running render */
774         switch (event->type) {
775                 case ESCKEY:
776                         return OPERATOR_RUNNING_MODAL;
777         }
778         return OPERATOR_PASS_THROUGH;
779 }
780
781 static void screen_render_cancel(bContext *C, wmOperator *op)
782 {
783         wmWindowManager *wm = CTX_wm_manager(C);
784         Scene *scene = (Scene *) op->customdata;
785
786         /* kill on cancel, because job is using op->reports */
787         WM_jobs_kill_type(wm, scene, WM_JOB_TYPE_RENDER);
788 }
789
790 static void clean_viewport_memory(Main *bmain, Scene *scene)
791 {
792         Object *object;
793         Scene *sce_iter;
794         Base *base;
795
796         for (object = bmain->object.first; object; object = object->id.next) {
797                 object->id.tag |= LIB_TAG_DOIT;
798         }
799
800         for (SETLOOPER(scene, sce_iter, base)) {
801                 if ((base->flag & BASE_VISIBLED) == 0) {
802                         continue;
803                 }
804                 if (RE_allow_render_generic_object(base->object)) {
805                         base->object->id.tag &= ~LIB_TAG_DOIT;
806                 }
807         }
808
809         for (SETLOOPER(scene, sce_iter, base)) {
810                 object = base->object;
811                 if ((object->id.tag & LIB_TAG_DOIT) == 0) {
812                         continue;
813                 }
814                 object->id.tag &= ~LIB_TAG_DOIT;
815
816                 BKE_object_free_derived_caches(object);
817         }
818 }
819
820 /* using context, starts job */
821 static int screen_render_invoke(bContext *C, wmOperator *op, const wmEvent *event)
822 {
823         /* new render clears all callbacks */
824         Main *mainp;
825         Scene *scene = CTX_data_scene(C);
826         SceneRenderLayer *srl = NULL;
827         Render *re;
828         wmJob *wm_job;
829         RenderJob *rj;
830         Image *ima;
831         int jobflag;
832         const bool is_animation = RNA_boolean_get(op->ptr, "animation");
833         const bool is_write_still = RNA_boolean_get(op->ptr, "write_still");
834         const bool use_viewport = RNA_boolean_get(op->ptr, "use_viewport");
835         View3D *v3d = use_viewport ? CTX_wm_view3d(C) : NULL;
836         struct Object *camera_override = v3d ? V3D_CAMERA_LOCAL(v3d) : NULL;
837         const char *name;
838         ScrArea *sa;
839         
840         /* only one render job at a time */
841         if (WM_jobs_test(CTX_wm_manager(C), scene, WM_JOB_TYPE_RENDER))
842                 return OPERATOR_CANCELLED;
843
844         if (RE_force_single_renderlayer(scene))
845                 WM_event_add_notifier(C, NC_SCENE | ND_RENDER_OPTIONS, NULL);
846
847         if (!RE_is_rendering_allowed(scene, camera_override, op->reports)) {
848                 return OPERATOR_CANCELLED;
849         }
850
851         if (!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
852                 BKE_report(op->reports, RPT_ERROR, "Cannot write a single file with an animation format selected");
853                 return OPERATOR_CANCELLED;
854         }
855         
856         /* stop all running jobs, except screen one. currently previews frustrate Render */
857         WM_jobs_kill_all_except(CTX_wm_manager(C), CTX_wm_screen(C));
858
859         /* get main */
860         if (G.debug_value == 101) {
861                 /* thread-safety experiment, copy main from the undo buffer */
862                 mainp = BKE_undo_get_main(&scene);
863         }
864         else
865                 mainp = CTX_data_main(C);
866
867         /* cancel animation playback */
868         if (ED_screen_animation_playing(CTX_wm_manager(C)))
869                 ED_screen_animation_play(C, 0, 0);
870         
871         /* handle UI stuff */
872         WM_cursor_wait(1);
873
874         /* flush sculpt and editmode changes */
875         ED_editors_flush_edits(C, true);
876
877         /* cleanup sequencer caches before starting user triggered render.
878          * otherwise, invalidated cache entries can make their way into
879          * the output rendering. We can't put that into RE_BlenderFrame,
880          * since sequence rendering can call that recursively... (peter) */
881         BKE_sequencer_cache_cleanup();
882
883         // store spare
884         // get view3d layer, local layer, make this nice api call to render
885         // store spare
886
887         /* ensure at least 1 area shows result */
888         sa = render_view_open(C, event->x, event->y, op->reports);
889
890         jobflag = WM_JOB_EXCL_RENDER | WM_JOB_PRIORITY | WM_JOB_PROGRESS;
891         
892         /* custom scene and single layer re-render */
893         screen_render_scene_layer_set(op, mainp, &scene, &srl);
894
895         if (RNA_struct_property_is_set(op->ptr, "layer"))
896                 jobflag |= WM_JOB_SUSPEND;
897
898         /* job custom data */
899         rj = MEM_callocN(sizeof(RenderJob), "render job");
900         rj->main = mainp;
901         rj->scene = scene;
902         rj->current_scene = rj->scene;
903         rj->srl = srl;
904         rj->camera_override = camera_override;
905         rj->lay_override = 0;
906         rj->anim = is_animation;
907         rj->write_still = is_write_still && !is_animation;
908         rj->iuser.scene = scene;
909         rj->iuser.ok = 1;
910         rj->reports = op->reports;
911         rj->orig_layer = 0;
912         rj->last_layer = 0;
913         rj->sa = sa;
914         rj->supports_glsl_draw = IMB_colormanagement_support_glsl_draw(&scene->view_settings);
915
916         BKE_color_managed_display_settings_copy(&rj->display_settings, &scene->display_settings);
917         BKE_color_managed_view_settings_copy(&rj->view_settings, &scene->view_settings);
918
919         if (sa) {
920                 SpaceImage *sima = sa->spacedata.first;
921                 rj->orig_layer = sima->iuser.layer;
922         }
923
924         if (v3d) {
925                 if (scene->lay != v3d->lay) {
926                         rj->lay_override = v3d->lay;
927                         rj->v3d_override = true;
928                 }
929                 else if (camera_override && camera_override != scene->camera)
930                         rj->v3d_override = true;
931
932                 if (v3d->localvd)
933                         rj->lay_override |= v3d->localvd->lay;
934         }
935
936         /* Lock the user interface depending on render settings. */
937         if (scene->r.use_lock_interface) {
938                 WM_set_locked_interface(CTX_wm_manager(C), true);
939
940                 /* Set flag interface need to be unlocked.
941                  *
942                  * This is so because we don't have copy of render settings
943                  * accessible from render job and copy is needed in case
944                  * of non-locked rendering, so we wouldn't try to unlock
945                  * anything if option was initially unset but then was
946                  * enabled during rendering.
947                  */
948                 rj->interface_locked = true;
949
950                 /* Clean memory used by viewport? */
951                 clean_viewport_memory(rj->main, scene);
952         }
953
954         /* setup job */
955         if (RE_seq_render_active(scene, &scene->r)) name = "Sequence Render";
956         else name = "Render";
957
958         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, name, jobflag, WM_JOB_TYPE_RENDER);
959         WM_jobs_customdata_set(wm_job, rj, render_freejob);
960         WM_jobs_timer(wm_job, 0.2, NC_SCENE | ND_RENDER_RESULT, 0);
961         WM_jobs_callbacks(wm_job, render_startjob, NULL, NULL, render_endjob);
962
963         /* get a render result image, and make sure it is empty */
964         ima = BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
965         BKE_image_signal(ima, NULL, IMA_SIGNAL_FREE);
966         BKE_image_backup_render(rj->scene, ima, true);
967         rj->image = ima;
968
969         /* setup new render */
970         re = RE_NewRender(scene->id.name);
971         RE_test_break_cb(re, rj, render_breakjob);
972         RE_draw_lock_cb(re, rj, render_drawlock);
973         RE_display_update_cb(re, rj, image_rect_update);
974         RE_current_scene_update_cb(re, rj, current_scene_update);
975         RE_stats_draw_cb(re, rj, image_renderinfo_cb);
976         RE_progress_cb(re, rj, render_progress_update);
977         RE_SetDepsgraph(re, CTX_data_depsgraph(C));
978
979         rj->re = re;
980         G.is_break = false;
981
982         /* store actual owner of job, so modal operator could check for it,
983          * the reason of this is that active scene could change when rendering
984          * several layers from compositor [#31800]
985          */
986         op->customdata = scene;
987
988         WM_jobs_start(CTX_wm_manager(C), wm_job);
989
990         WM_cursor_wait(0);
991         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, scene);
992
993         /* we set G.is_rendering here already instead of only in the job, this ensure
994          * main loop or other scene updates are disabled in time, since they may
995          * have started before the job thread */
996         G.is_rendering = true;
997
998         /* add modal handler for ESC */
999         WM_event_add_modal_handler(C, op);
1000
1001         return OPERATOR_RUNNING_MODAL;
1002 }
1003
1004 /* contextual render, using current scene, view3d? */
1005 void RENDER_OT_render(wmOperatorType *ot)
1006 {
1007         PropertyRNA *prop;
1008
1009         /* identifiers */
1010         ot->name = "Render";
1011         ot->description = "Render active scene";
1012         ot->idname = "RENDER_OT_render";
1013
1014         /* api callbacks */
1015         ot->invoke = screen_render_invoke;
1016         ot->modal = screen_render_modal;
1017         ot->cancel = screen_render_cancel;
1018         ot->exec = screen_render_exec;
1019
1020         /*ot->poll = ED_operator_screenactive;*/ /* this isn't needed, causes failer in background mode */
1021
1022         RNA_def_boolean(ot->srna, "animation", 0, "Animation", "Render files from the animation range of this scene");
1023         RNA_def_boolean(ot->srna, "write_still", 0, "Write Image", "Save rendered the image to the output path (used only when animation is disabled)");
1024         RNA_def_boolean(ot->srna, "use_viewport", 0, "Use 3D Viewport", "When inside a 3D viewport, use layers and camera of the viewport");
1025         prop = RNA_def_string(ot->srna, "layer", NULL, RE_MAXNAME, "Render Layer", "Single render layer to re-render (used only when animation is disabled)");
1026         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1027         prop = RNA_def_string(ot->srna, "scene", NULL, MAX_ID_NAME - 2, "Scene", "Scene to render, current scene if not specified");
1028         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1029 }
1030
1031
1032 /* ************** preview for 3d viewport ***************** */
1033
1034 #define PR_UPDATE_VIEW                          1
1035 #define PR_UPDATE_RENDERSIZE            2
1036 #define PR_UPDATE_MATERIAL                      4
1037 #define PR_UPDATE_DATABASE                      8
1038
1039 typedef struct RenderPreview {
1040         /* from wmJob */
1041         void *owner;
1042         short *stop, *do_update;
1043         wmJob *job;
1044         
1045         Scene *scene;
1046         ScrArea *sa;
1047         ARegion *ar;
1048         View3D *v3d;
1049         RegionView3D *rv3d;
1050         Main *bmain;
1051         RenderEngine *engine;
1052         
1053         float viewmat[4][4];
1054
1055         int start_resolution_divider;
1056         int resolution_divider;
1057         bool has_freestyle;
1058 } RenderPreview;
1059
1060 static int render_view3d_disprect(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D *rv3d, rcti *disprect)
1061 {
1062         /* copied code from view3d_draw.c */
1063         rctf viewborder;
1064         int draw_border;
1065         
1066         if (rv3d->persp == RV3D_CAMOB)
1067                 draw_border = (scene->r.mode & R_BORDER) != 0;
1068         else
1069                 draw_border = (v3d->flag2 & V3D_RENDER_BORDER) != 0;
1070
1071         if (draw_border) {
1072                 if (rv3d->persp == RV3D_CAMOB) {
1073                         ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
1074                         
1075                         disprect->xmin = viewborder.xmin + scene->r.border.xmin * BLI_rctf_size_x(&viewborder);
1076                         disprect->ymin = viewborder.ymin + scene->r.border.ymin * BLI_rctf_size_y(&viewborder);
1077                         disprect->xmax = viewborder.xmin + scene->r.border.xmax * BLI_rctf_size_x(&viewborder);
1078                         disprect->ymax = viewborder.ymin + scene->r.border.ymax * BLI_rctf_size_y(&viewborder);
1079                 }
1080                 else {
1081                         disprect->xmin = v3d->render_border.xmin * ar->winx;
1082                         disprect->xmax = v3d->render_border.xmax * ar->winx;
1083                         disprect->ymin = v3d->render_border.ymin * ar->winy;
1084                         disprect->ymax = v3d->render_border.ymax * ar->winy;
1085                 }
1086                 
1087                 return 1;
1088         }
1089         
1090         BLI_rcti_init(disprect, 0, 0, 0, 0);
1091         return 0;
1092 }
1093
1094 /* returns true if OK  */
1095 static bool render_view3d_get_rects(ARegion *ar, View3D *v3d, RegionView3D *rv3d, rctf *viewplane, RenderEngine *engine,
1096                                     float *r_clipsta, float *r_clipend, float *r_pixsize, bool *r_ortho)
1097 {
1098         
1099         if (ar->winx < 4 || ar->winy < 4) return false;
1100         
1101         *r_ortho = ED_view3d_viewplane_get(v3d, rv3d, ar->winx, ar->winy, viewplane, r_clipsta, r_clipend, r_pixsize);
1102         
1103         engine->resolution_x = ar->winx;
1104         engine->resolution_y = ar->winy;
1105
1106         return true;
1107 }
1108
1109 static bool render_view3d_is_valid(RenderPreview *rp)
1110 {
1111         return (rp->rv3d->render_engine != NULL);
1112 }
1113
1114 /* called by renderer, checks job value */
1115 static int render_view3d_break(void *rpv)
1116 {
1117         RenderPreview *rp = rpv;
1118         
1119         if (G.is_break)
1120                 return 1;
1121         
1122         /* during render, rv3d->engine can get freed */
1123         if (render_view3d_is_valid(rp) == false) {
1124                 *rp->stop = 1;
1125         }
1126         
1127         return *(rp->stop);
1128 }
1129
1130 static void render_view3d_display_update(void *rpv, RenderResult *UNUSED(rr), volatile struct rcti *UNUSED(rect))
1131 {
1132         RenderPreview *rp = rpv;
1133         
1134         *(rp->do_update) = true;
1135 }
1136
1137 static void render_view3d_renderinfo_cb(void *rjp, RenderStats *rs)
1138 {
1139         RenderPreview *rp = rjp;
1140
1141         /* during render, rv3d->engine can get freed */
1142         if (rp->rv3d->render_engine == NULL) {
1143                 *rp->stop = 1;
1144         }
1145         else {
1146                 make_renderinfo_string(rs, rp->scene, false, NULL, rp->engine->text);
1147         
1148                 /* make jobs timer to send notifier */
1149                 *(rp->do_update) = true;
1150         }
1151 }
1152
1153 BLI_INLINE void rcti_scale_coords(rcti *scaled_rect, const rcti *rect,
1154                                   const float scale)
1155 {
1156         scaled_rect->xmin = rect->xmin * scale;
1157         scaled_rect->ymin = rect->ymin * scale;
1158         scaled_rect->xmax = rect->xmax * scale;
1159         scaled_rect->ymax = rect->ymax * scale;
1160 }
1161
1162 static void render_update_resolution(Render *re, const RenderPreview *rp,
1163                                      bool use_border, const rcti *clip_rect)
1164 {
1165         int winx = rp->ar->winx / rp->resolution_divider;
1166         int winy = rp->ar->winy / rp->resolution_divider;
1167         if (use_border) {
1168                 rcti scaled_cliprct;
1169                 rcti_scale_coords(&scaled_cliprct, clip_rect,
1170                                   1.0f / rp->resolution_divider);
1171                 RE_ChangeResolution(re, winx, winy, &scaled_cliprct);
1172         }
1173         else {
1174                 RE_ChangeResolution(re, winx, winy, NULL);
1175         }
1176
1177         if (rp->has_freestyle) {
1178                 if (rp->resolution_divider == 1) {
1179                         RE_ChangeModeFlag(re, R_EDGE_FRS, false);
1180                 }
1181                 else {
1182                         RE_ChangeModeFlag(re, R_EDGE_FRS, true);
1183                 }
1184         }
1185 }
1186
1187 static void render_view3d_startjob(void *customdata, short *stop, short *do_update, float *UNUSED(progress))
1188 {
1189         RenderPreview *rp = customdata;
1190         Render *re;
1191         RenderStats *rstats;
1192         rctf viewplane;
1193         rcti cliprct;
1194         float clipsta, clipend, pixsize;
1195         bool orth, restore = 0;
1196         char name[32];
1197         int update_flag;
1198         bool use_border;
1199         int ob_inst_update_flag = 0;
1200
1201         update_flag = rp->engine->job_update_flag;
1202         rp->engine->job_update_flag = 0;
1203
1204         //printf("ma %d res %d view %d db %d\n", update_flag & PR_UPDATE_MATERIAL, update_flag & PR_UPDATE_RENDERSIZE, update_flag & PR_UPDATE_VIEW, update_flag & PR_UPDATE_DATABASE);
1205
1206         G.is_break = false;
1207         
1208         if (false == render_view3d_get_rects(rp->ar, rp->v3d, rp->rv3d, &viewplane, rp->engine, &clipsta, &clipend, &pixsize, &orth))
1209                 return;
1210         
1211         rp->stop = stop;
1212         rp->do_update = do_update;
1213
1214         // printf("Enter previewrender\n");
1215         
1216         /* ok, are we rendering all over? */
1217         sprintf(name, "View3dPreview %p", (void *)rp->ar);
1218         re = rp->engine->re = RE_GetRender(name);
1219         
1220         /* set this always, rp is different for each job */
1221         RE_test_break_cb(re, rp, render_view3d_break);
1222         RE_display_update_cb(re, rp, render_view3d_display_update);
1223         RE_stats_draw_cb(re, rp, render_view3d_renderinfo_cb);
1224         
1225         rstats = RE_GetStats(re);
1226
1227         if (update_flag & PR_UPDATE_VIEW) {
1228                 Object *object;
1229                 rp->resolution_divider = rp->start_resolution_divider;
1230
1231                 /* Same as database_init_objects(), loop over all objects.
1232                  * We might consider de-duplicating the code between this two cases.
1233                  */
1234                 for (object = rp->bmain->object.first; object; object = object->id.next) {
1235                         float mat[4][4];
1236                         mul_m4_m4m4(mat, rp->viewmat, object->obmat);
1237                         invert_m4_m4(object->imat_ren, mat);
1238                 }
1239         }
1240
1241         use_border = render_view3d_disprect(rp->scene, rp->ar, rp->v3d,
1242                                             rp->rv3d, &cliprct);
1243
1244         if ((update_flag & (PR_UPDATE_RENDERSIZE | PR_UPDATE_DATABASE | PR_UPDATE_VIEW)) || rstats->convertdone == 0) {
1245                 RenderData rdata;
1246
1247                 /* no osa, blur, seq, layers, savebuffer etc for preview render */
1248                 rdata = rp->scene->r;
1249                 rdata.mode &= ~(R_OSA | R_MBLUR | R_BORDER | R_PANORAMA);
1250                 rdata.scemode &= ~(R_DOSEQ | R_DOCOMP | R_FREE_IMAGE | R_EXR_TILE_FILE | R_FULL_SAMPLE);
1251                 rdata.scemode |= R_VIEWPORT_PREVIEW;
1252
1253                 /* we do use layers, but only active */
1254                 rdata.scemode |= R_SINGLE_LAYER;
1255
1256                 /* initalize always */
1257                 if (use_border) {
1258                         rdata.mode |= R_BORDER;
1259                         RE_InitState(re, NULL, &rdata, NULL, rp->ar->winx, rp->ar->winy, &cliprct);
1260                 }
1261                 else
1262                         RE_InitState(re, NULL, &rdata, NULL, rp->ar->winx, rp->ar->winy, NULL);
1263         }
1264
1265         if (orth)
1266                 RE_SetOrtho(re, &viewplane, clipsta, clipend);
1267         else
1268                 RE_SetWindow(re, &viewplane, clipsta, clipend);
1269
1270         RE_SetPixelSize(re, pixsize);
1271         
1272         if ((update_flag & PR_UPDATE_DATABASE) || rstats->convertdone == 0) {
1273                 unsigned int lay = rp->scene->lay;
1274
1275                 /* allow localview render for objects with lights in normal layers */
1276                 if (rp->v3d->lay & 0xFF000000)
1277                         lay |= rp->v3d->lay;
1278                 else lay = rp->v3d->lay;
1279                 
1280                 RE_SetView(re, rp->viewmat);
1281
1282                 /* copying blender data while main thread is locked, to avoid crashes */
1283                 WM_job_main_thread_lock_acquire(rp->job);
1284                 RE_Database_Free(re);
1285                 RE_Database_FromScene(re, rp->bmain, rp->scene, lay, 0);                // 0= dont use camera view
1286                 WM_job_main_thread_lock_release(rp->job);
1287
1288                 /* do preprocessing like building raytree, shadows, volumes, SSS */
1289                 RE_Database_Preprocess(re);
1290
1291                 /* conversion not completed, need to do it again */
1292                 if (!rstats->convertdone) {
1293                         if (render_view3d_is_valid(rp)) {
1294                                 rp->engine->job_update_flag |= PR_UPDATE_DATABASE;
1295                         }
1296                 }
1297
1298                 // printf("dbase update\n");
1299         }
1300         else {
1301                 // printf("dbase rotate\n");
1302                 RE_DataBase_IncrementalView(re, rp->viewmat, 0);
1303                 restore = 1;
1304         }
1305
1306         RE_DataBase_ApplyWindow(re);
1307
1308         /* OK, can we enter render code? */
1309         if (rstats->convertdone) {
1310                 bool first_time = true;
1311
1312                 if (update_flag & PR_UPDATE_VIEW) {
1313                         ob_inst_update_flag |= RE_OBJECT_INSTANCES_UPDATE_VIEW;
1314                 }
1315
1316                 RE_updateRenderInstances(re, ob_inst_update_flag);
1317
1318                 for (;;) {
1319                         if (first_time == false) {
1320                                 if (restore)
1321                                         RE_DataBase_IncrementalView(re, rp->viewmat, 1);
1322
1323                                 rp->resolution_divider /= 2;
1324                                 *do_update = 1;
1325
1326                                 render_update_resolution(re, rp, use_border, &cliprct);
1327
1328                                 RE_DataBase_IncrementalView(re, rp->viewmat, 0);
1329                                 RE_DataBase_ApplyWindow(re);
1330                                 restore = 1;
1331                         }
1332                         else {
1333                                 render_update_resolution(re, rp, use_border, &cliprct);
1334                         }
1335
1336                         RE_TileProcessor(re);
1337
1338                         first_time = false;
1339
1340                         if (*stop || rp->resolution_divider == 1) {
1341                                 break;
1342                         }
1343                 }
1344
1345                 /* always rotate back */
1346                 if (restore)
1347                         RE_DataBase_IncrementalView(re, rp->viewmat, 1);
1348         }
1349 }
1350
1351 static void render_view3d_free(void *customdata)
1352 {
1353         RenderPreview *rp = customdata;
1354         
1355         MEM_freeN(rp);
1356 }
1357
1358 static bool render_view3d_flag_changed(RenderEngine *engine, const bContext *C)
1359 {
1360         RegionView3D *rv3d = CTX_wm_region_view3d(C);
1361         View3D *v3d = CTX_wm_view3d(C);
1362         ARegion *ar = CTX_wm_region(C);
1363         Scene *scene = CTX_data_scene(C);
1364         Render *re;
1365         rctf viewplane;
1366         rcti disprect;
1367         float clipsta, clipend;
1368         bool orth;
1369         int job_update_flag = 0;
1370         char name[32];
1371         
1372         /* ensure render engine exists */
1373         re = engine->re;
1374
1375         if (!re) {
1376                 sprintf(name, "View3dPreview %p", (void *)ar);
1377                 re = engine->re = RE_GetRender(name);
1378                 if (!re)
1379                         re = engine->re = RE_NewRender(name);
1380
1381                 engine->update_flag |= RE_ENGINE_UPDATE_DATABASE;
1382         }
1383
1384         /* check update_flag */
1385         if (engine->update_flag & RE_ENGINE_UPDATE_MA)
1386                 job_update_flag |= PR_UPDATE_MATERIAL;
1387         
1388         if (engine->update_flag & RE_ENGINE_UPDATE_OTHER)
1389                 job_update_flag |= PR_UPDATE_MATERIAL;
1390         
1391         if (engine->update_flag & RE_ENGINE_UPDATE_DATABASE) {
1392                 job_update_flag |= PR_UPDATE_DATABASE;
1393
1394                 /* load editmesh */
1395                 if (scene->obedit)
1396                         ED_object_editmode_load(scene->obedit);
1397         }
1398         
1399         engine->update_flag = 0;
1400         
1401         /* check if viewport changed */
1402         if (engine->last_winx != ar->winx || engine->last_winy != ar->winy) {
1403                 engine->last_winx = ar->winx;
1404                 engine->last_winy = ar->winy;
1405                 job_update_flag |= PR_UPDATE_RENDERSIZE;
1406         }
1407
1408         if (compare_m4m4(engine->last_viewmat, rv3d->viewmat, 0.00001f) == 0) {
1409                 copy_m4_m4(engine->last_viewmat, rv3d->viewmat);
1410                 job_update_flag |= PR_UPDATE_VIEW;
1411         }
1412         
1413         render_view3d_get_rects(ar, v3d, rv3d, &viewplane, engine, &clipsta, &clipend, NULL, &orth);
1414         
1415         if (BLI_rctf_compare(&viewplane, &engine->last_viewplane, 0.00001f) == 0) {
1416                 engine->last_viewplane = viewplane;
1417                 job_update_flag |= PR_UPDATE_VIEW;
1418         }
1419         
1420         render_view3d_disprect(scene, ar, v3d, rv3d, &disprect);
1421         if (BLI_rcti_compare(&disprect, &engine->last_disprect) == 0) {
1422                 engine->last_disprect = disprect;
1423                 job_update_flag |= PR_UPDATE_RENDERSIZE;
1424         }
1425
1426         /* any changes? go ahead and rerender */
1427         if (job_update_flag) {
1428                 engine->job_update_flag |= job_update_flag;
1429                 return true;
1430         }
1431
1432         return false;
1433 }
1434
1435 static void render_view3d_do(RenderEngine *engine, const bContext *C)
1436 {
1437         wmJob *wm_job;
1438         RenderPreview *rp;
1439         Scene *scene = CTX_data_scene(C);
1440         ARegion *ar = CTX_wm_region(C);
1441         int width = ar->winx, height = ar->winy;
1442         int divider = 1;
1443         int resolution_threshold = scene->r.preview_start_resolution *
1444                                    scene->r.preview_start_resolution;
1445
1446         if (CTX_wm_window(C) == NULL)
1447                 return;
1448         if (!render_view3d_flag_changed(engine, C))
1449                 return;
1450
1451         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), CTX_wm_region(C), "Render Preview",
1452                              WM_JOB_EXCL_RENDER, WM_JOB_TYPE_RENDER_PREVIEW);
1453         rp = MEM_callocN(sizeof(RenderPreview), "render preview");
1454         rp->job = wm_job;
1455
1456         while (width * height > resolution_threshold) {
1457                 width = max_ii(1, width / 2);
1458                 height = max_ii(1, height / 2);
1459                 divider *= 2;
1460         }
1461
1462         /* customdata for preview thread */
1463         rp->scene = scene;
1464         rp->engine = engine;
1465         rp->sa = CTX_wm_area(C);
1466         rp->ar = CTX_wm_region(C);
1467         rp->v3d = rp->sa->spacedata.first;
1468         rp->rv3d = CTX_wm_region_view3d(C);
1469         rp->bmain = CTX_data_main(C);
1470         rp->resolution_divider = divider;
1471         rp->start_resolution_divider = divider;
1472         rp->has_freestyle = (scene->r.mode & R_EDGE_FRS) != 0;
1473         copy_m4_m4(rp->viewmat, rp->rv3d->viewmat);
1474         
1475         /* clear info text */
1476         engine->text[0] = '\0';
1477         
1478         /* setup job */
1479         WM_jobs_customdata_set(wm_job, rp, render_view3d_free);
1480         WM_jobs_timer(wm_job, 0.1, NC_SPACE | ND_SPACE_VIEW3D, NC_SPACE | ND_SPACE_VIEW3D);
1481         WM_jobs_callbacks(wm_job, render_view3d_startjob, NULL, NULL, NULL);
1482         
1483         WM_jobs_start(CTX_wm_manager(C), wm_job);
1484         
1485         engine->flag &= ~RE_ENGINE_DO_UPDATE;
1486 }
1487
1488 /* callback for render engine, on changes */
1489 void render_view3d_update(RenderEngine *engine, const bContext *C)
1490 {       
1491         /* this shouldn't be needed and causes too many database rebuilds, but we
1492          * aren't actually tracking updates for all relevant datablocks so this is
1493          * a catch-all for updates */
1494         engine->update_flag |= RE_ENGINE_UPDATE_DATABASE;
1495
1496         render_view3d_do(engine, C);
1497 }
1498
1499 void render_view3d_draw(RenderEngine *engine, const bContext *C)
1500 {
1501         Render *re = engine->re;
1502         RenderResult rres;
1503         char name[32];
1504         
1505         render_view3d_do(engine, C);
1506         
1507         if (re == NULL) {
1508                 sprintf(name, "View3dPreview %p", (void *)CTX_wm_region(C));
1509                 re = RE_GetRender(name);
1510         
1511                 if (re == NULL) return;
1512         }
1513         
1514         /* Viewport render preview doesn't support multiview, view hardcoded to 0 */
1515         RE_AcquireResultImage(re, &rres, 0);
1516         
1517         if (rres.rectf) {
1518                 RegionView3D *rv3d = CTX_wm_region_view3d(C);
1519                 View3D *v3d = CTX_wm_view3d(C);
1520                 Scene *scene = CTX_data_scene(C);
1521                 ARegion *ar = CTX_wm_region(C);
1522                 bool force_fallback = false;
1523                 bool need_fallback = true;
1524                 float dither = scene->r.dither_intensity;
1525                 float scale_x, scale_y;
1526                 rcti clip_rect;
1527                 int xof, yof;
1528
1529                 if (render_view3d_disprect(scene, ar, v3d, rv3d, &clip_rect)) {
1530                         scale_x = (float) BLI_rcti_size_x(&clip_rect) / rres.rectx;
1531                         scale_y = (float) BLI_rcti_size_y(&clip_rect) / rres.recty;
1532                         xof = clip_rect.xmin;
1533                         yof = clip_rect.ymin;
1534                 }
1535                 else {
1536                         scale_x = (float) ar->winx / rres.rectx;
1537                         scale_y = (float) ar->winy / rres.recty;
1538                         xof = rres.xof;
1539                         yof = rres.yof;
1540                 }
1541
1542                 /* If user decided not to use GLSL, fallback to glaDrawPixelsAuto */
1543                 force_fallback |= (U.image_draw_method != IMAGE_DRAW_METHOD_GLSL);
1544
1545                 /* Try using GLSL display transform. */
1546                 if (force_fallback == false) {
1547                         if (IMB_colormanagement_setup_glsl_draw(&scene->view_settings, &scene->display_settings, dither, true)) {
1548                                 glEnable(GL_BLEND);
1549                                 IMMDrawPixelsTexState state = immDrawPixelsTexSetup(GPU_SHADER_2D_IMAGE_COLOR);
1550                                 immDrawPixelsTex(&state, xof, yof, rres.rectx, rres.recty,
1551                                                  GL_RGBA, GL_FLOAT, GL_NEAREST, rres.rectf,
1552                                                  scale_x, scale_y, NULL);;
1553                                 glDisable(GL_BLEND);
1554
1555                                 IMB_colormanagement_finish_glsl_draw();
1556                                 need_fallback = false;
1557                         }
1558                 }
1559
1560                 /* If GLSL failed, use old-school CPU-based transform. */
1561                 if (need_fallback) {
1562                         unsigned char *display_buffer = MEM_mallocN(4 * rres.rectx * rres.recty * sizeof(char),
1563                                                                     "render_view3d_draw");
1564
1565                         IMB_colormanagement_buffer_make_display_space(rres.rectf, display_buffer, rres.rectx, rres.recty,
1566                                                                       4, dither, &scene->view_settings, &scene->display_settings);
1567
1568                         glEnable(GL_BLEND);
1569                         IMMDrawPixelsTexState state = immDrawPixelsTexSetup(GPU_SHADER_2D_IMAGE_COLOR);
1570                         immDrawPixelsTex(&state, xof, yof, rres.rectx, rres.recty,
1571                                          GL_RGBA, GL_UNSIGNED_BYTE,
1572                                          GL_NEAREST, display_buffer,
1573                                          scale_x, scale_y, NULL);
1574                         glDisable(GL_BLEND);
1575
1576                         MEM_freeN(display_buffer);
1577                 }
1578         }
1579
1580         RE_ReleaseResultImage(re);
1581 }
1582
1583 void ED_viewport_render_kill_jobs(wmWindowManager *wm,
1584                                   Main *bmain,
1585                                   bool free_database)
1586 {
1587         bScreen *sc;
1588         ScrArea *sa;
1589         ARegion *ar;
1590
1591         if (!wm)
1592                 return;
1593
1594         /* kill all actively running jobs */
1595         WM_jobs_kill(wm, NULL, render_view3d_startjob);
1596
1597         /* loop over 3D view render engines */
1598         for (sc = bmain->screen.first; sc; sc = sc->id.next) {
1599                 for (sa = sc->areabase.first; sa; sa = sa->next) {
1600                         if (sa->spacetype != SPACE_VIEW3D)
1601                                 continue;
1602                         
1603                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
1604                                 RegionView3D *rv3d;
1605                                 
1606                                 if (ar->regiontype != RGN_TYPE_WINDOW)
1607                                         continue;
1608                                 
1609                                 rv3d = ar->regiondata;
1610
1611                                 if (rv3d->render_engine) {
1612                                         /* free render database now before we change data, because
1613                                          * RE_Database_Free will also loop over blender data */
1614                                         if (free_database) {
1615                                                 char name[32];
1616                                                 Render *re;
1617
1618                                                 sprintf(name, "View3dPreview %p", (void *)ar);
1619                                                 re = RE_GetRender(name);
1620
1621                                                 if (re)
1622                                                         RE_Database_Free(re);
1623
1624                                                 /* tag render engine to update entire database */
1625                                                 rv3d->render_engine->update_flag |= RE_ENGINE_UPDATE_DATABASE;
1626                                         }
1627                                         else {
1628                                                 /* quick shader update */
1629                                                 rv3d->render_engine->update_flag |= RE_ENGINE_UPDATE_MA;
1630                                         }
1631                                 }
1632                         }
1633                 }
1634         }
1635 }
1636
1637 Scene *ED_render_job_get_scene(const bContext *C)
1638 {
1639         wmWindowManager *wm = CTX_wm_manager(C);
1640         RenderJob *rj = (RenderJob *)WM_jobs_customdata_from_type(wm, WM_JOB_TYPE_RENDER);
1641         
1642         if (rj)
1643                 return rj->scene;
1644         
1645         return NULL;
1646 }
1647
1648 Scene *ED_render_job_get_current_scene(const bContext *C)
1649 {
1650         wmWindowManager *wm = CTX_wm_manager(C);
1651         RenderJob *rj = (RenderJob *)WM_jobs_customdata_from_type(wm, WM_JOB_TYPE_RENDER);
1652         if (rj) {
1653                 return rj->current_scene;
1654         }
1655         return NULL;
1656 }
1657
1658 /* Motion blur curve preset */
1659
1660 static int render_shutter_curve_preset_exec(bContext *C, wmOperator *op)
1661 {
1662         Scene *scene = CTX_data_scene(C);
1663         CurveMapping *mblur_shutter_curve = &scene->r.mblur_shutter_curve;
1664         CurveMap *cm = mblur_shutter_curve->cm;
1665         int preset = RNA_enum_get(op->ptr, "shape");
1666
1667         cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
1668         mblur_shutter_curve->preset = preset;
1669         curvemap_reset(cm,
1670                        &mblur_shutter_curve->clipr,
1671                        mblur_shutter_curve->preset,
1672                        CURVEMAP_SLOPE_POS_NEG);
1673         curvemapping_changed(mblur_shutter_curve, false);
1674
1675         return OPERATOR_FINISHED;
1676 }
1677
1678 void RENDER_OT_shutter_curve_preset(wmOperatorType *ot)
1679 {
1680         PropertyRNA *prop;
1681         static EnumPropertyItem prop_shape_items[] = {
1682                 {CURVE_PRESET_SHARP, "SHARP", 0, "Sharp", ""},
1683                 {CURVE_PRESET_SMOOTH, "SMOOTH", 0, "Smooth", ""},
1684                 {CURVE_PRESET_MAX, "MAX", 0, "Max", ""},
1685                 {CURVE_PRESET_LINE, "LINE", 0, "Line", ""},
1686                 {CURVE_PRESET_ROUND, "ROUND", 0, "Round", ""},
1687                 {CURVE_PRESET_ROOT, "ROOT", 0, "Root", ""},
1688                 {0, NULL, 0, NULL, NULL}};
1689
1690         ot->name = "Shutter Curve Preset";
1691         ot->description = "Set shutter curve";
1692         ot->idname = "RENDER_OT_shutter_curve_preset";
1693
1694         ot->exec = render_shutter_curve_preset_exec;
1695
1696         prop = RNA_def_enum(ot->srna, "shape", prop_shape_items, CURVE_PRESET_SMOOTH, "Mode", "");
1697         RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_CURVE); /* Abusing id_curve :/ */
1698 }