Cycles: svn merge -r37333:37694 https://svn.blender.org/svnroot/bf-blender/trunk
[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 /* executes blocking render */
193 static int screen_render_exec(bContext *C, wmOperator *op)
194 {
195         Scene *scene= CTX_data_scene(C);
196         Render *re= RE_NewRender(scene->id.name);
197         Image *ima;
198         View3D *v3d= CTX_wm_view3d(C);
199         Main *mainp= CTX_data_main(C);
200         unsigned int lay= (v3d)? v3d->lay: scene->lay;
201         const short is_animation= RNA_boolean_get(op->ptr, "animation");
202         const short is_write_still= RNA_boolean_get(op->ptr, "write_still");
203         struct Object *camera_override= v3d ? V3D_CAMERA_LOCAL(v3d) : NULL;
204
205         if(!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.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         G.afbreek= 0;
211         RE_test_break_cb(re, NULL, (int (*)(void *)) blender_test_break);
212
213         ima= BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
214         BKE_image_signal(ima, NULL, IMA_SIGNAL_FREE);
215         BKE_image_backup_render(scene, ima);
216
217         /* cleanup sequencer caches before starting user triggered render.
218            otherwise, invalidated cache entries can make their way into
219            the output rendering. We can't put that into RE_BlenderFrame,
220            since sequence rendering can call that recursively... (peter) */
221         seq_stripelem_cache_cleanup();
222
223         RE_SetReports(re, op->reports);
224
225         if(is_animation)
226                 RE_BlenderAnim(re, mainp, scene, camera_override, lay, scene->r.sfra, scene->r.efra, scene->r.frame_step);
227         else
228                 RE_BlenderFrame(re, mainp, scene, NULL, camera_override, lay, scene->r.cfra, is_write_still);
229
230         RE_SetReports(re, NULL);
231
232         // no redraw needed, we leave state as we entered it
233         ED_update_for_newframe(mainp, scene, CTX_wm_screen(C), 1);
234
235         WM_event_add_notifier(C, NC_SCENE|ND_RENDER_RESULT, scene);
236
237         return OPERATOR_FINISHED;
238 }
239
240 typedef struct RenderJob {
241         Main *main;
242         Scene *scene;
243         Render *re;
244         wmWindow *win;
245         SceneRenderLayer *srl;
246         struct Object *camera_override;
247         int lay;
248         short anim, write_still;
249         Image *image;
250         ImageUser iuser;
251         short *stop;
252         short *do_update;
253         float *progress;
254         ReportList *reports;
255 } RenderJob;
256
257 static void render_freejob(void *rjv)
258 {
259         RenderJob *rj= rjv;
260
261         MEM_freeN(rj);
262 }
263
264 /* str is IMA_MAX_RENDER_TEXT in size */
265 static void make_renderinfo_string(RenderStats *rs, Scene *scene, char *str)
266 {
267         char info_time_str[32]; // used to be extern to header_info.c
268         uintptr_t mem_in_use, mmap_in_use, peak_memory;
269         float megs_used_memory, mmap_used_memory, megs_peak_memory;
270         char *spos= str;
271
272         mem_in_use= MEM_get_memory_in_use();
273         mmap_in_use= MEM_get_mapped_memory_in_use();
274         peak_memory = MEM_get_peak_memory();
275
276         megs_used_memory= (mem_in_use-mmap_in_use)/(1024.0*1024.0);
277         mmap_used_memory= (mmap_in_use)/(1024.0*1024.0);
278         megs_peak_memory = (peak_memory)/(1024.0*1024.0);
279
280         if(scene->lay & 0xFF000000)
281                 spos+= sprintf(spos, "Localview | ");
282         else if(scene->r.scemode & R_SINGLE_LAYER)
283                 spos+= sprintf(spos, "Single Layer | ");
284
285         if(rs->statstr) {
286                 spos+= sprintf(spos, "%s ", rs->statstr);
287         }
288         else {
289                 spos+= sprintf(spos, "Fra:%d  Ve:%d Fa:%d ", (scene->r.cfra), rs->totvert, rs->totface);
290                 if(rs->tothalo) spos+= sprintf(spos, "Ha:%d ", rs->tothalo);
291                 if(rs->totstrand) spos+= sprintf(spos, "St:%d ", rs->totstrand);
292                 spos+= sprintf(spos, "La:%d Mem:%.2fM (%.2fM, peak %.2fM) ", rs->totlamp, megs_used_memory, mmap_used_memory, megs_peak_memory);
293
294                 if(rs->curfield)
295                         spos+= sprintf(spos, "Field %d ", rs->curfield);
296                 if(rs->curblur)
297                         spos+= sprintf(spos, "Blur %d ", rs->curblur);
298         }
299
300         BLI_timestr(rs->lastframetime, info_time_str);
301         spos+= sprintf(spos, "Time:%s ", info_time_str);
302
303         if(rs->curfsa)
304                 spos+= sprintf(spos, "| Full Sample %d ", rs->curfsa);
305         
306         if(rs->infostr && rs->infostr[0])
307                 spos+= sprintf(spos, "| %s ", rs->infostr);
308
309         /* very weak... but 512 characters is quite safe */
310         if(spos >= str+IMA_MAX_RENDER_TEXT)
311                 if (G.f & G_DEBUG)
312                         printf("WARNING! renderwin text beyond limit \n");
313
314 }
315
316 static void image_renderinfo_cb(void *rjv, RenderStats *rs)
317 {
318         RenderJob *rj= rjv;
319         RenderResult *rr;
320
321         rr= RE_AcquireResultRead(rj->re);
322
323         if(rr) {
324                 /* malloc OK here, stats_draw is not in tile threads */
325                 if(rr->text==NULL)
326                         rr->text= MEM_callocN(IMA_MAX_RENDER_TEXT, "rendertext");
327
328                 make_renderinfo_string(rs, rj->scene, rr->text);
329         }
330
331         RE_ReleaseResult(rj->re);
332
333         /* make jobs timer to send notifier */
334         *(rj->do_update)= 1;
335
336 }
337
338 static void render_progress_update(void *rjv, float progress)
339 {
340         RenderJob *rj= rjv;
341         
342         if(rj->progress)
343                 *rj->progress = progress;
344 }
345
346 static void image_rect_update(void *rjv, RenderResult *rr, volatile rcti *renrect)
347 {
348         RenderJob *rj= rjv;
349         Image *ima= rj->image;
350         ImBuf *ibuf;
351         void *lock;
352
353         /* only update if we are displaying the slot being rendered */
354         if(ima->render_slot != ima->last_render_slot)
355                 return;
356
357         ibuf= BKE_image_acquire_ibuf(ima, &rj->iuser, &lock);
358         if(ibuf) {
359                 image_buffer_rect_update(rj->scene, rr, ibuf, renrect);
360
361                 /* make jobs timer to send notifier */
362                 *(rj->do_update)= 1;
363         }
364         BKE_image_release_ibuf(ima, lock);
365 }
366
367 static void render_startjob(void *rjv, short *stop, short *do_update, float *progress)
368 {
369         RenderJob *rj= rjv;
370
371         rj->stop= stop;
372         rj->do_update= do_update;
373         rj->progress= progress;
374
375         RE_SetReports(rj->re, rj->reports);
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);
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         RE_SetReports(rj->re, NULL);
383 }
384
385 static void render_endjob(void *rjv)
386 {
387         RenderJob *rj= rjv;     
388
389         /* this render may be used again by the sequencer without the active 'Render' where the callbacks
390          * would be re-assigned. assign dummy callbacks to avoid referencing freed renderjobs bug [#24508] */
391         RE_InitRenderCB(rj->re);
392
393         if(rj->main != G.main)
394                 free_main(rj->main);
395
396         /* else the frame will not update for the original value */
397         if(!(rj->scene->r.scemode & R_NO_FRAME_UPDATE))
398                 ED_update_for_newframe(G.main, rj->scene, rj->win->screen, 1);
399         
400         /* XXX above function sets all tags in nodes */
401         ntreeClearTags(rj->scene->nodetree);
402         
403         /* potentially set by caller */
404         rj->scene->r.scemode &= ~R_NO_FRAME_UPDATE;
405         
406         if(rj->srl) {
407                 NodeTagIDChanged(rj->scene->nodetree, &rj->scene->id);
408                 WM_main_add_notifier(NC_NODE|NA_EDITED, rj->scene);
409         }
410         
411         /* XXX render stability hack */
412         G.rendering = 0;
413         WM_main_add_notifier(NC_WINDOW, NULL);
414 }
415
416 /* called by render, check job 'stop' value or the global */
417 static int render_breakjob(void *rjv)
418 {
419         RenderJob *rj= rjv;
420
421         if(G.afbreek)
422                 return 1;
423         if(rj->stop && *(rj->stop))
424                 return 1;
425         return 0;
426 }
427
428 /* runs in thread, no cursor setting here works. careful with notifiers too (malloc conflicts) */
429 /* maybe need a way to get job send notifer? */
430 static void render_drawlock(void *UNUSED(rjv), int lock)
431 {
432         BKE_spacedata_draw_locks(lock);
433         
434 }
435
436 /* catch esc */
437 static int screen_render_modal(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
438 {
439         /* no running blender, remove handler and pass through */
440         if(0==WM_jobs_test(CTX_wm_manager(C), CTX_data_scene(C))) {
441                 return OPERATOR_FINISHED|OPERATOR_PASS_THROUGH;
442         }
443
444         /* running render */
445         switch (event->type) {
446                 case ESCKEY:
447                         return OPERATOR_RUNNING_MODAL;
448                         break;
449         }
450         return OPERATOR_PASS_THROUGH;
451 }
452
453 /* using context, starts job */
454 static int screen_render_invoke(bContext *C, wmOperator *op, wmEvent *event)
455 {
456         /* new render clears all callbacks */
457         Main *mainp;
458         Scene *scene= CTX_data_scene(C);
459         SceneRenderLayer *srl=NULL;
460         bScreen *screen= CTX_wm_screen(C);
461         View3D *v3d= CTX_wm_view3d(C);
462         Render *re;
463         wmJob *steve;
464         RenderJob *rj;
465         Image *ima;
466         int jobflag;
467         const short is_animation= RNA_boolean_get(op->ptr, "animation");
468         const short is_write_still= RNA_boolean_get(op->ptr, "write_still");
469         struct Object *camera_override= v3d ? V3D_CAMERA_LOCAL(v3d) : NULL;
470         
471         /* only one render job at a time */
472         if(WM_jobs_test(CTX_wm_manager(C), scene))
473                 return OPERATOR_CANCELLED;
474
475         if(!RE_is_rendering_allowed(scene, camera_override, op->reports)) {
476                 return OPERATOR_CANCELLED;
477         }
478
479         if(!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.imtype)) {
480                 BKE_report(op->reports, RPT_ERROR, "Can't write a single file with an animation format selected.");
481                 return OPERATOR_CANCELLED;
482         }       
483         
484         /* stop all running jobs, currently previews frustrate Render */
485         WM_jobs_stop_all(CTX_wm_manager(C));
486
487         /* get main */
488         if(G.rt == 101) {
489                 /* thread-safety experiment, copy main from the undo buffer */
490                 mainp= BKE_undo_get_main(&scene);
491         }
492         else
493                 mainp= CTX_data_main(C);
494
495         /* cancel animation playback */
496         if (screen->animtimer)
497                 ED_screen_animation_play(C, 0, 0);
498         
499         /* handle UI stuff */
500         WM_cursor_wait(1);
501
502         /* flush multires changes (for sculpt) */
503         multires_force_render_update(CTX_data_active_object(C));
504
505         /* cleanup sequencer caches before starting user triggered render.
506            otherwise, invalidated cache entries can make their way into
507            the output rendering. We can't put that into RE_BlenderFrame,
508            since sequence rendering can call that recursively... (peter) */
509         seq_stripelem_cache_cleanup();
510
511         /* get editmode results */
512         ED_object_exit_editmode(C, 0);  /* 0 = does not exit editmode */
513
514         // store spare
515         // get view3d layer, local layer, make this nice api call to render
516         // store spare
517
518         /* ensure at least 1 area shows result */
519         render_view_open(C, event->x, event->y);
520
521         jobflag= WM_JOB_EXCL_RENDER|WM_JOB_PRIORITY|WM_JOB_PROGRESS;
522         
523         /* single layer re-render */
524         if(RNA_property_is_set(op->ptr, "layer")) {
525                 SceneRenderLayer *rl;
526                 Scene *scn;
527                 char scene_name[MAX_ID_NAME-2], rl_name[RE_MAXNAME];
528
529                 RNA_string_get(op->ptr, "layer", rl_name);
530                 RNA_string_get(op->ptr, "scene", scene_name);
531
532                 scn = (Scene *)BLI_findstring(&mainp->scene, scene_name, offsetof(ID, name) + 2);
533                 rl = (SceneRenderLayer *)BLI_findstring(&scene->r.layers, rl_name, offsetof(SceneRenderLayer, name));
534                 
535                 if (scn && rl) {
536                         /* camera switch wont have updated */
537                         scn->r.cfra= scene->r.cfra;
538                         scene_camera_switch_update(scn);
539
540                         scene = scn;
541                         srl = rl;
542                 }
543                 jobflag |= WM_JOB_SUSPEND;
544         }
545
546         /* job custom data */
547         rj= MEM_callocN(sizeof(RenderJob), "render job");
548         rj->main= mainp;
549         rj->scene= scene;
550         rj->win= CTX_wm_window(C);
551         rj->srl = srl;
552         rj->camera_override = camera_override;
553         rj->lay = (v3d)? v3d->lay: scene->lay;
554         rj->anim= is_animation;
555         rj->write_still= is_write_still && !is_animation;
556         rj->iuser.scene= scene;
557         rj->iuser.ok= 1;
558         rj->reports= op->reports;
559
560         /* setup job */
561         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, "Render", jobflag);
562         WM_jobs_customdata(steve, rj, render_freejob);
563         WM_jobs_timer(steve, 0.2, NC_SCENE|ND_RENDER_RESULT, 0);
564         WM_jobs_callbacks(steve, render_startjob, NULL, NULL, render_endjob);
565
566         /* get a render result image, and make sure it is empty */
567         ima= BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
568         BKE_image_signal(ima, NULL, IMA_SIGNAL_FREE);
569         BKE_image_backup_render(rj->scene, ima);
570         rj->image= ima;
571
572         /* setup new render */
573         re= RE_NewRender(scene->id.name);
574         RE_test_break_cb(re, rj, render_breakjob);
575         RE_draw_lock_cb(re, rj, render_drawlock);
576         RE_display_draw_cb(re, rj, image_rect_update);
577         RE_stats_draw_cb(re, rj, image_renderinfo_cb);
578         RE_progress_cb(re, rj, render_progress_update);
579
580         rj->re= re;
581         G.afbreek= 0;
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 /* contextual render, using current scene, view3d? */
600 void RENDER_OT_render(wmOperatorType *ot)
601 {
602         /* identifiers */
603         ot->name= "Render";
604         ot->description= "Render active scene";
605         ot->idname= "RENDER_OT_render";
606
607         /* api callbacks */
608         ot->invoke= screen_render_invoke;
609         ot->modal= screen_render_modal;
610         ot->exec= screen_render_exec;
611
612         /*ot->poll= ED_operator_screenactive;*/ /* this isnt needed, causes failer in background mode */
613
614         RNA_def_boolean(ot->srna, "animation", 0, "Animation", "Render files from the animation range of this scene");
615         RNA_def_boolean(ot->srna, "write_still", 0, "Write Image", "Save rendered the image to the output path (used only when animation is disabled)");
616         RNA_def_string(ot->srna, "layer", "", RE_MAXNAME, "Render Layer", "Single render layer to re-render");
617         RNA_def_string(ot->srna, "scene", "", MAX_ID_NAME-2, "Scene", "Re-render single layer in this scene");
618 }
619