Cycles: svn merge -r36777:37040 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->infostr && rs->infostr[0])
304                 spos+= sprintf(spos, "| %s ", rs->infostr);
305
306         /* very weak... but 512 characters is quite safe */
307         if(spos >= str+IMA_MAX_RENDER_TEXT)
308                 if (G.f & G_DEBUG)
309                         printf("WARNING! renderwin text beyond limit \n");
310
311 }
312
313 static void image_renderinfo_cb(void *rjv, RenderStats *rs)
314 {
315         RenderJob *rj= rjv;
316         RenderResult *rr;
317
318         rr= RE_AcquireResultRead(rj->re);
319
320         if(rr) {
321                 /* malloc OK here, stats_draw is not in tile threads */
322                 if(rr->text==NULL)
323                         rr->text= MEM_callocN(IMA_MAX_RENDER_TEXT, "rendertext");
324
325                 make_renderinfo_string(rs, rj->scene, rr->text);
326         }
327
328         RE_ReleaseResult(rj->re);
329
330         /* make jobs timer to send notifier */
331         *(rj->do_update)= 1;
332
333 }
334
335 static void render_progress_update(void *rjv, float progress)
336 {
337         RenderJob *rj= rjv;
338         
339         if(rj->progress)
340                 *rj->progress = progress;
341 }
342
343 static void image_rect_update(void *rjv, RenderResult *rr, volatile rcti *renrect)
344 {
345         RenderJob *rj= rjv;
346         Image *ima= rj->image;
347         ImBuf *ibuf;
348         void *lock;
349
350         /* only update if we are displaying the slot being rendered */
351         if(ima->render_slot != ima->last_render_slot)
352                 return;
353
354         ibuf= BKE_image_acquire_ibuf(ima, &rj->iuser, &lock);
355         if(ibuf) {
356                 image_buffer_rect_update(rj->scene, rr, ibuf, renrect);
357
358                 /* make jobs timer to send notifier */
359                 *(rj->do_update)= 1;
360         }
361         BKE_image_release_ibuf(ima, lock);
362 }
363
364 static void render_startjob(void *rjv, short *stop, short *do_update, float *progress)
365 {
366         RenderJob *rj= rjv;
367
368         rj->stop= stop;
369         rj->do_update= do_update;
370         rj->progress= progress;
371
372         RE_SetReports(rj->re, rj->reports);
373
374         if(rj->anim)
375                 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);
376         else
377                 RE_BlenderFrame(rj->re, rj->main, rj->scene, rj->srl, rj->camera_override, rj->lay, rj->scene->r.cfra, rj->write_still);
378
379         RE_SetReports(rj->re, NULL);
380 }
381
382 static void render_endjob(void *rjv)
383 {
384         RenderJob *rj= rjv;     
385
386         /* this render may be used again by the sequencer without the active 'Render' where the callbacks
387          * would be re-assigned. assign dummy callbacks to avoid referencing freed renderjobs bug [#24508] */
388         RE_InitRenderCB(rj->re);
389
390         if(rj->main != G.main)
391                 free_main(rj->main);
392
393         /* else the frame will not update for the original value */
394         if(!(rj->scene->r.scemode & R_NO_FRAME_UPDATE))
395                 ED_update_for_newframe(G.main, rj->scene, rj->win->screen, 1);
396         
397         /* XXX above function sets all tags in nodes */
398         ntreeClearTags(rj->scene->nodetree);
399         
400         /* potentially set by caller */
401         rj->scene->r.scemode &= ~R_NO_FRAME_UPDATE;
402         
403         if(rj->srl) {
404                 NodeTagIDChanged(rj->scene->nodetree, &rj->scene->id);
405                 WM_main_add_notifier(NC_NODE|NA_EDITED, rj->scene);
406         }
407         
408         /* XXX render stability hack */
409         G.rendering = 0;
410         WM_main_add_notifier(NC_WINDOW, NULL);
411 }
412
413 /* called by render, check job 'stop' value or the global */
414 static int render_breakjob(void *rjv)
415 {
416         RenderJob *rj= rjv;
417
418         if(G.afbreek)
419                 return 1;
420         if(rj->stop && *(rj->stop))
421                 return 1;
422         return 0;
423 }
424
425 /* runs in thread, no cursor setting here works. careful with notifiers too (malloc conflicts) */
426 /* maybe need a way to get job send notifer? */
427 static void render_drawlock(void *UNUSED(rjv), int lock)
428 {
429         BKE_spacedata_draw_locks(lock);
430         
431 }
432
433 /* catch esc */
434 static int screen_render_modal(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
435 {
436         /* no running blender, remove handler and pass through */
437         if(0==WM_jobs_test(CTX_wm_manager(C), CTX_data_scene(C))) {
438                 return OPERATOR_FINISHED|OPERATOR_PASS_THROUGH;
439         }
440
441         /* running render */
442         switch (event->type) {
443                 case ESCKEY:
444                         return OPERATOR_RUNNING_MODAL;
445                         break;
446         }
447         return OPERATOR_PASS_THROUGH;
448 }
449
450 /* using context, starts job */
451 static int screen_render_invoke(bContext *C, wmOperator *op, wmEvent *event)
452 {
453         /* new render clears all callbacks */
454         Main *mainp;
455         Scene *scene= CTX_data_scene(C);
456         SceneRenderLayer *srl=NULL;
457         bScreen *screen= CTX_wm_screen(C);
458         View3D *v3d= CTX_wm_view3d(C);
459         Render *re;
460         wmJob *steve;
461         RenderJob *rj;
462         Image *ima;
463         int jobflag;
464         const short is_animation= RNA_boolean_get(op->ptr, "animation");
465         const short is_write_still= RNA_boolean_get(op->ptr, "write_still");
466         struct Object *camera_override= v3d ? V3D_CAMERA_LOCAL(v3d) : NULL;
467         
468         /* only one render job at a time */
469         if(WM_jobs_test(CTX_wm_manager(C), scene))
470                 return OPERATOR_CANCELLED;
471
472         if(!RE_is_rendering_allowed(scene, camera_override, op->reports)) {
473                 return OPERATOR_CANCELLED;
474         }
475
476         if(!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.imtype)) {
477                 BKE_report(op->reports, RPT_ERROR, "Can't write a single file with an animation format selected.");
478                 return OPERATOR_CANCELLED;
479         }       
480         
481         /* stop all running jobs, currently previews frustrate Render */
482         WM_jobs_stop_all(CTX_wm_manager(C));
483
484         /* get main */
485         if(G.rt == 101) {
486                 /* thread-safety experiment, copy main from the undo buffer */
487                 mainp= BKE_undo_get_main(&scene);
488         }
489         else
490                 mainp= CTX_data_main(C);
491
492         /* cancel animation playback */
493         if (screen->animtimer)
494                 ED_screen_animation_play(C, 0, 0);
495         
496         /* handle UI stuff */
497         WM_cursor_wait(1);
498
499         /* flush multires changes (for sculpt) */
500         multires_force_render_update(CTX_data_active_object(C));
501
502         /* cleanup sequencer caches before starting user triggered render.
503            otherwise, invalidated cache entries can make their way into
504            the output rendering. We can't put that into RE_BlenderFrame,
505            since sequence rendering can call that recursively... (peter) */
506         seq_stripelem_cache_cleanup();
507
508         /* get editmode results */
509         ED_object_exit_editmode(C, 0);  /* 0 = does not exit editmode */
510
511         // store spare
512         // get view3d layer, local layer, make this nice api call to render
513         // store spare
514
515         /* ensure at least 1 area shows result */
516         render_view_open(C, event->x, event->y);
517
518         jobflag= WM_JOB_EXCL_RENDER|WM_JOB_PRIORITY|WM_JOB_PROGRESS;
519         
520         /* single layer re-render */
521         if(RNA_property_is_set(op->ptr, "layer")) {
522                 SceneRenderLayer *rl;
523                 Scene *scn;
524                 char scene_name[MAX_ID_NAME-2], rl_name[RE_MAXNAME];
525
526                 RNA_string_get(op->ptr, "layer", rl_name);
527                 RNA_string_get(op->ptr, "scene", scene_name);
528
529                 scn = (Scene *)BLI_findstring(&mainp->scene, scene_name, offsetof(ID, name) + 2);
530                 rl = (SceneRenderLayer *)BLI_findstring(&scene->r.layers, rl_name, offsetof(SceneRenderLayer, name));
531                 
532                 if (scn && rl) {
533                         /* camera switch wont have updated */
534                         scn->r.cfra= scene->r.cfra;
535                         scene_camera_switch_update(scn);
536
537                         scene = scn;
538                         srl = rl;
539                 }
540                 jobflag |= WM_JOB_SUSPEND;
541         }
542
543         /* job custom data */
544         rj= MEM_callocN(sizeof(RenderJob), "render job");
545         rj->main= mainp;
546         rj->scene= scene;
547         rj->win= CTX_wm_window(C);
548         rj->srl = srl;
549         rj->camera_override = camera_override;
550         rj->lay = (v3d)? v3d->lay: scene->lay;
551         rj->anim= is_animation;
552         rj->write_still= is_write_still && !is_animation;
553         rj->iuser.scene= scene;
554         rj->iuser.ok= 1;
555         rj->reports= op->reports;
556
557         /* setup job */
558         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, "Render", 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");
614         RNA_def_string(ot->srna, "scene", "", MAX_ID_NAME-2, "Scene", "Re-render single layer in this scene");
615 }
616