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