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