Bugfix #27519
[blender.git] / source / blender / editors / render / render_internal.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2008 Blender Foundation.
21  * All rights reserved.
22  *
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/render/render_internal.c
28  *  \ingroup edrend
29  */
30
31
32 #include <math.h>
33 #include <string.h>
34 #include <stddef.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_blenlib.h"
39 #include "BLI_math.h"
40 #include "BLI_threads.h"
41 #include "BLI_rand.h"
42 #include "BLI_utildefines.h"
43
44 #include "DNA_scene_types.h"
45
46 #include "BKE_blender.h"
47 #include "BKE_context.h"
48 #include "BKE_global.h"
49 #include "BKE_image.h"
50 #include "BKE_library.h"
51 #include "BKE_main.h"
52 #include "BKE_node.h"
53 #include "BKE_multires.h"
54 #include "BKE_report.h"
55 #include "BKE_sequencer.h"
56 #include "BKE_screen.h"
57 #include "BKE_scene.h"
58
59 #include "WM_api.h"
60 #include "WM_types.h"
61
62 #include "ED_screen.h"
63 #include "ED_object.h"
64
65 #include "RE_pipeline.h"
66 #include "IMB_imbuf.h"
67 #include "IMB_imbuf_types.h"
68
69 #include "RNA_access.h"
70 #include "RNA_define.h"
71
72 #include "wm_window.h"
73
74 #include "render_intern.h"
75
76 /* Render Callbacks */
77
78 /* called inside thread! */
79 void image_buffer_rect_update(Scene *scene, RenderResult *rr, ImBuf *ibuf, volatile rcti *renrect)
80 {
81         float x1, y1, *rectf= NULL;
82         int ymin, ymax, xmin, xmax;
83         int rymin, rxmin, do_color_management;
84         char *rectc;
85
86         /* if renrect argument, we only refresh scanlines */
87         if(renrect) {
88                 /* if ymax==recty, rendering of layer is ready, we should not draw, other things happen... */
89                 if(rr->renlay==NULL || renrect->ymax>=rr->recty)
90                         return;
91
92                 /* xmin here is first subrect x coord, xmax defines subrect width */
93                 xmin = renrect->xmin + rr->crop;
94                 xmax = renrect->xmax - xmin + rr->crop;
95                 if(xmax<2)
96                         return;
97
98                 ymin= renrect->ymin + rr->crop;
99                 ymax= renrect->ymax - ymin + rr->crop;
100                 if(ymax<2)
101                         return;
102                 renrect->ymin= renrect->ymax;
103
104         }
105         else {
106                 xmin = ymin = rr->crop;
107                 xmax = rr->rectx - 2*rr->crop;
108                 ymax = rr->recty - 2*rr->crop;
109         }
110
111         /* xmin ymin is in tile coords. transform to ibuf */
112         rxmin= rr->tilerect.xmin + xmin;
113         if(rxmin >= ibuf->x) return;
114         rymin= rr->tilerect.ymin + ymin;
115         if(rymin >= ibuf->y) return;
116
117         if(rxmin + xmax > ibuf->x)
118                 xmax= ibuf->x - rxmin;
119         if(rymin + ymax > ibuf->y)
120                 ymax= ibuf->y - rymin;
121
122         if(xmax < 1 || ymax < 1) return;
123
124         /* find current float rect for display, first case is after composit... still weak */
125         if(rr->rectf)
126                 rectf= rr->rectf;
127         else {
128                 if(rr->rect32)
129                         return;
130                 else {
131                         if(rr->renlay==NULL || rr->renlay->rectf==NULL) return;
132                         rectf= rr->renlay->rectf;
133                 }
134         }
135         if(rectf==NULL) return;
136
137         if(ibuf->rect==NULL)
138                 imb_addrectImBuf(ibuf);
139         
140         rectf+= 4*(rr->rectx*ymin + xmin);
141         rectc= (char *)(ibuf->rect + ibuf->x*rymin + rxmin);
142
143         do_color_management = (scene && (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT));
144         
145         /* XXX make nice consistent functions for this */
146         for(y1= 0; y1<ymax; y1++) {
147                 float *rf= rectf;
148                 float srgb[3];
149                 char *rc= rectc;
150                 const float dither = ibuf->dither / 255.0f;
151
152                 /* XXX temp. because crop offset */
153                 if(rectc >= (char *)(ibuf->rect)) {
154                         for(x1= 0; x1<xmax; x1++, rf += 4, rc+=4) {
155                                 /* color management */
156                                 if(do_color_management) {
157                                         srgb[0]= linearrgb_to_srgb(rf[0]);
158                                         srgb[1]= linearrgb_to_srgb(rf[1]);
159                                         srgb[2]= linearrgb_to_srgb(rf[2]);
160                                 }
161                                 else {
162                                         copy_v3_v3(srgb, rf);
163                                 }
164
165                                 /* dither */
166                                 if(dither != 0.0f) {
167                                         const float d = (BLI_frand()-0.5f)*dither;
168
169                                         srgb[0] += d;
170                                         srgb[1] += d;
171                                         srgb[2] += d;
172                                 }
173
174                                 /* write */
175                                 rc[0]= FTOCHAR(srgb[0]);
176                                 rc[1]= FTOCHAR(srgb[1]);
177                                 rc[2]= FTOCHAR(srgb[2]);
178                                 rc[3]= FTOCHAR(rf[3]);
179                         }
180                 }
181
182                 rectf += 4*rr->rectx;
183                 rectc += 4*ibuf->x;
184         }
185 }
186
187 /* ****************************** render invoking ***************** */
188
189 /* set callbacks, exported to sequence render too.
190  Only call in foreground (UI) renders. */
191
192 static void render_error_reports(void *reports, const char *str)
193 {
194         BKE_report(reports, RPT_ERROR, str);
195 }
196
197 /* executes blocking render */
198 static int screen_render_exec(bContext *C, wmOperator *op)
199 {
200         Scene *scene= CTX_data_scene(C);
201         Render *re= RE_NewRender(scene->id.name);
202         Image *ima;
203         View3D *v3d= CTX_wm_view3d(C);
204         Main *mainp= CTX_data_main(C);
205         unsigned int lay= (v3d)? v3d->lay: scene->lay;
206         const short is_animation= RNA_boolean_get(op->ptr, "animation");
207         const short is_write_still= RNA_boolean_get(op->ptr, "write_still");
208         struct Object *camera_override= v3d ? V3D_CAMERA_LOCAL(v3d) : NULL;
209
210         if(!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.imtype)) {
211                 BKE_report(op->reports, RPT_ERROR, "Can't write a single file with an animation format selected.");
212                 return OPERATOR_CANCELLED;
213         }
214
215         G.afbreek= 0;
216         RE_test_break_cb(re, NULL, (int (*)(void *)) blender_test_break);
217         RE_error_cb(re, op->reports, render_error_reports);
218
219         ima= BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
220         BKE_image_signal(ima, NULL, IMA_SIGNAL_FREE);
221         BKE_image_backup_render(scene, ima);
222
223         /* cleanup sequencer caches before starting user triggered render.
224            otherwise, invalidated cache entries can make their way into
225            the output rendering. We can't put that into RE_BlenderFrame,
226            since sequence rendering can call that recursively... (peter) */
227         seq_stripelem_cache_cleanup();
228
229         if(is_animation)
230                 RE_BlenderAnim(re, mainp, scene, camera_override, lay, scene->r.sfra, scene->r.efra, scene->r.frame_step, op->reports);
231         else
232                 RE_BlenderFrame(re, mainp, scene, NULL, camera_override, lay, scene->r.cfra, is_write_still);
233
234         // no redraw needed, we leave state as we entered it
235         ED_update_for_newframe(mainp, scene, CTX_wm_screen(C), 1);
236
237         WM_event_add_notifier(C, NC_SCENE|ND_RENDER_RESULT, scene);
238
239         return OPERATOR_FINISHED;
240 }
241
242 typedef struct RenderJob {
243         Main *main;
244         Scene *scene;
245         Render *re;
246         wmWindow *win;
247         SceneRenderLayer *srl;
248         struct Object *camera_override;
249         int lay;
250         short anim, write_still;
251         Image *image;
252         ImageUser iuser;
253         short *stop;
254         short *do_update;
255         float *progress;
256         ReportList *reports;
257 } RenderJob;
258
259 static void render_freejob(void *rjv)
260 {
261         RenderJob *rj= rjv;
262
263         MEM_freeN(rj);
264 }
265
266 /* str is IMA_MAX_RENDER_TEXT in size */
267 static void make_renderinfo_string(RenderStats *rs, Scene *scene, char *str)
268 {
269         char info_time_str[32]; // used to be extern to header_info.c
270         uintptr_t mem_in_use, mmap_in_use, peak_memory;
271         float megs_used_memory, mmap_used_memory, megs_peak_memory;
272         char *spos= str;
273
274         mem_in_use= MEM_get_memory_in_use();
275         mmap_in_use= MEM_get_mapped_memory_in_use();
276         peak_memory = MEM_get_peak_memory();
277
278         megs_used_memory= (mem_in_use-mmap_in_use)/(1024.0*1024.0);
279         mmap_used_memory= (mmap_in_use)/(1024.0*1024.0);
280         megs_peak_memory = (peak_memory)/(1024.0*1024.0);
281
282         if(scene->lay & 0xFF000000)
283                 spos+= sprintf(spos, "Localview | ");
284         else if(scene->r.scemode & R_SINGLE_LAYER)
285                 spos+= sprintf(spos, "Single Layer | ");
286
287         if(rs->statstr) {
288                 spos+= sprintf(spos, "%s ", rs->statstr);
289         }
290         else {
291                 spos+= sprintf(spos, "Fra:%d  Ve:%d Fa:%d ", (scene->r.cfra), rs->totvert, rs->totface);
292                 if(rs->tothalo) spos+= sprintf(spos, "Ha:%d ", rs->tothalo);
293                 if(rs->totstrand) spos+= sprintf(spos, "St:%d ", rs->totstrand);
294                 spos+= sprintf(spos, "La:%d Mem:%.2fM (%.2fM, peak %.2fM) ", rs->totlamp, megs_used_memory, mmap_used_memory, megs_peak_memory);
295
296                 if(rs->curfield)
297                         spos+= sprintf(spos, "Field %d ", rs->curfield);
298                 if(rs->curblur)
299                         spos+= sprintf(spos, "Blur %d ", rs->curblur);
300         }
301
302         BLI_timestr(rs->lastframetime, info_time_str);
303         spos+= sprintf(spos, "Time:%s ", info_time_str);
304
305         if(rs->curfsa)
306                 spos+= sprintf(spos, "| Full Sample %d ", rs->curfsa);
307         
308         if(rs->infostr && rs->infostr[0])
309                 spos+= sprintf(spos, "| %s ", rs->infostr);
310
311         /* very weak... but 512 characters is quite safe */
312         if(spos >= str+IMA_MAX_RENDER_TEXT)
313                 if (G.f & G_DEBUG)
314                         printf("WARNING! renderwin text beyond limit \n");
315
316 }
317
318 static void image_renderinfo_cb(void *rjv, RenderStats *rs)
319 {
320         RenderJob *rj= rjv;
321         RenderResult *rr;
322
323         rr= RE_AcquireResultRead(rj->re);
324
325         if(rr) {
326                 /* malloc OK here, stats_draw is not in tile threads */
327                 if(rr->text==NULL)
328                         rr->text= MEM_callocN(IMA_MAX_RENDER_TEXT, "rendertext");
329
330                 make_renderinfo_string(rs, rj->scene, rr->text);
331         }
332
333         RE_ReleaseResult(rj->re);
334
335         /* make jobs timer to send notifier */
336         *(rj->do_update)= 1;
337
338 }
339
340 static void render_progress_update(void *rjv, float progress)
341 {
342         RenderJob *rj= rjv;
343         
344         if(rj->progress)
345                 *rj->progress = progress;
346 }
347
348 static void image_rect_update(void *rjv, RenderResult *rr, volatile rcti *renrect)
349 {
350         RenderJob *rj= rjv;
351         Image *ima= rj->image;
352         ImBuf *ibuf;
353         void *lock;
354
355         /* only update if we are displaying the slot being rendered */
356         if(ima->render_slot != ima->last_render_slot)
357                 return;
358
359         ibuf= BKE_image_acquire_ibuf(ima, &rj->iuser, &lock);
360         if(ibuf) {
361                 image_buffer_rect_update(rj->scene, rr, ibuf, renrect);
362
363                 /* make jobs timer to send notifier */
364                 *(rj->do_update)= 1;
365         }
366         BKE_image_release_ibuf(ima, lock);
367 }
368
369 static void render_startjob(void *rjv, short *stop, short *do_update, float *progress)
370 {
371         RenderJob *rj= rjv;
372
373         rj->stop= stop;
374         rj->do_update= do_update;
375         rj->progress= progress;
376
377         if(rj->anim)
378                 RE_BlenderAnim(rj->re, rj->main, rj->scene, rj->camera_override, rj->lay, rj->scene->r.sfra, rj->scene->r.efra, rj->scene->r.frame_step, rj->reports);
379         else
380                 RE_BlenderFrame(rj->re, rj->main, rj->scene, rj->srl, rj->camera_override, rj->lay, rj->scene->r.cfra, rj->write_still);
381 }
382
383 static void render_endjob(void *rjv)
384 {
385         RenderJob *rj= rjv;     
386
387         /* this render may be used again by the sequencer without the active 'Render' where the callbacks
388          * would be re-assigned. assign dummy callbacks to avoid referencing freed renderjobs bug [#24508] */
389         RE_InitRenderCB(rj->re);
390
391         if(rj->main != G.main)
392                 free_main(rj->main);
393
394         /* else the frame will not update for the original value */
395         if(!(rj->scene->r.scemode & R_NO_FRAME_UPDATE))
396                 ED_update_for_newframe(G.main, rj->scene, rj->win->screen, 1);
397         
398         /* XXX above function sets all tags in nodes */
399         ntreeClearTags(rj->scene->nodetree);
400         
401         /* potentially set by caller */
402         rj->scene->r.scemode &= ~R_NO_FRAME_UPDATE;
403         
404         if(rj->srl) {
405                 NodeTagIDChanged(rj->scene->nodetree, &rj->scene->id);
406                 WM_main_add_notifier(NC_NODE|NA_EDITED, rj->scene);
407         }
408         
409         /* XXX render stability hack */
410         G.rendering = 0;
411         WM_main_add_notifier(NC_WINDOW, NULL);
412 }
413
414 /* called by render, check job 'stop' value or the global */
415 static int render_breakjob(void *rjv)
416 {
417         RenderJob *rj= rjv;
418
419         if(G.afbreek)
420                 return 1;
421         if(rj->stop && *(rj->stop))
422                 return 1;
423         return 0;
424 }
425
426 /* runs in thread, no cursor setting here works. careful with notifiers too (malloc conflicts) */
427 /* maybe need a way to get job send notifer? */
428 static void render_drawlock(void *UNUSED(rjv), int lock)
429 {
430         BKE_spacedata_draw_locks(lock);
431         
432 }
433
434 /* catch esc */
435 static int screen_render_modal(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
436 {
437         /* no running blender, remove handler and pass through */
438         if(0==WM_jobs_test(CTX_wm_manager(C), CTX_data_scene(C))) {
439                 return OPERATOR_FINISHED|OPERATOR_PASS_THROUGH;
440         }
441
442         /* running render */
443         switch (event->type) {
444                 case ESCKEY:
445                         return OPERATOR_RUNNING_MODAL;
446                         break;
447         }
448         return OPERATOR_PASS_THROUGH;
449 }
450
451 /* using context, starts job */
452 static int screen_render_invoke(bContext *C, wmOperator *op, wmEvent *event)
453 {
454         /* new render clears all callbacks */
455         Main *mainp;
456         Scene *scene= CTX_data_scene(C);
457         SceneRenderLayer *srl=NULL;
458         bScreen *screen= CTX_wm_screen(C);
459         View3D *v3d= CTX_wm_view3d(C);
460         Render *re;
461         wmJob *steve;
462         RenderJob *rj;
463         Image *ima;
464         int jobflag;
465         const short is_animation= RNA_boolean_get(op->ptr, "animation");
466         const short is_write_still= RNA_boolean_get(op->ptr, "write_still");
467         struct Object *camera_override= v3d ? V3D_CAMERA_LOCAL(v3d) : NULL;
468         
469         /* only one render job at a time */
470         if(WM_jobs_test(CTX_wm_manager(C), scene))
471                 return OPERATOR_CANCELLED;
472
473         if(!RE_is_rendering_allowed(scene, camera_override, op->reports, render_error_reports)) {
474                 return OPERATOR_CANCELLED;
475         }
476
477         if(!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.imtype)) {
478                 BKE_report(op->reports, RPT_ERROR, "Can't write a single file with an animation format selected.");
479                 return OPERATOR_CANCELLED;
480         }       
481         
482         /* stop all running jobs, currently previews frustrate Render */
483         WM_jobs_stop_all(CTX_wm_manager(C));
484
485         /* get main */
486         if(G.rt == 101) {
487                 /* thread-safety experiment, copy main from the undo buffer */
488                 mainp= BKE_undo_get_main(&scene);
489         }
490         else
491                 mainp= CTX_data_main(C);
492
493         /* cancel animation playback */
494         if (screen->animtimer)
495                 ED_screen_animation_play(C, 0, 0);
496         
497         /* handle UI stuff */
498         WM_cursor_wait(1);
499
500         /* flush multires changes (for sculpt) */
501         multires_force_render_update(CTX_data_active_object(C));
502
503         /* cleanup sequencer caches before starting user triggered render.
504            otherwise, invalidated cache entries can make their way into
505            the output rendering. We can't put that into RE_BlenderFrame,
506            since sequence rendering can call that recursively... (peter) */
507         seq_stripelem_cache_cleanup();
508
509         /* get editmode results */
510         ED_object_exit_editmode(C, 0);  /* 0 = does not exit editmode */
511
512         // store spare
513         // get view3d layer, local layer, make this nice api call to render
514         // store spare
515
516         /* ensure at least 1 area shows result */
517         render_view_open(C, event->x, event->y);
518
519         jobflag= WM_JOB_EXCL_RENDER|WM_JOB_PRIORITY|WM_JOB_PROGRESS;
520         
521         /* single layer re-render */
522         if(RNA_property_is_set(op->ptr, "layer")) {
523                 SceneRenderLayer *rl;
524                 Scene *scn;
525                 char scene_name[MAX_ID_NAME-2], rl_name[RE_MAXNAME];
526
527                 RNA_string_get(op->ptr, "layer", rl_name);
528                 RNA_string_get(op->ptr, "scene", scene_name);
529
530                 scn = (Scene *)BLI_findstring(&mainp->scene, scene_name, offsetof(ID, name) + 2);
531                 rl = (SceneRenderLayer *)BLI_findstring(&scene->r.layers, rl_name, offsetof(SceneRenderLayer, name));
532                 
533                 if (scn && rl) {
534                         /* camera switch wont have updated */
535                         scn->r.cfra= scene->r.cfra;
536                         scene_camera_switch_update(scn);
537
538                         scene = scn;
539                         srl = rl;
540                 }
541                 jobflag |= WM_JOB_SUSPEND;
542         }
543
544         /* job custom data */
545         rj= MEM_callocN(sizeof(RenderJob), "render job");
546         rj->main= mainp;
547         rj->scene= scene;
548         rj->win= CTX_wm_window(C);
549         rj->srl = srl;
550         rj->camera_override = camera_override;
551         rj->lay = (v3d)? v3d->lay: scene->lay;
552         rj->anim= is_animation;
553         rj->write_still= is_write_still && !is_animation;
554         rj->iuser.scene= scene;
555         rj->iuser.ok= 1;
556         rj->reports= op->reports;
557
558         /* setup job */
559         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, "Render", jobflag);
560         WM_jobs_customdata(steve, rj, render_freejob);
561         WM_jobs_timer(steve, 0.2, NC_SCENE|ND_RENDER_RESULT, 0);
562         WM_jobs_callbacks(steve, render_startjob, NULL, NULL, render_endjob);
563
564         /* get a render result image, and make sure it is empty */
565         ima= BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
566         BKE_image_signal(ima, NULL, IMA_SIGNAL_FREE);
567         BKE_image_backup_render(rj->scene, ima);
568         rj->image= ima;
569
570         /* setup new render */
571         re= RE_NewRender(scene->id.name);
572         RE_test_break_cb(re, rj, render_breakjob);
573         RE_draw_lock_cb(re, rj, render_drawlock);
574         RE_display_draw_cb(re, rj, image_rect_update);
575         RE_stats_draw_cb(re, rj, image_renderinfo_cb);
576         RE_progress_cb(re, rj, render_progress_update);
577
578         rj->re= re;
579         G.afbreek= 0;
580
581         RE_error_cb(re, op->reports, render_error_reports);
582
583         WM_jobs_start(CTX_wm_manager(C), steve);
584
585         WM_cursor_wait(0);
586         WM_event_add_notifier(C, NC_SCENE|ND_RENDER_RESULT, scene);
587
588         /* we set G.rendering here already instead of only in the job, this ensure
589            main loop or other scene updates are disabled in time, since they may
590            have started before the job thread */
591         G.rendering = 1;
592
593         /* add modal handler for ESC */
594         WM_event_add_modal_handler(C, op);
595
596         return OPERATOR_RUNNING_MODAL;
597 }
598
599
600 /* contextual render, using current scene, view3d? */
601 void RENDER_OT_render(wmOperatorType *ot)
602 {
603         /* identifiers */
604         ot->name= "Render";
605         ot->description= "Render active scene";
606         ot->idname= "RENDER_OT_render";
607
608         /* api callbacks */
609         ot->invoke= screen_render_invoke;
610         ot->modal= screen_render_modal;
611         ot->exec= screen_render_exec;
612
613         /*ot->poll= ED_operator_screenactive;*/ /* this isnt needed, causes failer in background mode */
614
615         RNA_def_boolean(ot->srna, "animation", 0, "Animation", "Render files from the animation range of this scene");
616         RNA_def_boolean(ot->srna, "write_still", 0, "Write Image", "Save rendered the image to the output path (used only when animation is disabled)");
617         RNA_def_string(ot->srna, "layer", "", RE_MAXNAME, "Render Layer", "Single render layer to re-render");
618         RNA_def_string(ot->srna, "scene", "", MAX_ID_NAME-2, "Scene", "Re-render single layer in this scene");
619 }
620