Merge branch 'blender2.7'
[blender.git] / source / blender / render / intern / source / render_result.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) 2006 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/render/intern/source/render_result.c
29  *  \ingroup render
30  */
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <errno.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_utildefines.h"
40 #include "BLI_listbase.h"
41 #include "BLI_hash_md5.h"
42 #include "BLI_path_util.h"
43 #include "BLI_rect.h"
44 #include "BLI_string.h"
45 #include "BLI_threads.h"
46
47 #include "BKE_appdir.h"
48 #include "BKE_camera.h"
49 #include "BKE_global.h"
50 #include "BKE_image.h"
51 #include "BKE_report.h"
52 #include "BKE_scene.h"
53
54 #include "IMB_imbuf.h"
55 #include "IMB_imbuf_types.h"
56 #include "IMB_colormanagement.h"
57
58 #include "intern/openexr/openexr_multi.h"
59
60 #include "RE_engine.h"
61
62 #include "render_result.h"
63 #include "render_types.h"
64
65 /********************************** Free *************************************/
66
67 static void render_result_views_free(RenderResult *res)
68 {
69         while (res->views.first) {
70                 RenderView *rv = res->views.first;
71                 BLI_remlink(&res->views, rv);
72
73                 if (rv->rect32)
74                         MEM_freeN(rv->rect32);
75
76                 if (rv->rectz)
77                         MEM_freeN(rv->rectz);
78
79                 if (rv->rectf)
80                         MEM_freeN(rv->rectf);
81
82                 MEM_freeN(rv);
83         }
84
85         res->have_combined = false;
86 }
87
88 void render_result_free(RenderResult *res)
89 {
90         if (res == NULL) return;
91
92         while (res->layers.first) {
93                 RenderLayer *rl = res->layers.first;
94
95                 /* acolrect and scolrect are optionally allocated in shade_tile, only free here since it can be used for drawing */
96                 if (rl->acolrect) MEM_freeN(rl->acolrect);
97                 if (rl->scolrect) MEM_freeN(rl->scolrect);
98                 if (rl->display_buffer) MEM_freeN(rl->display_buffer);
99
100                 while (rl->passes.first) {
101                         RenderPass *rpass = rl->passes.first;
102                         if (rpass->rect) MEM_freeN(rpass->rect);
103                         BLI_remlink(&rl->passes, rpass);
104                         MEM_freeN(rpass);
105                 }
106                 BLI_remlink(&res->layers, rl);
107                 MEM_freeN(rl);
108         }
109
110         render_result_views_free(res);
111
112         if (res->rect32)
113                 MEM_freeN(res->rect32);
114         if (res->rectz)
115                 MEM_freeN(res->rectz);
116         if (res->rectf)
117                 MEM_freeN(res->rectf);
118         if (res->text)
119                 MEM_freeN(res->text);
120         if (res->error)
121                 MEM_freeN(res->error);
122
123         BKE_stamp_data_free(res->stamp_data);
124
125         MEM_freeN(res);
126 }
127
128 /* version that's compatible with fullsample buffers */
129 void render_result_free_list(ListBase *lb, RenderResult *rr)
130 {
131         RenderResult *rrnext;
132
133         for (; rr; rr = rrnext) {
134                 rrnext = rr->next;
135
136                 if (lb && lb->first)
137                         BLI_remlink(lb, rr);
138
139                 render_result_free(rr);
140         }
141 }
142
143 /********************************* multiview *************************************/
144
145 /* create a new views Listbase in rr without duplicating the memory pointers */
146 void render_result_views_shallowcopy(RenderResult *dst, RenderResult *src)
147 {
148         RenderView *rview;
149
150         if (dst == NULL || src == NULL)
151                 return;
152
153         for (rview = src->views.first; rview; rview = rview->next) {
154                 RenderView *rv;
155
156                 rv = MEM_mallocN(sizeof(RenderView), "new render view");
157                 BLI_addtail(&dst->views, rv);
158
159                 BLI_strncpy(rv->name, rview->name, sizeof(rv->name));
160                 rv->rectf = rview->rectf;
161                 rv->rectz = rview->rectz;
162                 rv->rect32 = rview->rect32;
163         }
164 }
165
166 /* free the views created temporarily */
167 void render_result_views_shallowdelete(RenderResult *rr)
168 {
169         if (rr == NULL)
170                 return;
171
172         while (rr->views.first) {
173                 RenderView *rv = rr->views.first;
174                 BLI_remlink(&rr->views, rv);
175                 MEM_freeN(rv);
176         }
177 }
178
179
180 static char* set_pass_name(char *outname, const char *name, int channel, const char *chan_id)
181 {
182         BLI_strncpy(outname, name, EXR_PASS_MAXNAME);
183         if (channel >= 0) {
184                 char token[3] = {'.', chan_id[channel], '\0'};
185                 strncat(outname, token, EXR_PASS_MAXNAME);
186         }
187         return outname;
188 }
189
190 static void set_pass_full_name(char *fullname, const char *name, int channel, const char *view, const char *chan_id)
191 {
192         BLI_strncpy(fullname, name, EXR_PASS_MAXNAME);
193         if (view && view[0]) {
194                 strncat(fullname, ".", EXR_PASS_MAXNAME);
195                 strncat(fullname, view, EXR_PASS_MAXNAME);
196         }
197         if (channel >= 0) {
198                 char token[3] = {'.', chan_id[channel], '\0'};
199                 strncat(fullname, token, EXR_PASS_MAXNAME);
200         }
201 }
202
203 /********************************** New **************************************/
204
205 static RenderPass *render_layer_add_pass(RenderResult *rr, RenderLayer *rl, int channels, const char *name, const char *viewname, const char *chan_id)
206 {
207         const int view_id = BLI_findstringindex(&rr->views, viewname, offsetof(RenderView, name));
208         RenderPass *rpass = MEM_callocN(sizeof(RenderPass), name);
209         size_t rectsize = ((size_t)rr->rectx) * rr->recty * channels;
210
211         rpass->channels = channels;
212         rpass->rectx = rl->rectx;
213         rpass->recty = rl->recty;
214         rpass->view_id = view_id;
215
216         BLI_strncpy(rpass->name, name, sizeof(rpass->name));
217         BLI_strncpy(rpass->chan_id, chan_id, sizeof(rpass->chan_id));
218         BLI_strncpy(rpass->view, viewname, sizeof(rpass->view));
219         set_pass_full_name(rpass->fullname, rpass->name, -1, rpass->view, rpass->chan_id);
220
221         if (rl->exrhandle) {
222                 int a;
223                 for (a = 0; a < channels; a++) {
224                         char passname[EXR_PASS_MAXNAME];
225                         IMB_exr_add_channel(rl->exrhandle, rl->name, set_pass_name(passname, rpass->name, a, rpass->chan_id), viewname, 0, 0, NULL, false);
226                 }
227         }
228         else {
229                 float *rect;
230                 int x;
231
232                 rpass->rect = MEM_mapallocN(sizeof(float) * rectsize, name);
233                 if (rpass->rect == NULL) {
234                         MEM_freeN(rpass);
235                         return NULL;
236                 }
237
238                 if (STREQ(rpass->name, RE_PASSNAME_VECTOR)) {
239                         /* initialize to max speed */
240                         rect = rpass->rect;
241                         for (x = rectsize - 1; x >= 0; x--)
242                                 rect[x] = PASS_VECTOR_MAX;
243                 }
244                 else if (STREQ(rpass->name, RE_PASSNAME_Z)) {
245                         rect = rpass->rect;
246                         for (x = rectsize - 1; x >= 0; x--)
247                                 rect[x] = 10e10;
248                 }
249         }
250
251         BLI_addtail(&rl->passes, rpass);
252
253         return rpass;
254 }
255 /* wrapper called from render_opengl */
256 RenderPass *gp_add_pass(RenderResult *rr, RenderLayer *rl, int channels, const char *name, const char *viewname)
257 {
258         return render_layer_add_pass(rr, rl, channels, name, viewname, "RGBA");
259 }
260
261 /* called by main render as well for parts */
262 /* will read info from Render *re to define layers */
263 /* called in threads */
264 /* re->winx,winy is coordinate space of entire image, partrct the part within */
265 RenderResult *render_result_new(Render *re, rcti *partrct, int crop, int savebuffers, const char *layername, const char *viewname)
266 {
267         RenderResult *rr;
268         RenderLayer *rl;
269         RenderView *rv;
270         int rectx, recty;
271
272         rectx = BLI_rcti_size_x(partrct);
273         recty = BLI_rcti_size_y(partrct);
274
275         if (rectx <= 0 || recty <= 0)
276                 return NULL;
277
278         rr = MEM_callocN(sizeof(RenderResult), "new render result");
279         rr->rectx = rectx;
280         rr->recty = recty;
281         rr->renrect.xmin = 0; rr->renrect.xmax = rectx - 2 * crop;
282         /* crop is one or two extra pixels rendered for filtering, is used for merging and display too */
283         rr->crop = crop;
284
285         /* tilerect is relative coordinates within render disprect. do not subtract crop yet */
286         rr->tilerect.xmin = partrct->xmin - re->disprect.xmin;
287         rr->tilerect.xmax = partrct->xmax - re->disprect.xmin;
288         rr->tilerect.ymin = partrct->ymin - re->disprect.ymin;
289         rr->tilerect.ymax = partrct->ymax - re->disprect.ymin;
290
291         if (savebuffers) {
292                 rr->do_exr_tile = true;
293         }
294
295         render_result_views_new(rr, &re->r);
296
297         /* check renderdata for amount of layers */
298         FOREACH_VIEW_LAYER_TO_RENDER_BEGIN(re, view_layer)
299         {
300                 if (layername && layername[0]) {
301                         if (!STREQ(view_layer->name, layername)) {
302                                 continue;
303                         }
304                 }
305
306                 rl = MEM_callocN(sizeof(RenderLayer), "new render layer");
307                 BLI_addtail(&rr->layers, rl);
308
309                 BLI_strncpy(rl->name, view_layer->name, sizeof(rl->name));
310                 rl->layflag = view_layer->layflag;
311                 rl->passflag = view_layer->passflag; /* for debugging: view_layer->passflag | SCE_PASS_RAYHITS; */
312                 rl->rectx = rectx;
313                 rl->recty = recty;
314
315                 if (rr->do_exr_tile) {
316                         rl->display_buffer = MEM_mapallocN((size_t)rectx * recty * sizeof(unsigned int),
317                                                            "Combined display space rgba");
318                         if (rl->display_buffer == NULL) {
319                                 render_result_free(rr);
320                                 return NULL;
321                         }
322                         rl->exrhandle = IMB_exr_get_handle();
323                 }
324
325                 for (rv = rr->views.first; rv; rv = rv->next) {
326                         const char *view = rv->name;
327
328                         if (viewname && viewname[0])
329                                 if (!STREQ(view, viewname))
330                                         continue;
331
332                         if (rr->do_exr_tile)
333                                 IMB_exr_add_view(rl->exrhandle, view);
334
335 #define RENDER_LAYER_ADD_PASS_SAFE(rr, rl, channels, name, viewname, chan_id) \
336                         do { \
337                                 if (render_layer_add_pass(rr, rl, channels, name, viewname, chan_id) == NULL) { \
338                                         render_result_free(rr); \
339                                         return NULL; \
340                                 } \
341                         } while (false)
342
343                         /* a renderlayer should always have a Combined pass*/
344                         render_layer_add_pass(rr, rl, 4, "Combined", view, "RGBA");
345
346                         if (view_layer->passflag  & SCE_PASS_Z)
347                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, RE_PASSNAME_Z, view, "Z");
348                         if (view_layer->passflag  & SCE_PASS_VECTOR)
349                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 4, RE_PASSNAME_VECTOR, view, "XYZW");
350                         if (view_layer->passflag  & SCE_PASS_NORMAL)
351                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_NORMAL, view, "XYZ");
352                         if (view_layer->passflag  & SCE_PASS_UV)
353                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_UV, view, "UVA");
354                         if (view_layer->passflag  & SCE_PASS_EMIT)
355                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_EMIT, view, "RGB");
356                         if (view_layer->passflag  & SCE_PASS_AO)
357                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_AO, view, "RGB");
358                         if (view_layer->passflag  & SCE_PASS_ENVIRONMENT)
359                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_ENVIRONMENT, view, "RGB");
360                         if (view_layer->passflag  & SCE_PASS_SHADOW)
361                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_SHADOW, view, "RGB");
362                         if (view_layer->passflag  & SCE_PASS_INDEXOB)
363                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, RE_PASSNAME_INDEXOB, view, "X");
364                         if (view_layer->passflag  & SCE_PASS_INDEXMA)
365                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, RE_PASSNAME_INDEXMA, view, "X");
366                         if (view_layer->passflag  & SCE_PASS_MIST)
367                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, RE_PASSNAME_MIST, view, "Z");
368                         if (rl->passflag & SCE_PASS_RAYHITS)
369                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 4, RE_PASSNAME_RAYHITS, view, "RGB");
370                         if (view_layer->passflag  & SCE_PASS_DIFFUSE_DIRECT)
371                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_DIFFUSE_DIRECT, view, "RGB");
372                         if (view_layer->passflag  & SCE_PASS_DIFFUSE_INDIRECT)
373                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_DIFFUSE_INDIRECT, view, "RGB");
374                         if (view_layer->passflag  & SCE_PASS_DIFFUSE_COLOR)
375                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_DIFFUSE_COLOR, view, "RGB");
376                         if (view_layer->passflag  & SCE_PASS_GLOSSY_DIRECT)
377                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_GLOSSY_DIRECT, view, "RGB");
378                         if (view_layer->passflag  & SCE_PASS_GLOSSY_INDIRECT)
379                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_GLOSSY_INDIRECT, view, "RGB");
380                         if (view_layer->passflag  & SCE_PASS_GLOSSY_COLOR)
381                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_GLOSSY_COLOR, view, "RGB");
382                         if (view_layer->passflag  & SCE_PASS_TRANSM_DIRECT)
383                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_TRANSM_DIRECT, view, "RGB");
384                         if (view_layer->passflag  & SCE_PASS_TRANSM_INDIRECT)
385                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_TRANSM_INDIRECT, view, "RGB");
386                         if (view_layer->passflag  & SCE_PASS_TRANSM_COLOR)
387                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_TRANSM_COLOR, view, "RGB");
388                         if (view_layer->passflag  & SCE_PASS_SUBSURFACE_DIRECT)
389                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_SUBSURFACE_DIRECT, view, "RGB");
390                         if (view_layer->passflag  & SCE_PASS_SUBSURFACE_INDIRECT)
391                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_SUBSURFACE_INDIRECT, view, "RGB");
392                         if (view_layer->passflag  & SCE_PASS_SUBSURFACE_COLOR)
393                                 RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_SUBSURFACE_COLOR, view, "RGB");
394 #undef RENDER_LAYER_ADD_PASS_SAFE
395                 }
396         }
397         FOREACH_VIEW_LAYER_TO_RENDER_END;
398
399         /* previewrender doesn't do layers, so we make a default one */
400         if (BLI_listbase_is_empty(&rr->layers) && !(layername && layername[0])) {
401                 rl = MEM_callocN(sizeof(RenderLayer), "new render layer");
402                 BLI_addtail(&rr->layers, rl);
403
404                 rl->rectx = rectx;
405                 rl->recty = recty;
406
407                 /* duplicate code... */
408                 if (rr->do_exr_tile) {
409                         rl->display_buffer = MEM_mapallocN(rectx * recty * sizeof(unsigned int), "Combined display space rgba");
410                         rl->exrhandle = IMB_exr_get_handle();
411                 }
412
413                 for (rv = rr->views.first; rv; rv = rv->next) {
414                         const char *view = rv->name;
415
416                         if (viewname && viewname[0])
417                                 if (strcmp(view, viewname) != 0)
418                                         continue;
419
420                         if (rr->do_exr_tile)
421                                 IMB_exr_add_view(rl->exrhandle, view);
422
423                         /* a renderlayer should always have a Combined pass */
424                         render_layer_add_pass(rr, rl, 4, RE_PASSNAME_COMBINED, view, "RGBA");
425                 }
426
427                 /* note, this has to be in sync with scene.c */
428                 rl->layflag = 0x7FFF;    /* solid ztra halo strand */
429                 rl->passflag = SCE_PASS_COMBINED;
430
431                 re->active_view_layer = 0;
432         }
433
434         /* border render; calculate offset for use in compositor. compo is centralized coords */
435         /* XXX obsolete? I now use it for drawing border render offset (ton) */
436         rr->xof = re->disprect.xmin + BLI_rcti_cent_x(&re->disprect) - (re->winx / 2);
437         rr->yof = re->disprect.ymin + BLI_rcti_cent_y(&re->disprect) - (re->winy / 2);
438
439         return rr;
440 }
441
442 void render_result_clone_passes(Render *re, RenderResult *rr, const char *viewname)
443 {
444         RenderLayer *rl;
445         RenderPass *main_rp;
446
447         for (rl = rr->layers.first; rl; rl = rl->next) {
448                 RenderLayer *main_rl = BLI_findstring(&re->result->layers, rl->name, offsetof(RenderLayer, name));
449                 if (!main_rl) {
450                         continue;
451                 }
452
453                 for (main_rp = main_rl->passes.first; main_rp; main_rp = main_rp->next) {
454                         if (viewname && viewname[0] && !STREQ(main_rp->view, viewname)) {
455                                 continue;
456                         }
457
458                         /* Compare fullname to make sure that the view also is equal. */
459                         RenderPass *rp = BLI_findstring(&rl->passes, main_rp->fullname, offsetof(RenderPass, fullname));
460                         if (!rp) {
461                                 render_layer_add_pass(rr, rl, main_rp->channels, main_rp->name, main_rp->view, main_rp->chan_id);
462                         }
463                 }
464         }
465 }
466
467 void render_result_add_pass(RenderResult *rr, const char *name, int channels, const char *chan_id, const char *layername, const char *viewname)
468 {
469         RenderLayer *rl;
470         RenderPass *rp;
471         RenderView *rv;
472
473         for (rl = rr->layers.first; rl; rl = rl->next) {
474                 if (layername && layername[0] && !STREQ(rl->name, layername)) {
475                         continue;
476                 }
477
478                 for (rv = rr->views.first; rv; rv = rv->next) {
479                         const char *view = rv->name;
480
481                         if (viewname && viewname[0] && !STREQ(view, viewname)) continue;
482
483                         /* Ensure that the pass doesn't exist yet. */
484                         for (rp = rl->passes.first; rp; rp = rp->next) {
485                                 if (!STREQ(rp->name, name)) continue;
486                                 if (!STREQ(rp->view, view)) continue;
487                                 break;
488                         }
489
490                         if (!rp) {
491                                 render_layer_add_pass(rr, rl, channels, name, view, chan_id);
492                         }
493                 }
494         }
495 }
496
497 static int passtype_from_name(const char *name)
498 {
499         const char delim[] = {'.', '\0'};
500         const char *sep, *suf;
501         int len = BLI_str_partition(name, delim, &sep, &suf);
502
503 #define CHECK_PASS(NAME) if (STREQLEN(name, RE_PASSNAME_ ## NAME, len)) return SCE_PASS_ ## NAME
504
505         CHECK_PASS(COMBINED);
506         CHECK_PASS(Z);
507         CHECK_PASS(VECTOR);
508         CHECK_PASS(NORMAL);
509         CHECK_PASS(UV);
510         CHECK_PASS(EMIT);
511         CHECK_PASS(SHADOW);
512         CHECK_PASS(AO);
513         CHECK_PASS(ENVIRONMENT);
514         CHECK_PASS(INDEXOB);
515         CHECK_PASS(INDEXMA);
516         CHECK_PASS(MIST);
517         CHECK_PASS(RAYHITS);
518         CHECK_PASS(DIFFUSE_DIRECT);
519         CHECK_PASS(DIFFUSE_INDIRECT);
520         CHECK_PASS(DIFFUSE_COLOR);
521         CHECK_PASS(GLOSSY_DIRECT);
522         CHECK_PASS(GLOSSY_INDIRECT);
523         CHECK_PASS(GLOSSY_COLOR);
524         CHECK_PASS(TRANSM_DIRECT);
525         CHECK_PASS(TRANSM_INDIRECT);
526         CHECK_PASS(TRANSM_COLOR);
527         CHECK_PASS(SUBSURFACE_DIRECT);
528         CHECK_PASS(SUBSURFACE_INDIRECT);
529         CHECK_PASS(SUBSURFACE_COLOR);
530
531 #undef CHECK_PASS
532         return 0;
533 }
534
535 /* callbacks for render_result_new_from_exr */
536 static void *ml_addlayer_cb(void *base, const char *str)
537 {
538         RenderResult *rr = base;
539         RenderLayer *rl;
540
541         rl = MEM_callocN(sizeof(RenderLayer), "new render layer");
542         BLI_addtail(&rr->layers, rl);
543
544         BLI_strncpy(rl->name, str, EXR_LAY_MAXNAME);
545         return rl;
546 }
547
548 static void ml_addpass_cb(void *base, void *lay, const char *name, float *rect, int totchan, const char *chan_id, const char *view)
549 {
550         RenderResult *rr = base;
551         RenderLayer *rl = lay;
552         RenderPass *rpass = MEM_callocN(sizeof(RenderPass), "loaded pass");
553
554         BLI_addtail(&rl->passes, rpass);
555         rpass->channels = totchan;
556         rl->passflag |= passtype_from_name(name);
557
558         /* channel id chars */
559         BLI_strncpy(rpass->chan_id, chan_id, sizeof(rpass->chan_id));
560
561         rpass->rect = rect;
562         BLI_strncpy(rpass->name, name, EXR_PASS_MAXNAME);
563         BLI_strncpy(rpass->view, view, sizeof(rpass->view));
564         set_pass_full_name(rpass->fullname, name, -1, view, rpass->chan_id);
565
566         if (view[0] != '\0') {
567                 rpass->view_id = BLI_findstringindex(&rr->views, view, offsetof(RenderView, name));
568         }
569         else {
570                 rpass->view_id = 0;
571         }
572 }
573
574 static void *ml_addview_cb(void *base, const char *str)
575 {
576         RenderResult *rr = base;
577         RenderView *rv;
578
579         rv = MEM_callocN(sizeof(RenderView), "new render view");
580         BLI_strncpy(rv->name, str, EXR_VIEW_MAXNAME);
581
582         /* For stereo drawing we need to ensure:
583          * STEREO_LEFT_NAME  == STEREO_LEFT_ID and
584          * STEREO_RIGHT_NAME == STEREO_RIGHT_ID */
585
586         if (STREQ(str, STEREO_LEFT_NAME)) {
587                 BLI_addhead(&rr->views, rv);
588         }
589         else if (STREQ(str, STEREO_RIGHT_NAME)) {
590                 RenderView *left_rv = BLI_findstring(&rr->views, STEREO_LEFT_NAME, offsetof(RenderView, name));
591
592                 if (left_rv == NULL) {
593                         BLI_addhead(&rr->views, rv);
594                 }
595                 else {
596                         BLI_insertlinkafter(&rr->views, left_rv, rv);
597                 }
598         }
599         else {
600                 BLI_addtail(&rr->views, rv);
601         }
602
603         return rv;
604 }
605
606 static int order_render_passes(const void *a, const void *b)
607 {
608         // 1 if a is after b
609         RenderPass *rpa = (RenderPass *) a;
610         RenderPass *rpb = (RenderPass *) b;
611         unsigned int passtype_a = passtype_from_name(rpa->name);
612         unsigned int passtype_b = passtype_from_name(rpb->name);
613
614         /* Render passes with default type always go first. */
615         if (passtype_b && !passtype_a)
616                 return 1;
617         if (passtype_a && !passtype_b)
618                 return 0;
619
620         if (passtype_a && passtype_b) {
621                 if (passtype_a > passtype_b)
622                         return 1;
623                 else if (passtype_a < passtype_b)
624                         return 0;
625         }
626         else {
627                 int cmp = strncmp(rpa->name, rpb->name, EXR_PASS_MAXNAME);
628                 if (cmp > 0)
629                         return 1;
630                 if (cmp < 0)
631                         return 0;
632         }
633
634
635         /* they have the same type */
636         /* left first */
637         if (STREQ(rpa->view, STEREO_LEFT_NAME))
638                 return 0;
639         else if (STREQ(rpb->view, STEREO_LEFT_NAME))
640                 return 1;
641
642         /* right second */
643         if (STREQ(rpa->view, STEREO_RIGHT_NAME))
644                 return 0;
645         else if (STREQ(rpb->view, STEREO_RIGHT_NAME))
646                 return 1;
647
648         /* remaining in ascending id order */
649         return (rpa->view_id < rpb->view_id);
650 }
651
652 /* from imbuf, if a handle was returned and it's not a singlelayer multiview we convert this to render result */
653 RenderResult *render_result_new_from_exr(void *exrhandle, const char *colorspace, bool predivide, int rectx, int recty)
654 {
655         RenderResult *rr = MEM_callocN(sizeof(RenderResult), __func__);
656         RenderLayer *rl;
657         RenderPass *rpass;
658         const char *to_colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_SCENE_LINEAR);
659
660         rr->rectx = rectx;
661         rr->recty = recty;
662
663         IMB_exr_multilayer_convert(exrhandle, rr, ml_addview_cb, ml_addlayer_cb, ml_addpass_cb);
664
665         for (rl = rr->layers.first; rl; rl = rl->next) {
666                 rl->rectx = rectx;
667                 rl->recty = recty;
668
669                 BLI_listbase_sort(&rl->passes, order_render_passes);
670
671                 for (rpass = rl->passes.first; rpass; rpass = rpass->next) {
672                         rpass->rectx = rectx;
673                         rpass->recty = recty;
674
675                         if (rpass->channels >= 3) {
676                                 IMB_colormanagement_transform(rpass->rect, rpass->rectx, rpass->recty, rpass->channels,
677                                                               colorspace, to_colorspace, predivide);
678                         }
679                 }
680         }
681
682         return rr;
683 }
684
685 void render_result_view_new(RenderResult *rr, const char *viewname)
686 {
687         RenderView *rv = MEM_callocN(sizeof(RenderView), "new render view");
688         BLI_addtail(&rr->views, rv);
689         BLI_strncpy(rv->name, viewname, sizeof(rv->name));
690 }
691
692 void render_result_views_new(RenderResult *rr, RenderData *rd)
693 {
694         SceneRenderView *srv;
695
696         /* clear previously existing views - for sequencer */
697         render_result_views_free(rr);
698
699         /* check renderdata for amount of views */
700         if ((rd->scemode & R_MULTIVIEW)) {
701                 for (srv = rd->views.first; srv; srv = srv->next) {
702                         if (BKE_scene_multiview_is_render_view_active(rd, srv) == false)
703                                 continue;
704                         render_result_view_new(rr, srv->name);
705                 }
706         }
707
708         /* we always need at least one view */
709         if (BLI_listbase_count_at_most(&rr->views, 1) == 0) {
710                 render_result_view_new(rr, "");
711         }
712 }
713
714 bool render_result_has_views(RenderResult *rr)
715 {
716         RenderView *rv = rr->views.first;
717         return (rv && (rv->next || rv->name[0]));
718 }
719
720 /*********************************** Merge ***********************************/
721
722 static void do_merge_tile(RenderResult *rr, RenderResult *rrpart, float *target, float *tile, int pixsize)
723 {
724         int y, tilex, tiley;
725         size_t ofs, copylen;
726
727         copylen = tilex = rrpart->rectx;
728         tiley = rrpart->recty;
729
730         if (rrpart->crop) { /* filters add pixel extra */
731                 tile += pixsize * (rrpart->crop + ((size_t)rrpart->crop) * tilex);
732
733                 copylen = tilex - 2 * rrpart->crop;
734                 tiley -= 2 * rrpart->crop;
735
736                 ofs = (((size_t)rrpart->tilerect.ymin) + rrpart->crop) * rr->rectx + (rrpart->tilerect.xmin + rrpart->crop);
737                 target += pixsize * ofs;
738         }
739         else {
740                 ofs = (((size_t)rrpart->tilerect.ymin) * rr->rectx + rrpart->tilerect.xmin);
741                 target += pixsize * ofs;
742         }
743
744         copylen *= sizeof(float) * pixsize;
745         tilex *= pixsize;
746         ofs = pixsize * rr->rectx;
747
748         for (y = 0; y < tiley; y++) {
749                 memcpy(target, tile, copylen);
750                 target += ofs;
751                 tile += tilex;
752         }
753 }
754
755 /* used when rendering to a full buffer, or when reading the exr part-layer-pass file */
756 /* no test happens here if it fits... we also assume layers are in sync */
757 /* is used within threads */
758 void render_result_merge(RenderResult *rr, RenderResult *rrpart)
759 {
760         RenderLayer *rl, *rlp;
761         RenderPass *rpass, *rpassp;
762
763         for (rl = rr->layers.first; rl; rl = rl->next) {
764                 rlp = RE_GetRenderLayer(rrpart, rl->name);
765                 if (rlp) {
766                         /* passes are allocated in sync */
767                         for (rpass = rl->passes.first, rpassp = rlp->passes.first;
768                              rpass && rpassp;
769                              rpass = rpass->next)
770                         {
771                                 /* renderresult have all passes, renderpart only the active view's passes */
772                                 if (strcmp(rpassp->fullname, rpass->fullname) != 0)
773                                         continue;
774
775                                 do_merge_tile(rr, rrpart, rpass->rect, rpassp->rect, rpass->channels);
776
777                                 /* manually get next render pass */
778                                 rpassp = rpassp->next;
779                         }
780                 }
781         }
782 }
783
784 /* Called from the UI and render pipeline, to save multilayer and multiview
785  * images, optionally isolating a specific, view, layer or RGBA/Z pass. */
786 bool RE_WriteRenderResult(ReportList *reports, RenderResult *rr, const char *filename, ImageFormatData *imf, const char *view, int layer)
787 {
788         void *exrhandle = IMB_exr_get_handle();
789         const bool half_float = (imf && imf->depth == R_IMF_CHAN_DEPTH_16);
790         const bool multi_layer = !(imf && imf->imtype == R_IMF_IMTYPE_OPENEXR);
791         const bool write_z = !multi_layer && (imf && (imf->flag & R_IMF_FLAG_ZBUF));
792
793         /* Write first layer if not multilayer and no layer was specified. */
794         if (!multi_layer && layer == -1) {
795                 layer = 0;
796         }
797
798         /* First add views since IMB_exr_add_channel checks number of views. */
799         if (render_result_has_views(rr)) {
800                 for (RenderView *rview = rr->views.first; rview; rview = rview->next) {
801                         if (!view || STREQ(view, rview->name)) {
802                                 IMB_exr_add_view(exrhandle, rview->name);
803                         }
804                 }
805         }
806
807         /* Compositing result. */
808         if (rr->have_combined) {
809                 for (RenderView *rview = rr->views.first; rview; rview = rview->next) {
810                         if (!rview->rectf) {
811                                 continue;
812                         }
813
814                         const char *viewname = rview->name;
815                         if (view) {
816                                 if (!STREQ(view, viewname)) {
817                                         continue;
818                                 }
819                                 else {
820                                         viewname = "";
821                                 }
822                         }
823
824                         /* Skip compositing if only a single other layer is requested. */
825                         if (!multi_layer && layer != 0) {
826                                 continue;
827                         }
828
829                         for (int a = 0; a < 4; a++) {
830                                 char passname[EXR_PASS_MAXNAME];
831                                 char layname[EXR_PASS_MAXNAME];
832                                 const char *chan_id = "RGBA";
833
834                                 if (multi_layer) {
835                                         set_pass_name(passname, "Combined", a, chan_id);
836                                         BLI_strncpy(layname, "Composite", sizeof(layname));
837                                 }
838                                 else {
839                                         passname[0] = chan_id[a];
840                                         passname[1] = '\0';
841                                         layname[0] = '\0';
842                                 }
843
844                                 IMB_exr_add_channel(exrhandle, layname, passname, viewname,
845                                                     4, 4 * rr->rectx, rview->rectf + a, half_float);
846                         }
847
848                         if (write_z && rview->rectz) {
849                                 const char *layname = (multi_layer)? "Composite": "";
850                                 IMB_exr_add_channel(exrhandle, layname, "Z", viewname,
851                                                     1, rr->rectx, rview->rectz, false);
852                         }
853                 }
854         }
855
856         /* Other render layers. */
857         int nr = (rr->have_combined)? 1: 0;
858         for (RenderLayer *rl = rr->layers.first; rl; rl = rl->next, nr++) {
859                 /* Skip other render layers if requested. */
860                 if (!multi_layer && nr != layer) {
861                         continue;
862                 }
863
864                 for (RenderPass *rp = rl->passes.first; rp; rp = rp->next) {
865                         /* Skip non-RGBA and Z passes if not using multi layer. */
866                         if (!multi_layer && !(STREQ(rp->name, RE_PASSNAME_COMBINED) ||
867                                               STREQ(rp->name, "") ||
868                                               (STREQ(rp->name, RE_PASSNAME_Z) && write_z)))
869                         {
870                                 continue;
871                         }
872
873                         /* Skip pass if it does not match the requested view(s). */
874                         const char *viewname = rp->view;
875                         if (view) {
876                                 if (!STREQ(view, viewname)) {
877                                         continue;
878                                 }
879                                 else {
880                                         viewname = "";
881                                 }
882                         }
883
884                         /* We only store RGBA passes as half float, for
885                          * others precision loss can be problematic. */
886                         bool pass_half_float = half_float &&
887                                                (STREQ(rp->chan_id, "RGB") ||
888                                                 STREQ(rp->chan_id, "RGBA") ||
889                                                 STREQ(rp->chan_id, "R") ||
890                                                 STREQ(rp->chan_id, "G") ||
891                                                 STREQ(rp->chan_id, "B") ||
892                                                 STREQ(rp->chan_id, "A"));
893
894
895                         for (int a = 0; a < rp->channels; a++) {
896                                 /* Save Combined as RGBA if single layer save. */
897                                 char passname[EXR_PASS_MAXNAME];
898                                 char layname[EXR_PASS_MAXNAME];
899
900                                 if (multi_layer) {
901                                         set_pass_name(passname, rp->name, a, rp->chan_id);
902                                         BLI_strncpy(layname, rl->name, sizeof(layname));
903                                 }
904                                 else {
905                                         passname[0] = rp->chan_id[a];
906                                         passname[1] = '\0';
907                                         layname[0] = '\0';
908                                 }
909
910                                 IMB_exr_add_channel(exrhandle, layname, passname, viewname,
911                                                     rp->channels, rp->channels * rr->rectx, rp->rect + a,
912                                                     pass_half_float);
913                         }
914                 }
915         }
916
917         errno = 0;
918
919         BLI_make_existing_file(filename);
920
921         int compress = (imf ? imf->exr_codec : 0);
922         bool success = IMB_exr_begin_write(exrhandle, filename, rr->rectx, rr->recty, compress, rr->stamp_data);
923         if (success) {
924                 IMB_exr_write_channels(exrhandle);
925         }
926         else {
927                 /* TODO, get the error from openexr's exception */
928                 BKE_reportf(reports, RPT_ERROR, "Error writing render result, %s (see console)", strerror(errno));
929         }
930
931         IMB_exr_close(exrhandle);
932         return success;
933 }
934
935 /**************************** Single Layer Rendering *************************/
936
937 void render_result_single_layer_begin(Render *re)
938 {
939         /* all layers except the active one get temporally pushed away */
940
941         /* officially pushed result should be NULL... error can happen with do_seq */
942         RE_FreeRenderResult(re->pushedresult);
943
944         re->pushedresult = re->result;
945         re->result = NULL;
946 }
947
948 /* if scemode is R_SINGLE_LAYER, at end of rendering, merge the both render results */
949 void render_result_single_layer_end(Render *re)
950 {
951         ViewLayer *view_layer;
952         RenderLayer *rlpush;
953         RenderLayer *rl;
954         int nr;
955
956         if (re->result == NULL) {
957                 printf("pop render result error; no current result!\n");
958                 return;
959         }
960
961         if (!re->pushedresult)
962                 return;
963
964         if (re->pushedresult->rectx == re->result->rectx && re->pushedresult->recty == re->result->recty) {
965                 /* find which layer in re->pushedresult should be replaced */
966                 rl = re->result->layers.first;
967
968                 /* render result should be empty after this */
969                 BLI_remlink(&re->result->layers, rl);
970
971                 /* reconstruct render result layers */
972                 for (nr = 0, view_layer = re->view_layers.first; view_layer; view_layer = view_layer->next, nr++) {
973                         if (nr == re->active_view_layer) {
974                                 BLI_addtail(&re->result->layers, rl);
975                         }
976                         else {
977                                 rlpush = RE_GetRenderLayer(re->pushedresult, view_layer->name);
978                                 if (rlpush) {
979                                         BLI_remlink(&re->pushedresult->layers, rlpush);
980                                         BLI_addtail(&re->result->layers, rlpush);
981                                 }
982                         }
983                 }
984         }
985
986         RE_FreeRenderResult(re->pushedresult);
987         re->pushedresult = NULL;
988 }
989
990 /************************* EXR Tile File Rendering ***************************/
991
992 static void save_render_result_tile(RenderResult *rr, RenderResult *rrpart, const char *viewname)
993 {
994         RenderLayer *rlp, *rl;
995         RenderPass *rpassp;
996         int offs, partx, party;
997
998         BLI_thread_lock(LOCK_IMAGE);
999
1000         for (rlp = rrpart->layers.first; rlp; rlp = rlp->next) {
1001                 rl = RE_GetRenderLayer(rr, rlp->name);
1002
1003                 /* should never happen but prevents crash if it does */
1004                 BLI_assert(rl);
1005                 if (UNLIKELY(rl == NULL)) {
1006                         continue;
1007                 }
1008
1009                 if (rrpart->crop) { /* filters add pixel extra */
1010                         offs = (rrpart->crop + rrpart->crop * rrpart->rectx);
1011                 }
1012                 else {
1013                         offs = 0;
1014                 }
1015
1016                 /* passes are allocated in sync */
1017                 for (rpassp = rlp->passes.first; rpassp; rpassp = rpassp->next) {
1018                         const int xstride = rpassp->channels;
1019                         int a;
1020                         char fullname[EXR_PASS_MAXNAME];
1021
1022                         for (a = 0; a < xstride; a++) {
1023                                 set_pass_full_name(fullname, rpassp->name, a, viewname, rpassp->chan_id);
1024
1025                                 IMB_exr_set_channel(rl->exrhandle, rlp->name, fullname,
1026                                                     xstride, xstride * rrpart->rectx, rpassp->rect + a + xstride * offs);
1027                         }
1028                 }
1029
1030         }
1031
1032         party = rrpart->tilerect.ymin + rrpart->crop;
1033         partx = rrpart->tilerect.xmin + rrpart->crop;
1034
1035         for (rlp = rrpart->layers.first; rlp; rlp = rlp->next) {
1036                 rl = RE_GetRenderLayer(rr, rlp->name);
1037
1038                 /* should never happen but prevents crash if it does */
1039                 BLI_assert(rl);
1040                 if (UNLIKELY(rl == NULL)) {
1041                         continue;
1042                 }
1043
1044                 IMB_exrtile_write_channels(rl->exrhandle, partx, party, 0, viewname, false);
1045         }
1046
1047         BLI_thread_unlock(LOCK_IMAGE);
1048 }
1049
1050 void render_result_save_empty_result_tiles(Render *re)
1051 {
1052         RenderPart *pa;
1053         RenderResult *rr;
1054         RenderLayer *rl;
1055
1056         for (rr = re->result; rr; rr = rr->next) {
1057                 for (rl = rr->layers.first; rl; rl = rl->next) {
1058                         for (pa = re->parts.first; pa; pa = pa->next) {
1059                                 if (pa->status != PART_STATUS_MERGED) {
1060                                         int party = pa->disprect.ymin - re->disprect.ymin;
1061                                         int partx = pa->disprect.xmin - re->disprect.xmin;
1062                                         IMB_exrtile_write_channels(rl->exrhandle, partx, party, 0, re->viewname, true);
1063                                 }
1064                         }
1065                 }
1066         }
1067 }
1068
1069 static void render_result_register_pass_cb(RenderEngine *engine, Scene *UNUSED(scene), ViewLayer *view_layer,
1070                                            const char *name, int channels, const char *chanid, int UNUSED(type))
1071 {
1072         RE_engine_add_pass(engine, name, channels, chanid, view_layer->name);
1073 }
1074
1075 static void render_result_create_all_passes(RenderEngine *engine, Render *re, RenderLayer *rl)
1076 {
1077         if (engine && engine->type->update_render_passes) {
1078                 ViewLayer *view_layer;
1079                 view_layer = BLI_findstring(&re->view_layers, rl->name, offsetof(ViewLayer, name));
1080                 if (view_layer) {
1081                         RE_engine_update_render_passes(engine, re->scene, view_layer, render_result_register_pass_cb);
1082                 }
1083         }
1084 }
1085
1086 /* begin write of exr tile file */
1087 void render_result_exr_file_begin(Render *re, RenderEngine *engine)
1088 {
1089         RenderResult *rr;
1090         RenderLayer *rl;
1091         char str[FILE_MAX];
1092
1093         for (rr = re->result; rr; rr = rr->next) {
1094                 for (rl = rr->layers.first; rl; rl = rl->next) {
1095                         render_result_create_all_passes(engine, re, rl);
1096
1097                         render_result_exr_file_path(re->scene, rl->name, rr->sample_nr, str);
1098                         printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
1099                         IMB_exrtile_begin_write(rl->exrhandle, str, 0, rr->rectx, rr->recty, re->partx, re->party);
1100                 }
1101         }
1102 }
1103
1104 /* end write of exr tile file, read back first sample */
1105 void render_result_exr_file_end(Render *re, RenderEngine *engine)
1106 {
1107         RenderResult *rr;
1108         RenderLayer *rl;
1109
1110         for (rr = re->result; rr; rr = rr->next) {
1111                 for (rl = rr->layers.first; rl; rl = rl->next) {
1112                         IMB_exr_close(rl->exrhandle);
1113                         rl->exrhandle = NULL;
1114                 }
1115
1116                 rr->do_exr_tile = false;
1117         }
1118
1119         render_result_free_list(&re->fullresult, re->result);
1120         re->result = NULL;
1121
1122         render_result_exr_file_read_sample(re, 0, engine);
1123 }
1124
1125 /* save part into exr file */
1126 void render_result_exr_file_merge(RenderResult *rr, RenderResult *rrpart, const char *viewname)
1127 {
1128         for (; rr && rrpart; rr = rr->next, rrpart = rrpart->next)
1129                 save_render_result_tile(rr, rrpart, viewname);
1130 }
1131
1132 /* path to temporary exr file */
1133 void render_result_exr_file_path(Scene *scene, const char *layname, int sample, char *filepath)
1134 {
1135         char name[FILE_MAXFILE + MAX_ID_NAME + MAX_ID_NAME + 100];
1136         const char *fi = BLI_path_basename(BKE_main_blendfile_path_from_global());
1137
1138         if (sample == 0) {
1139                 BLI_snprintf(name, sizeof(name), "%s_%s_%s.exr", fi, scene->id.name + 2, layname);
1140         }
1141         else {
1142                 BLI_snprintf(name, sizeof(name), "%s_%s_%s%d.exr", fi, scene->id.name + 2, layname, sample);
1143         }
1144
1145         /* Make name safe for paths, see T43275. */
1146         BLI_filename_make_safe(name);
1147
1148         BLI_make_file_string("/", filepath, BKE_tempdir_session(), name);
1149 }
1150
1151 /* only for temp buffer, makes exact copy of render result */
1152 int render_result_exr_file_read_sample(Render *re, int sample, RenderEngine *engine)
1153 {
1154         RenderLayer *rl;
1155         char str[FILE_MAXFILE + MAX_ID_NAME + MAX_ID_NAME + 100] = "";
1156         bool success = true;
1157
1158         RE_FreeRenderResult(re->result);
1159         re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS, RR_ALL_VIEWS);
1160
1161         for (rl = re->result->layers.first; rl; rl = rl->next) {
1162                 render_result_create_all_passes(engine, re, rl);
1163
1164                 render_result_exr_file_path(re->scene, rl->name, sample, str);
1165                 printf("read exr tmp file: %s\n", str);
1166
1167                 if (!render_result_exr_file_read_path(re->result, rl, str)) {
1168                         printf("cannot read: %s\n", str);
1169                         success = false;
1170                 }
1171         }
1172
1173         return success;
1174 }
1175
1176 /* called for reading temp files, and for external engines */
1177 int render_result_exr_file_read_path(RenderResult *rr, RenderLayer *rl_single, const char *filepath)
1178 {
1179         RenderLayer *rl;
1180         RenderPass *rpass;
1181         void *exrhandle = IMB_exr_get_handle();
1182         int rectx, recty;
1183
1184         if (IMB_exr_begin_read(exrhandle, filepath, &rectx, &recty) == 0) {
1185                 printf("failed being read %s\n", filepath);
1186                 IMB_exr_close(exrhandle);
1187                 return 0;
1188         }
1189
1190         if (rr == NULL || rectx != rr->rectx || recty != rr->recty) {
1191                 if (rr)
1192                         printf("error in reading render result: dimensions don't match\n");
1193                 else
1194                         printf("error in reading render result: NULL result pointer\n");
1195                 IMB_exr_close(exrhandle);
1196                 return 0;
1197         }
1198
1199         for (rl = rr->layers.first; rl; rl = rl->next) {
1200                 if (rl_single && rl_single != rl)
1201                         continue;
1202
1203                 /* passes are allocated in sync */
1204                 for (rpass = rl->passes.first; rpass; rpass = rpass->next) {
1205                         const int xstride = rpass->channels;
1206                         int a;
1207                         char fullname[EXR_PASS_MAXNAME];
1208
1209                         for (a = 0; a < xstride; a++) {
1210                                 set_pass_full_name(fullname, rpass->name, a, rpass->view, rpass->chan_id);
1211                                 IMB_exr_set_channel(exrhandle, rl->name, fullname,
1212                                                     xstride, xstride * rectx, rpass->rect + a);
1213                         }
1214
1215                         set_pass_full_name(rpass->fullname, rpass->name, -1, rpass->view, rpass->chan_id);
1216                 }
1217         }
1218
1219         IMB_exr_read_channels(exrhandle);
1220         IMB_exr_close(exrhandle);
1221
1222         return 1;
1223 }
1224
1225 static void render_result_exr_file_cache_path(Scene *sce, const char *root, char *r_path)
1226 {
1227         char filename_full[FILE_MAX + MAX_ID_NAME + 100], filename[FILE_MAXFILE], dirname[FILE_MAXDIR];
1228         char path_digest[16] = {0};
1229         char path_hexdigest[33];
1230
1231         /* If root is relative, use either current .blend file dir, or temp one if not saved. */
1232         const char *blendfile_path = BKE_main_blendfile_path_from_global();
1233         if (blendfile_path[0] != '\0') {
1234                 BLI_split_dirfile(blendfile_path, dirname, filename, sizeof(dirname), sizeof(filename));
1235                 BLI_path_extension_replace(filename, sizeof(filename), "");  /* strip '.blend' */
1236                 BLI_hash_md5_buffer(blendfile_path, strlen(blendfile_path), path_digest);
1237         }
1238         else {
1239                 BLI_strncpy(dirname, BKE_tempdir_base(), sizeof(dirname));
1240                 BLI_strncpy(filename, "UNSAVED", sizeof(filename));
1241         }
1242         BLI_hash_md5_to_hexdigest(path_digest, path_hexdigest);
1243
1244         /* Default to *non-volatile* tmp dir. */
1245         if (*root == '\0') {
1246                 root = BKE_tempdir_base();
1247         }
1248
1249         BLI_snprintf(filename_full, sizeof(filename_full), "cached_RR_%s_%s_%s.exr",
1250                      filename, sce->id.name + 2, path_hexdigest);
1251         BLI_make_file_string(dirname, r_path, root, filename_full);
1252 }
1253
1254 void render_result_exr_file_cache_write(Render *re)
1255 {
1256         RenderResult *rr = re->result;
1257         char str[FILE_MAXFILE + FILE_MAXFILE + MAX_ID_NAME + 100];
1258         char *root = U.render_cachedir;
1259
1260         render_result_exr_file_cache_path(re->scene, root, str);
1261         printf("Caching exr file, %dx%d, %s\n", rr->rectx, rr->recty, str);
1262
1263         RE_WriteRenderResult(NULL, rr, str, NULL, NULL, -1);
1264 }
1265
1266 /* For cache, makes exact copy of render result */
1267 bool render_result_exr_file_cache_read(Render *re)
1268 {
1269         char str[FILE_MAXFILE + MAX_ID_NAME + MAX_ID_NAME + 100] = "";
1270         char *root = U.render_cachedir;
1271
1272         RE_FreeRenderResult(re->result);
1273         re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS, RR_ALL_VIEWS);
1274
1275         /* First try cache. */
1276         render_result_exr_file_cache_path(re->scene, root, str);
1277
1278         printf("read exr cache file: %s\n", str);
1279         if (!render_result_exr_file_read_path(re->result, NULL, str)) {
1280                 printf("cannot read: %s\n", str);
1281                 return false;
1282         }
1283         return true;
1284 }
1285
1286 /*************************** Combined Pixel Rect *****************************/
1287
1288 ImBuf *render_result_rect_to_ibuf(RenderResult *rr, RenderData *rd, const int view_id)
1289 {
1290         ImBuf *ibuf = IMB_allocImBuf(rr->rectx, rr->recty, rd->im_format.planes, 0);
1291         RenderView *rv = RE_RenderViewGetById(rr, view_id);
1292
1293         /* if not exists, BKE_imbuf_write makes one */
1294         ibuf->rect = (unsigned int *) rv->rect32;
1295         ibuf->rect_float = rv->rectf;
1296         ibuf->zbuf_float = rv->rectz;
1297
1298         /* float factor for random dither, imbuf takes care of it */
1299         ibuf->dither = rd->dither_intensity;
1300
1301         /* prepare to gamma correct to sRGB color space
1302          * note that sequence editor can generate 8bpc render buffers
1303          */
1304         if (ibuf->rect) {
1305                 if (BKE_imtype_valid_depths(rd->im_format.imtype) & (R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_24 | R_IMF_CHAN_DEPTH_32)) {
1306                         if (rd->im_format.depth == R_IMF_CHAN_DEPTH_8) {
1307                                 /* Higher depth bits are supported but not needed for current file output. */
1308                                 ibuf->rect_float = NULL;
1309                         }
1310                         else {
1311                                 IMB_float_from_rect(ibuf);
1312                         }
1313                 }
1314                 else {
1315                         /* ensure no float buffer remained from previous frame */
1316                         ibuf->rect_float = NULL;
1317                 }
1318         }
1319
1320         /* color -> grayscale */
1321         /* editing directly would alter the render view */
1322         if (rd->im_format.planes == R_IMF_PLANES_BW) {
1323                 ImBuf *ibuf_bw = IMB_dupImBuf(ibuf);
1324                 IMB_color_to_bw(ibuf_bw);
1325                 IMB_freeImBuf(ibuf);
1326                 ibuf = ibuf_bw;
1327         }
1328
1329         return ibuf;
1330 }
1331
1332 void RE_render_result_rect_from_ibuf(RenderResult *rr, RenderData *UNUSED(rd), ImBuf *ibuf, const int view_id)
1333 {
1334         RenderView *rv = RE_RenderViewGetById(rr, view_id);
1335
1336         if (ibuf->rect_float) {
1337                 rr->have_combined = true;
1338
1339                 if (!rv->rectf)
1340                         rv->rectf = MEM_mallocN(4 * sizeof(float) * rr->rectx * rr->recty, "render_seq rectf");
1341
1342                 memcpy(rv->rectf, ibuf->rect_float, 4 * sizeof(float) * rr->rectx * rr->recty);
1343
1344                 /* TSK! Since sequence render doesn't free the *rr render result, the old rect32
1345                  * can hang around when sequence render has rendered a 32 bits one before */
1346                 MEM_SAFE_FREE(rv->rect32);
1347         }
1348         else if (ibuf->rect) {
1349                 rr->have_combined = true;
1350
1351                 if (!rv->rect32)
1352                         rv->rect32 = MEM_mallocN(sizeof(int) * rr->rectx * rr->recty, "render_seq rect");
1353
1354                 memcpy(rv->rect32, ibuf->rect, 4 * rr->rectx * rr->recty);
1355
1356                 /* Same things as above, old rectf can hang around from previous render. */
1357                 MEM_SAFE_FREE(rv->rectf);
1358         }
1359 }
1360
1361 void render_result_rect_fill_zero(RenderResult *rr, const int view_id)
1362 {
1363         RenderView *rv = RE_RenderViewGetById(rr, view_id);
1364
1365         if (rv->rectf)
1366                 memset(rv->rectf, 0, 4 * sizeof(float) * rr->rectx * rr->recty);
1367         else if (rv->rect32)
1368                 memset(rv->rect32, 0, 4 * rr->rectx * rr->recty);
1369         else
1370                 rv->rect32 = MEM_callocN(sizeof(int) * rr->rectx * rr->recty, "render_seq rect");
1371 }
1372
1373 void render_result_rect_get_pixels(RenderResult *rr, unsigned int *rect, int rectx, int recty,
1374                                    const ColorManagedViewSettings *view_settings, const ColorManagedDisplaySettings *display_settings,
1375                                    const int view_id)
1376 {
1377         RenderView *rv = RE_RenderViewGetById(rr, view_id);
1378
1379         if (rv->rect32)
1380                 memcpy(rect, rv->rect32, sizeof(int) * rr->rectx * rr->recty);
1381         else if (rv->rectf)
1382                 IMB_display_buffer_transform_apply((unsigned char *) rect, rv->rectf, rr->rectx, rr->recty, 4,
1383                                                    view_settings, display_settings, true);
1384         else
1385                 /* else fill with black */
1386                 memset(rect, 0, sizeof(int) * rectx * recty);
1387 }
1388
1389
1390 /*************************** multiview functions *****************************/
1391
1392 bool RE_HasCombinedLayer(RenderResult *res)
1393 {
1394         RenderView *rv;
1395
1396         if (res == NULL)
1397                 return false;
1398
1399         rv = res->views.first;
1400         if (rv == NULL)
1401                 return false;
1402
1403         return (rv->rect32 || rv->rectf);
1404 }
1405
1406 bool RE_HasFloatPixels(RenderResult *res)
1407 {
1408         RenderView *rview;
1409
1410         for (rview = res->views.first; rview; rview = rview->next) {
1411                 if (rview->rect32 && !rview->rectf) {
1412                         return false;
1413                 }
1414         }
1415
1416         return true;
1417 }
1418
1419 bool RE_RenderResult_is_stereo(RenderResult *res)
1420 {
1421         if (! BLI_findstring(&res->views, STEREO_LEFT_NAME, offsetof(RenderView, name)))
1422                 return false;
1423
1424         if (! BLI_findstring(&res->views, STEREO_RIGHT_NAME, offsetof(RenderView, name)))
1425                 return false;
1426
1427         return true;
1428 }
1429
1430 RenderView *RE_RenderViewGetById(RenderResult *res, const int view_id)
1431 {
1432         RenderView *rv = BLI_findlink(&res->views, view_id);
1433         BLI_assert(res->views.first);
1434         return rv ? rv : res->views.first;
1435 }
1436
1437 RenderView *RE_RenderViewGetByName(RenderResult *res, const char *viewname)
1438 {
1439         RenderView *rv = BLI_findstring(&res->views, viewname, offsetof(RenderView, name));
1440         BLI_assert(res->views.first);
1441         return rv ? rv : res->views.first;
1442 }
1443
1444 static RenderPass *duplicate_render_pass(RenderPass *rpass)
1445 {
1446         RenderPass *new_rpass = MEM_mallocN(sizeof(RenderPass), "new render pass");
1447         *new_rpass = *rpass;
1448         new_rpass->next = new_rpass->prev = NULL;
1449         if (new_rpass->rect != NULL) {
1450                 new_rpass->rect = MEM_dupallocN(new_rpass->rect);
1451         }
1452         return new_rpass;
1453 }
1454
1455 static RenderLayer *duplicate_render_layer(RenderLayer *rl)
1456 {
1457         RenderLayer *new_rl = MEM_mallocN(sizeof(RenderLayer), "new render layer");
1458         *new_rl = *rl;
1459         new_rl->next = new_rl->prev = NULL;
1460         new_rl->passes.first = new_rl->passes.last = NULL;
1461         new_rl->exrhandle = NULL;
1462         if (new_rl->acolrect != NULL) {
1463                 new_rl->acolrect = MEM_dupallocN(new_rl->acolrect);
1464         }
1465         if (new_rl->scolrect != NULL) {
1466                 new_rl->scolrect = MEM_dupallocN(new_rl->scolrect);
1467         }
1468         if (new_rl->display_buffer != NULL) {
1469                 new_rl->display_buffer = MEM_dupallocN(new_rl->display_buffer);
1470         }
1471         for (RenderPass *rpass = rl->passes.first; rpass != NULL; rpass = rpass->next) {
1472                 RenderPass  *new_rpass = duplicate_render_pass(rpass);
1473                 BLI_addtail(&new_rl->passes, new_rpass);
1474         }
1475         return new_rl;
1476 }
1477
1478 static RenderView *duplicate_render_view(RenderView *rview)
1479 {
1480         RenderView *new_rview = MEM_mallocN(sizeof(RenderView), "new render view");
1481         *new_rview = *rview;
1482         if (new_rview->rectf != NULL) {
1483                 new_rview->rectf = MEM_dupallocN(new_rview->rectf);
1484         }
1485         if (new_rview->rectz != NULL) {
1486                 new_rview->rectz = MEM_dupallocN(new_rview->rectz);
1487         }
1488         if (new_rview->rect32 != NULL) {
1489                 new_rview->rect32 = MEM_dupallocN(new_rview->rect32);
1490         }
1491         return new_rview;
1492 }
1493
1494 RenderResult *RE_DuplicateRenderResult(RenderResult *rr)
1495 {
1496         RenderResult *new_rr = MEM_mallocN(sizeof(RenderResult), "new duplicated render result");
1497         *new_rr = *rr;
1498         new_rr->next = new_rr->prev = NULL;
1499         new_rr->layers.first = new_rr->layers.last = NULL;
1500         new_rr->views.first = new_rr->views.last = NULL;
1501         for (RenderLayer *rl = rr->layers.first; rl != NULL; rl = rl->next) {
1502                 RenderLayer *new_rl = duplicate_render_layer(rl);
1503                 BLI_addtail(&new_rr->layers, new_rl);
1504         }
1505         for (RenderView *rview = rr->views.first; rview != NULL; rview = rview->next) {
1506                 RenderView *new_rview = duplicate_render_view(rview);
1507                 BLI_addtail(&new_rr->views, new_rview);
1508         }
1509         if (new_rr->rect32 != NULL) {
1510                 new_rr->rect32 = MEM_dupallocN(new_rr->rect32);
1511         }
1512         if (new_rr->rectf != NULL) {
1513                 new_rr->rectf = MEM_dupallocN(new_rr->rectf);
1514         }
1515         if (new_rr->rectz != NULL) {
1516                 new_rr->rectz = MEM_dupallocN(new_rr->rectz);
1517         }
1518         new_rr->stamp_data = MEM_dupallocN(new_rr->stamp_data);
1519         return new_rr;
1520 }