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