rename RNA_property_is_set() --> RNA_struct_property_is_set() in preperation to add...
[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                 predivide= (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT_PREDIVIDE);
144         }
145         else {
146                 profile_from= IB_PROFILE_SRGB;
147                 predivide= 0;
148         }
149
150         IMB_buffer_byte_from_float(rectc, rectf,
151                 4, ibuf->dither, IB_PROFILE_SRGB, profile_from, predivide,
152                 xmax, ymax, ibuf->x, rr->rectx);
153 }
154
155 /* ****************************** render invoking ***************** */
156
157 /* set callbacks, exported to sequence render too.
158  Only call in foreground (UI) renders. */
159
160 static void screen_render_scene_layer_set(wmOperator *op, Main *mainp, Scene **scene, SceneRenderLayer **srl)
161 {
162         /* single layer re-render */
163         if(RNA_struct_property_is_set(op->ptr, "scene")) {
164                 Scene *scn;
165                 char scene_name[MAX_ID_NAME-2];
166
167                 RNA_string_get(op->ptr, "scene", scene_name);
168                 scn = (Scene *)BLI_findstring(&mainp->scene, scene_name, offsetof(ID, name) + 2);
169                 
170                 if (scn) {
171                         /* camera switch wont have updated */
172                         scn->r.cfra= (*scene)->r.cfra;
173                         scene_camera_switch_update(scn);
174
175                         *scene = scn;
176                 }
177         }
178
179         if(RNA_struct_property_is_set(op->ptr, "layer")) {
180                 SceneRenderLayer *rl;
181                 char rl_name[RE_MAXNAME];
182
183                 RNA_string_get(op->ptr, "layer", rl_name);
184                 rl = (SceneRenderLayer *)BLI_findstring(&(*scene)->r.layers, rl_name, offsetof(SceneRenderLayer, name));
185                 
186                 if (rl)
187                         *srl = rl;
188         }
189 }
190
191 /* executes blocking render */
192 static int screen_render_exec(bContext *C, wmOperator *op)
193 {
194         Scene *scene= CTX_data_scene(C);
195         SceneRenderLayer *srl= NULL;
196         Render *re;
197         Image *ima;
198         View3D *v3d= CTX_wm_view3d(C);
199         Main *mainp= CTX_data_main(C);
200         unsigned int 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         /* custom scene and single layer re-render */
206         screen_render_scene_layer_set(op, mainp, &scene, &srl);
207
208         if(!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
209                 BKE_report(op->reports, RPT_ERROR, "Can't write a single file with an animation format selected");
210                 return OPERATOR_CANCELLED;
211         }
212
213         re= RE_NewRender(scene->id.name);
214         lay= (v3d)? v3d->lay: scene->lay;
215
216         G.afbreek= 0;
217         RE_test_break_cb(re, NULL, (int (*)(void *)) blender_test_break);
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         RE_SetReports(re, op->reports);
230
231         if(is_animation)
232                 RE_BlenderAnim(re, mainp, scene, camera_override, lay, scene->r.sfra, scene->r.efra, scene->r.frame_step);
233         else
234                 RE_BlenderFrame(re, mainp, scene, srl, camera_override, lay, scene->r.cfra, is_write_still);
235
236         RE_SetReports(re, NULL);
237
238         // no redraw needed, we leave state as we entered it
239         ED_update_for_newframe(mainp, scene, CTX_wm_screen(C), 1);
240
241         WM_event_add_notifier(C, NC_SCENE|ND_RENDER_RESULT, scene);
242
243         return OPERATOR_FINISHED;
244 }
245
246 typedef struct RenderJob {
247         Main *main;
248         Scene *scene;
249         Render *re;
250         wmWindow *win;
251         SceneRenderLayer *srl;
252         struct Object *camera_override;
253         int lay;
254         short anim, write_still;
255         Image *image;
256         ImageUser iuser;
257         short *stop;
258         short *do_update;
259         float *progress;
260         ReportList *reports;
261 } RenderJob;
262
263 static void render_freejob(void *rjv)
264 {
265         RenderJob *rj= rjv;
266
267         MEM_freeN(rj);
268 }
269
270 /* str is IMA_MAX_RENDER_TEXT in size */
271 static void make_renderinfo_string(RenderStats *rs, Scene *scene, char *str)
272 {
273         char info_time_str[32]; // used to be extern to header_info.c
274         uintptr_t mem_in_use, mmap_in_use, peak_memory;
275         float megs_used_memory, mmap_used_memory, megs_peak_memory;
276         char *spos= str;
277
278         mem_in_use= MEM_get_memory_in_use();
279         mmap_in_use= MEM_get_mapped_memory_in_use();
280         peak_memory = MEM_get_peak_memory();
281
282         megs_used_memory= (mem_in_use-mmap_in_use)/(1024.0*1024.0);
283         mmap_used_memory= (mmap_in_use)/(1024.0*1024.0);
284         megs_peak_memory = (peak_memory)/(1024.0*1024.0);
285
286         if(scene->lay & 0xFF000000)
287                 spos+= sprintf(spos, "Localview | ");
288         else if(scene->r.scemode & R_SINGLE_LAYER)
289                 spos+= sprintf(spos, "Single Layer | ");
290
291         if(rs->statstr) {
292                 spos+= sprintf(spos, "%s ", rs->statstr);
293         }
294         else {
295                 spos+= sprintf(spos, "Fra:%d  ", (scene->r.cfra));
296                 if(rs->totvert) spos+= sprintf(spos, "Ve:%d ", rs->totvert);
297                 if(rs->totface) spos+= sprintf(spos, "Fa:%d ", rs->totface);
298                 if(rs->tothalo) spos+= sprintf(spos, "Ha:%d ", rs->tothalo);
299                 if(rs->totstrand) spos+= sprintf(spos, "St:%d ", rs->totstrand);
300                 if(rs->totlamp) spos+= sprintf(spos, "La:%d ", rs->totlamp);
301                 spos+= sprintf(spos, "Mem:%.2fM (%.2fM, peak %.2fM) ", megs_used_memory, mmap_used_memory, megs_peak_memory);
302
303                 if(rs->curfield)
304                         spos+= sprintf(spos, "Field %d ", rs->curfield);
305                 if(rs->curblur)
306                         spos+= sprintf(spos, "Blur %d ", rs->curblur);
307         }
308
309         BLI_timestr(rs->lastframetime, info_time_str);
310         spos+= sprintf(spos, "Time:%s ", info_time_str);
311
312         if(rs->curfsa)
313                 spos+= sprintf(spos, "| Full Sample %d ", rs->curfsa);
314         
315         if(rs->infostr && rs->infostr[0])
316                 spos+= sprintf(spos, "| %s ", rs->infostr);
317
318         /* very weak... but 512 characters is quite safe */
319         if(spos >= str+IMA_MAX_RENDER_TEXT)
320                 if (G.f & G_DEBUG)
321                         printf("WARNING! renderwin text beyond limit \n");
322
323 }
324
325 static void image_renderinfo_cb(void *rjv, RenderStats *rs)
326 {
327         RenderJob *rj= rjv;
328         RenderResult *rr;
329
330         rr= RE_AcquireResultRead(rj->re);
331
332         if(rr) {
333                 /* malloc OK here, stats_draw is not in tile threads */
334                 if(rr->text==NULL)
335                         rr->text= MEM_callocN(IMA_MAX_RENDER_TEXT, "rendertext");
336
337                 make_renderinfo_string(rs, rj->scene, rr->text);
338         }
339
340         RE_ReleaseResult(rj->re);
341
342         /* make jobs timer to send notifier */
343         *(rj->do_update)= 1;
344
345 }
346
347 static void render_progress_update(void *rjv, float progress)
348 {
349         RenderJob *rj= rjv;
350         
351         if(rj->progress && *rj->progress != progress) {
352                 *rj->progress = progress;
353
354                 /* make jobs timer to send notifier */
355                 *(rj->do_update)= 1;
356         }
357 }
358
359 static void image_rect_update(void *rjv, RenderResult *rr, volatile rcti *renrect)
360 {
361         RenderJob *rj= rjv;
362         Image *ima= rj->image;
363         ImBuf *ibuf;
364         void *lock;
365
366         /* only update if we are displaying the slot being rendered */
367         if(ima->render_slot != ima->last_render_slot)
368                 return;
369
370         ibuf= BKE_image_acquire_ibuf(ima, &rj->iuser, &lock);
371         if(ibuf) {
372                 image_buffer_rect_update(rj->scene, rr, ibuf, renrect);
373
374                 /* make jobs timer to send notifier */
375                 *(rj->do_update)= 1;
376         }
377         BKE_image_release_ibuf(ima, lock);
378 }
379
380 static void render_startjob(void *rjv, short *stop, short *do_update, float *progress)
381 {
382         RenderJob *rj= rjv;
383
384         rj->stop= stop;
385         rj->do_update= do_update;
386         rj->progress= progress;
387
388         RE_SetReports(rj->re, rj->reports);
389
390         if(rj->anim)
391                 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);
392         else
393                 RE_BlenderFrame(rj->re, rj->main, rj->scene, rj->srl, rj->camera_override, rj->lay, rj->scene->r.cfra, rj->write_still);
394
395         RE_SetReports(rj->re, NULL);
396 }
397
398 static void render_endjob(void *rjv)
399 {
400         RenderJob *rj= rjv;     
401
402         /* this render may be used again by the sequencer without the active 'Render' where the callbacks
403          * would be re-assigned. assign dummy callbacks to avoid referencing freed renderjobs bug [#24508] */
404         RE_InitRenderCB(rj->re);
405
406         if(rj->main != G.main)
407                 free_main(rj->main);
408
409         /* else the frame will not update for the original value */
410         if(!(rj->scene->r.scemode & R_NO_FRAME_UPDATE))
411                 ED_update_for_newframe(G.main, rj->scene, rj->win->screen, 1);
412         
413         /* XXX above function sets all tags in nodes */
414         ntreeCompositClearTags(rj->scene->nodetree);
415         
416         /* potentially set by caller */
417         rj->scene->r.scemode &= ~R_NO_FRAME_UPDATE;
418         
419         if(rj->srl) {
420                 nodeUpdateID(rj->scene->nodetree, &rj->scene->id);
421                 WM_main_add_notifier(NC_NODE|NA_EDITED, rj->scene);
422         }
423         
424         /* XXX render stability hack */
425         G.rendering = 0;
426         WM_main_add_notifier(NC_WINDOW, NULL);
427 }
428
429 /* called by render, check job 'stop' value or the global */
430 static int render_breakjob(void *rjv)
431 {
432         RenderJob *rj= rjv;
433
434         if(G.afbreek)
435                 return 1;
436         if(rj->stop && *(rj->stop))
437                 return 1;
438         return 0;
439 }
440
441 /* runs in thread, no cursor setting here works. careful with notifiers too (malloc conflicts) */
442 /* maybe need a way to get job send notifer? */
443 static void render_drawlock(void *UNUSED(rjv), int lock)
444 {
445         BKE_spacedata_draw_locks(lock);
446         
447 }
448
449 /* catch esc */
450 static int screen_render_modal(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
451 {
452         /* no running blender, remove handler and pass through */
453         if(0==WM_jobs_test(CTX_wm_manager(C), CTX_data_scene(C))) {
454                 return OPERATOR_FINISHED|OPERATOR_PASS_THROUGH;
455         }
456
457         /* running render */
458         switch (event->type) {
459                 case ESCKEY:
460                         return OPERATOR_RUNNING_MODAL;
461                         break;
462         }
463         return OPERATOR_PASS_THROUGH;
464 }
465
466 /* using context, starts job */
467 static int screen_render_invoke(bContext *C, wmOperator *op, wmEvent *event)
468 {
469         /* new render clears all callbacks */
470         Main *mainp;
471         Scene *scene= CTX_data_scene(C);
472         SceneRenderLayer *srl=NULL;
473         bScreen *screen= CTX_wm_screen(C);
474         View3D *v3d= CTX_wm_view3d(C);
475         Render *re;
476         wmJob *steve;
477         RenderJob *rj;
478         Image *ima;
479         int jobflag;
480         const short is_animation= RNA_boolean_get(op->ptr, "animation");
481         const short is_write_still= RNA_boolean_get(op->ptr, "write_still");
482         struct Object *camera_override= v3d ? V3D_CAMERA_LOCAL(v3d) : NULL;
483         const char *name;
484         
485         /* only one render job at a time */
486         if(WM_jobs_test(CTX_wm_manager(C), scene))
487                 return OPERATOR_CANCELLED;
488
489         if(!RE_is_rendering_allowed(scene, camera_override, op->reports)) {
490                 return OPERATOR_CANCELLED;
491         }
492
493         if(!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
494                 BKE_report(op->reports, RPT_ERROR, "Can't write a single file with an animation format selected");
495                 return OPERATOR_CANCELLED;
496         }       
497         
498         /* stop all running jobs, currently previews frustrate Render */
499         WM_jobs_stop_all(CTX_wm_manager(C));
500
501         /* get main */
502         if(G.rt == 101) {
503                 /* thread-safety experiment, copy main from the undo buffer */
504                 mainp= BKE_undo_get_main(&scene);
505         }
506         else
507                 mainp= CTX_data_main(C);
508
509         /* cancel animation playback */
510         if (screen->animtimer)
511                 ED_screen_animation_play(C, 0, 0);
512         
513         /* handle UI stuff */
514         WM_cursor_wait(1);
515
516         /* flush multires changes (for sculpt) */
517         multires_force_render_update(CTX_data_active_object(C));
518
519         /* cleanup sequencer caches before starting user triggered render.
520            otherwise, invalidated cache entries can make their way into
521            the output rendering. We can't put that into RE_BlenderFrame,
522            since sequence rendering can call that recursively... (peter) */
523         seq_stripelem_cache_cleanup();
524
525         /* get editmode results */
526         ED_object_exit_editmode(C, 0);  /* 0 = does not exit editmode */
527
528         // store spare
529         // get view3d layer, local layer, make this nice api call to render
530         // store spare
531
532         /* ensure at least 1 area shows result */
533         render_view_open(C, event->x, event->y);
534
535         jobflag= WM_JOB_EXCL_RENDER|WM_JOB_PRIORITY|WM_JOB_PROGRESS;
536         
537         /* custom scene and single layer re-render */
538         screen_render_scene_layer_set(op, mainp, &scene, &srl);
539
540         if(RNA_struct_property_is_set(op->ptr, "layer"))
541                 jobflag |= WM_JOB_SUSPEND;
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         if(RE_seq_render_active(scene, &scene->r)) name= "Sequence Render";
559         else name= "Render";
560
561         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, name, 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 (used only when animation is disabled)");
617         RNA_def_string(ot->srna, "scene", "", MAX_ID_NAME-2, "Scene", "Scene to render, current scene if not specified");
618 }
619