fix for bug with render slots - where the menus wouldnt only show layers from the...
[blender.git] / source / blender / blenkernel / intern / image.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) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, 2006, full recode
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/image.c
27  *  \ingroup bke
28  */
29
30
31 #include <stdio.h>
32 #include <string.h>
33 #include <fcntl.h>
34 #include <math.h>
35 #ifndef WIN32
36 #include <unistd.h>
37 #else
38 #include <io.h>
39 #endif
40
41 #include <time.h>
42
43 #ifdef _WIN32
44 #define open _open
45 #define close _close
46 #endif
47
48 #include "MEM_guardedalloc.h"
49
50 #include "IMB_imbuf_types.h"
51 #include "IMB_imbuf.h"
52
53 #ifdef WITH_OPENEXR
54 #include "intern/openexr/openexr_multi.h"
55 #endif
56
57 #include "DNA_packedFile_types.h"
58 #include "DNA_scene_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_camera_types.h"
61 #include "DNA_sequence_types.h"
62 #include "DNA_userdef_types.h"
63 #include "DNA_brush_types.h"
64 #include "DNA_mesh_types.h"
65 #include "DNA_meshdata_types.h"
66
67 #include "BLI_blenlib.h"
68 #include "BLI_threads.h"
69 #include "BLI_utildefines.h"
70 #include "BLI_bpath.h"
71
72 #include "BKE_bmfont.h"
73 #include "BKE_global.h"
74 #include "BKE_icons.h"
75 #include "BKE_image.h"
76 #include "BKE_library.h"
77 #include "BKE_main.h"
78 #include "BKE_packedFile.h"
79 #include "BKE_scene.h"
80 #include "BKE_node.h"
81 #include "BKE_sequencer.h" /* seq_foreground_frame_get() */
82 #include "BKE_utildefines.h"
83
84 #include "BLF_api.h"
85
86 #include "PIL_time.h"
87
88 #include "RE_pipeline.h"
89
90 #include "GPU_draw.h"
91
92 #include "BLO_sys_types.h" // for intptr_t support
93
94 /* for image user iteration */
95 #include "DNA_node_types.h"
96 #include "DNA_space_types.h"
97 #include "DNA_screen_types.h"
98 #include "DNA_view3d_types.h"
99
100 #include "WM_api.h"
101
102 /* max int, to indicate we don't store sequences in ibuf */
103 #define IMA_NO_INDEX    0x7FEFEFEF
104
105 /* quick lookup: supports 1 million frames, thousand passes */
106 #define IMA_MAKE_INDEX(frame, index)    ((frame) << 10) + index
107 #define IMA_INDEX_FRAME(index)          (index >> 10)
108 #define IMA_INDEX_PASS(index)           (index & ~1023)
109
110 /* ******** IMAGE PROCESSING ************* */
111
112 static void de_interlace_ng(struct ImBuf *ibuf) /* neogeo fields */
113 {
114         struct ImBuf *tbuf1, *tbuf2;
115
116         if (ibuf == NULL) return;
117         if (ibuf->flags & IB_fields) return;
118         ibuf->flags |= IB_fields;
119
120         if (ibuf->rect) {
121                 /* make copies */
122                 tbuf1 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
123                 tbuf2 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
124
125                 ibuf->x *= 2;
126
127                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
128                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
129
130                 ibuf->x /= 2;
131                 IMB_rectcpy(ibuf, tbuf1, 0, 0, 0, 0, tbuf1->x, tbuf1->y);
132                 IMB_rectcpy(ibuf, tbuf2, 0, tbuf2->y, 0, 0, tbuf2->x, tbuf2->y);
133
134                 IMB_freeImBuf(tbuf1);
135                 IMB_freeImBuf(tbuf2);
136         }
137         ibuf->y /= 2;
138 }
139
140 static void de_interlace_st(struct ImBuf *ibuf) /* standard fields */
141 {
142         struct ImBuf *tbuf1, *tbuf2;
143
144         if (ibuf == NULL) return;
145         if (ibuf->flags & IB_fields) return;
146         ibuf->flags |= IB_fields;
147
148         if (ibuf->rect) {
149                 /* make copies */
150                 tbuf1 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, IB_rect);
151                 tbuf2 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, IB_rect);
152
153                 ibuf->x *= 2;
154
155                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
156                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
157
158                 ibuf->x /= 2;
159                 IMB_rectcpy(ibuf, tbuf2, 0, 0, 0, 0, tbuf2->x, tbuf2->y);
160                 IMB_rectcpy(ibuf, tbuf1, 0, tbuf2->y, 0, 0, tbuf1->x, tbuf1->y);
161
162                 IMB_freeImBuf(tbuf1);
163                 IMB_freeImBuf(tbuf2);
164         }
165         ibuf->y /= 2;
166 }
167
168 void BKE_image_de_interlace(Image *ima, int odd)
169 {
170         ImBuf *ibuf = BKE_image_get_ibuf(ima, NULL);
171         if (ibuf) {
172                 if (odd)
173                         de_interlace_st(ibuf);
174                 else
175                         de_interlace_ng(ibuf);
176         }
177 }
178
179 /* ***************** ALLOC & FREE, DATA MANAGING *************** */
180
181 static void image_free_buffers(Image *ima)
182 {
183         ImBuf *ibuf;
184
185         while ((ibuf = ima->ibufs.first)) {
186                 BLI_remlink(&ima->ibufs, ibuf);
187
188                 if (ibuf->userdata) {
189                         MEM_freeN(ibuf->userdata);
190                         ibuf->userdata = NULL;
191                 }
192                 IMB_freeImBuf(ibuf);
193         }
194
195         if (ima->anim) IMB_free_anim(ima->anim);
196         ima->anim = NULL;
197
198         if (ima->rr) {
199                 RE_FreeRenderResult(ima->rr);
200                 ima->rr = NULL;
201         }
202
203         GPU_free_image(ima);
204
205         ima->ok = IMA_OK;
206 }
207
208 /* called by library too, do not free ima itself */
209 void BKE_image_free(Image *ima)
210 {
211         int a;
212
213         image_free_buffers(ima);
214         if (ima->packedfile) {
215                 freePackedFile(ima->packedfile);
216                 ima->packedfile = NULL;
217         }
218         BKE_icon_delete(&ima->id);
219         ima->id.icon_id = 0;
220
221         BKE_previewimg_free(&ima->preview);
222
223         for (a = 0; a < IMA_MAX_RENDER_SLOT; a++) {
224                 if (ima->renders[a]) {
225                         RE_FreeRenderResult(ima->renders[a]);
226                         ima->renders[a] = NULL;
227                 }
228         }
229 }
230
231 /* only image block itself */
232 static Image *image_alloc(const char *name, short source, short type)
233 {
234         Image *ima;
235
236         ima = BKE_libblock_alloc(&G.main->image, ID_IM, name);
237         if (ima) {
238                 ima->ok = IMA_OK;
239
240                 ima->xrep = ima->yrep = 1;
241                 ima->aspx = ima->aspy = 1.0;
242                 ima->gen_x = 1024; ima->gen_y = 1024;
243                 ima->gen_type = 1;   /* no defines yet? */
244
245                 ima->source = source;
246                 ima->type = type;
247         }
248         return ima;
249 }
250
251 /* get the ibuf from an image cache, local use here only */
252 static ImBuf *image_get_ibuf(Image *ima, int index, int frame)
253 {
254         /* this function is intended to be thread safe. with IMA_NO_INDEX this
255          * should be OK, but when iterating over the list this is more tricky
256          * */
257         if (index == IMA_NO_INDEX)
258                 return ima->ibufs.first;
259         else {
260                 ImBuf *ibuf;
261
262                 index = IMA_MAKE_INDEX(frame, index);
263                 for (ibuf = ima->ibufs.first; ibuf; ibuf = ibuf->next)
264                         if (ibuf->index == index)
265                                 return ibuf;
266
267                 return NULL;
268         }
269 }
270
271 /* no ima->ibuf anymore, but listbase */
272 static void image_remove_ibuf(Image *ima, ImBuf *ibuf)
273 {
274         if (ibuf) {
275                 BLI_remlink(&ima->ibufs, ibuf);
276                 IMB_freeImBuf(ibuf);
277         }
278 }
279
280
281 /* no ima->ibuf anymore, but listbase */
282 static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
283 {
284         if (ibuf) {
285                 ImBuf *link;
286
287                 if (index != IMA_NO_INDEX)
288                         index = IMA_MAKE_INDEX(frame, index);
289
290                 /* insert based on index */
291                 for (link = ima->ibufs.first; link; link = link->next)
292                         if (link->index >= index)
293                                 break;
294
295                 ibuf->index = index;
296                 if (ima->flag & IMA_CM_PREDIVIDE)
297                         ibuf->flags |= IB_cm_predivide;
298                 else
299                         ibuf->flags &= ~IB_cm_predivide;
300
301                 /* this function accepts (link == NULL) */
302                 BLI_insertlinkbefore(&ima->ibufs, link, ibuf);
303
304                 /* now we don't want copies? */
305                 if (link && ibuf->index == link->index)
306                         image_remove_ibuf(ima, link);
307         }
308 }
309
310 /* empty image block, of similar type and filename */
311 Image *BKE_image_copy(Image *ima)
312 {
313         Image *nima = image_alloc(ima->id.name + 2, ima->source, ima->type);
314
315         BLI_strncpy(nima->name, ima->name, sizeof(ima->name));
316
317         nima->flag = ima->flag;
318         nima->tpageflag = ima->tpageflag;
319
320         nima->gen_x = ima->gen_x;
321         nima->gen_y = ima->gen_y;
322         nima->gen_type = ima->gen_type;
323
324         nima->animspeed = ima->animspeed;
325
326         nima->aspx = ima->aspx;
327         nima->aspy = ima->aspy;
328
329         return nima;
330 }
331
332 static void extern_local_image(Image *UNUSED(ima))
333 {
334         /* Nothing to do: images don't link to other IDs. This function exists to
335          * match id_make_local pattern. */
336 }
337
338 void BKE_image_make_local(struct Image *ima)
339 {
340         Main *bmain = G.main;
341         Tex *tex;
342         Brush *brush;
343         Mesh *me;
344         int is_local = FALSE, is_lib = FALSE;
345
346         /* - only lib users: do nothing
347          * - only local users: set flag
348          * - mixed: make copy
349          */
350
351         if (ima->id.lib == NULL) return;
352
353         /* Can't take short cut here: must check meshes at least because of bogus
354          * texface ID refs. - z0r */
355 #if 0
356         if (ima->id.us == 1) {
357                 id_clear_lib_data(bmain, &ima->id);
358                 extern_local_image(ima);
359                 return;
360         }
361 #endif
362
363         for (tex = bmain->tex.first; tex; tex = tex->id.next) {
364                 if (tex->ima == ima) {
365                         if (tex->id.lib) is_lib = TRUE;
366                         else is_local = TRUE;
367                 }
368         }
369         for (brush = bmain->brush.first; brush; brush = brush->id.next) {
370                 if (brush->clone.image == ima) {
371                         if (brush->id.lib) is_lib = TRUE;
372                         else is_local = TRUE;
373                 }
374         }
375         for (me = bmain->mesh.first; me; me = me->id.next) {
376                 if (me->mtface) {
377                         MTFace *tface;
378                         int a, i;
379
380                         for (i = 0; i < me->fdata.totlayer; i++) {
381                                 if (me->fdata.layers[i].type == CD_MTFACE) {
382                                         tface = (MTFace *)me->fdata.layers[i].data;
383
384                                         for (a = 0; a < me->totface; a++, tface++) {
385                                                 if (tface->tpage == ima) {
386                                                         if (me->id.lib) is_lib = TRUE;
387                                                         else is_local = TRUE;
388                                                 }
389                                         }
390                                 }
391                         }
392                 }
393
394                 if (me->mtpoly) {
395                         MTexPoly *mtpoly;
396                         int a, i;
397
398                         for (i = 0; i < me->pdata.totlayer; i++) {
399                                 if (me->pdata.layers[i].type == CD_MTEXPOLY) {
400                                         mtpoly = (MTexPoly *)me->pdata.layers[i].data;
401
402                                         for (a = 0; a < me->totpoly; a++, mtpoly++) {
403                                                 if (mtpoly->tpage == ima) {
404                                                         if (me->id.lib) is_lib = TRUE;
405                                                         else is_local = TRUE;
406                                                 }
407                                         }
408                                 }
409                         }
410                 }
411
412         }
413
414         if (is_local && is_lib == FALSE) {
415                 id_clear_lib_data(bmain, &ima->id);
416                 extern_local_image(ima);
417         }
418         else if (is_local && is_lib) {
419                 Image *ima_new = BKE_image_copy(ima);
420
421                 ima_new->id.us = 0;
422
423                 /* Remap paths of new ID using old library as base. */
424                 BKE_id_lib_local_paths(bmain, ima->id.lib, &ima_new->id);
425
426                 tex = bmain->tex.first;
427                 while (tex) {
428                         if (tex->id.lib == NULL) {
429                                 if (tex->ima == ima) {
430                                         tex->ima = ima_new;
431                                         ima_new->id.us++;
432                                         ima->id.us--;
433                                 }
434                         }
435                         tex = tex->id.next;
436                 }
437                 brush = bmain->brush.first;
438                 while (brush) {
439                         if (brush->id.lib == NULL) {
440                                 if (brush->clone.image == ima) {
441                                         brush->clone.image = ima_new;
442                                         ima_new->id.us++;
443                                         ima->id.us--;
444                                 }
445                         }
446                         brush = brush->id.next;
447                 }
448                 /* Transfer references in texfaces. Texfaces don't add to image ID
449                  * user count *unless* there are no other users. See
450                  * readfile.c:lib_link_mtface. */
451                 me = bmain->mesh.first;
452                 while (me) {
453                         if (me->mtface) {
454                                 MTFace *tface;
455                                 int a, i;
456
457                                 for (i = 0; i < me->fdata.totlayer; i++) {
458                                         if (me->fdata.layers[i].type == CD_MTFACE) {
459                                                 tface = (MTFace *)me->fdata.layers[i].data;
460
461                                                 for (a = 0; a < me->totface; a++, tface++) {
462                                                         if (tface->tpage == ima) {
463                                                                 tface->tpage = ima_new;
464                                                                 if (ima_new->id.us == 0) {
465                                                                         tface->tpage->id.us = 1;
466                                                                 }
467                                                                 id_lib_extern((ID *)ima_new);
468                                                         }
469                                                 }
470                                         }
471                                 }
472                         }
473
474                         if (me->mtpoly) {
475                                 MTexPoly *mtpoly;
476                                 int a, i;
477
478                                 for (i = 0; i < me->pdata.totlayer; i++) {
479                                         if (me->pdata.layers[i].type == CD_MTEXPOLY) {
480                                                 mtpoly = (MTexPoly *)me->pdata.layers[i].data;
481
482                                                 for (a = 0; a < me->totpoly; a++, mtpoly++) {
483                                                         if (mtpoly->tpage == ima) {
484                                                                 mtpoly->tpage = ima_new;
485                                                                 if (ima_new->id.us == 0) {
486                                                                         mtpoly->tpage->id.us = 1;
487                                                                 }
488                                                                 id_lib_extern((ID *)ima_new);
489                                                         }
490                                                 }
491                                         }
492                                 }
493                         }
494
495                         me = me->id.next;
496                 }
497         }
498 }
499
500 void BKE_image_merge(Image *dest, Image *source)
501 {
502         ImBuf *ibuf;
503
504         /* sanity check */
505         if (dest && source && dest != source) {
506
507                 while ((ibuf = source->ibufs.first)) {
508                         BLI_remlink(&source->ibufs, ibuf);
509                         image_assign_ibuf(dest, ibuf, IMA_INDEX_PASS(ibuf->index), IMA_INDEX_FRAME(ibuf->index));
510                 }
511
512                 BKE_libblock_free(&G.main->image, source);
513         }
514 }
515
516 /* note, we could be clever and scale all imbuf's but since some are mipmaps its not so simple */
517 int BKE_image_scale(Image *image, int width, int height)
518 {
519         ImBuf *ibuf;
520         void *lock;
521
522         ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
523
524         if (ibuf) {
525                 IMB_scaleImBuf(ibuf, width, height);
526                 ibuf->userflags |= IB_BITMAPDIRTY;
527         }
528
529         BKE_image_release_ibuf(image, lock);
530
531         return (ibuf != NULL);
532 }
533
534 Image *BKE_image_load(const char *filepath)
535 {
536         Image *ima;
537         int file, len;
538         const char *libname;
539         char str[FILE_MAX];
540
541         BLI_strncpy(str, filepath, sizeof(str));
542         BLI_path_abs(str, G.main->name);
543
544         /* exists? */
545         file = BLI_open(str, O_BINARY | O_RDONLY, 0);
546         if (file == -1) return NULL;
547         close(file);
548
549         /* create a short library name */
550         len = strlen(filepath);
551
552         while (len > 0 && filepath[len - 1] != '/' && filepath[len - 1] != '\\') len--;
553         libname = filepath + len;
554
555         ima = image_alloc(libname, IMA_SRC_FILE, IMA_TYPE_IMAGE);
556         BLI_strncpy(ima->name, filepath, sizeof(ima->name));
557
558         if (BLI_testextensie_array(filepath, imb_ext_movie))
559                 ima->source = IMA_SRC_MOVIE;
560
561         return ima;
562 }
563
564 /* checks if image was already loaded, then returns same image */
565 /* otherwise creates new. */
566 /* does not load ibuf itself */
567 /* pass on optional frame for #name images */
568 Image *BKE_image_load_exists(const char *filepath)
569 {
570         Image *ima;
571         char str[FILE_MAX], strtest[FILE_MAX];
572
573         BLI_strncpy(str, filepath, sizeof(str));
574         BLI_path_abs(str, G.main->name);
575
576         /* first search an identical image */
577         for (ima = G.main->image.first; ima; ima = ima->id.next) {
578                 if (ima->source != IMA_SRC_VIEWER && ima->source != IMA_SRC_GENERATED) {
579                         BLI_strncpy(strtest, ima->name, sizeof(ima->name));
580                         BLI_path_abs(strtest, G.main->name);
581
582                         if (BLI_path_cmp(strtest, str) == 0) {
583                                 if (ima->anim == NULL || ima->id.us == 0) {
584                                         BLI_strncpy(ima->name, filepath, sizeof(ima->name));    /* for stringcode */
585                                         ima->id.us++;                                       /* officially should not, it doesn't link here! */
586                                         if (ima->ok == 0)
587                                                 ima->ok = IMA_OK;
588                                         /* RETURN! */
589                                         return ima;
590                                 }
591                         }
592                 }
593         }
594
595         return BKE_image_load(filepath);
596 }
597
598 static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
599 {
600         ImBuf *ibuf;
601         unsigned char *rect = NULL;
602         float *rect_float = NULL;
603
604         if (floatbuf) {
605                 ibuf = IMB_allocImBuf(width, height, depth, IB_rectfloat);
606                 rect_float = ibuf->rect_float;
607                 ibuf->profile = IB_PROFILE_LINEAR_RGB;
608         }
609         else {
610                 ibuf = IMB_allocImBuf(width, height, depth, IB_rect);
611                 rect = (unsigned char *)ibuf->rect;
612                 ibuf->profile = IB_PROFILE_SRGB;
613         }
614
615         BLI_strncpy(ibuf->name, name, sizeof(ibuf->name));
616         ibuf->userflags |= IB_BITMAPDIRTY;
617
618         switch (uvtestgrid) {
619                 case 1:
620                         BKE_image_buf_fill_checker(rect, rect_float, width, height);
621                         break;
622                 case 2:
623                         BKE_image_buf_fill_checker_color(rect, rect_float, width, height);
624                         break;
625                 default:
626                         BKE_image_buf_fill_color(rect, rect_float, width, height, color);
627         }
628
629         return ibuf;
630 }
631
632 /* adds new image block, creates ImBuf and initializes color */
633 Image *BKE_image_add_generated(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
634 {
635         /* on save, type is changed to FILE in editsima.c */
636         Image *ima = image_alloc(name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
637
638         if (ima) {
639                 ImBuf *ibuf;
640
641                 /* BLI_strncpy(ima->name, name, FILE_MAX); */ /* don't do this, this writes in ain invalid filepath! */
642                 ima->gen_x = width;
643                 ima->gen_y = height;
644                 ima->gen_type = uvtestgrid;
645                 ima->gen_flag |= (floatbuf ? IMA_GEN_FLOAT : 0);
646
647                 ibuf = add_ibuf_size(width, height, ima->name, depth, floatbuf, uvtestgrid, color);
648                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
649
650                 ima->ok = IMA_OK_LOADED;
651         }
652
653         return ima;
654 }
655
656 /* creates an image image owns the imbuf passed */
657 Image *BKE_image_add_from_imbuf(ImBuf *ibuf)
658 {
659         /* on save, type is changed to FILE in editsima.c */
660         Image *ima;
661
662         ima = image_alloc(BLI_path_basename(ibuf->name), IMA_SRC_FILE, IMA_TYPE_IMAGE);
663
664         if (ima) {
665                 BLI_strncpy(ima->name, ibuf->name, FILE_MAX);
666                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
667                 ima->ok = IMA_OK_LOADED;
668         }
669
670         return ima;
671 }
672
673 /* packs rect from memory as PNG */
674 void BKE_image_memorypack(Image *ima)
675 {
676         ImBuf *ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
677
678         if (ibuf == NULL)
679                 return;
680         if (ima->packedfile) {
681                 freePackedFile(ima->packedfile);
682                 ima->packedfile = NULL;
683         }
684
685         ibuf->ftype = PNG;
686         ibuf->planes = R_IMF_PLANES_RGBA;
687
688         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
689         if (ibuf->encodedbuffer == NULL) {
690                 printf("memory save for pack error\n");
691         }
692         else {
693                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
694
695                 pf->data = ibuf->encodedbuffer;
696                 pf->size = ibuf->encodedsize;
697                 ima->packedfile = pf;
698                 ibuf->encodedbuffer = NULL;
699                 ibuf->encodedsize = 0;
700                 ibuf->userflags &= ~IB_BITMAPDIRTY;
701
702                 if (ima->source == IMA_SRC_GENERATED) {
703                         ima->source = IMA_SRC_FILE;
704                         ima->type = IMA_TYPE_IMAGE;
705                 }
706         }
707 }
708
709 void BKE_image_tag_time(Image *ima)
710 {
711         if (ima)
712                 ima->lastused = (int)PIL_check_seconds_timer();
713 }
714
715 #if 0
716 static void tag_all_images_time()
717 {
718         Image *ima;
719         int ctime = (int)PIL_check_seconds_timer();
720
721         ima = G.main->image.first;
722         while (ima) {
723                 if (ima->bindcode || ima->repbind || ima->ibufs.first) {
724                         ima->lastused = ctime;
725                 }
726         }
727 }
728 #endif
729
730 void free_old_images(void)
731 {
732         Image *ima;
733         static int lasttime = 0;
734         int ctime = (int)PIL_check_seconds_timer();
735
736         /*
737          * Run garbage collector once for every collecting period of time
738          * if textimeout is 0, that's the option to NOT run the collector
739          */
740         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
741                 return;
742
743         /* of course not! */
744         if (G.is_rendering)
745                 return;
746
747         lasttime = ctime;
748
749         ima = G.main->image.first;
750         while (ima) {
751                 if ((ima->flag & IMA_NOCOLLECT) == 0 && ctime - ima->lastused > U.textimeout) {
752                         /* If it's in GL memory, deallocate and set time tag to current time
753                          * This gives textures a "second chance" to be used before dying. */
754                         if (ima->bindcode || ima->repbind) {
755                                 GPU_free_image(ima);
756                                 ima->lastused = ctime;
757                         }
758                         /* Otherwise, just kill the buffers */
759                         else if (ima->ibufs.first) {
760                                 image_free_buffers(ima);
761                         }
762                 }
763                 ima = ima->id.next;
764         }
765 }
766
767 static uintptr_t image_mem_size(Image *ima)
768 {
769         ImBuf *ibuf, *ibufm;
770         int level;
771         uintptr_t size = 0;
772
773         size = 0;
774
775         /* viewers have memory depending on other rules, has no valid rect pointer */
776         if (ima->source == IMA_SRC_VIEWER)
777                 return 0;
778
779         for (ibuf = ima->ibufs.first; ibuf; ibuf = ibuf->next) {
780                 if (ibuf->rect) size += MEM_allocN_len(ibuf->rect);
781                 else if (ibuf->rect_float) size += MEM_allocN_len(ibuf->rect_float);
782
783                 for (level = 0; level < IB_MIPMAP_LEVELS; level++) {
784                         ibufm = ibuf->mipmap[level];
785                         if (ibufm) {
786                                 if (ibufm->rect) size += MEM_allocN_len(ibufm->rect);
787                                 else if (ibufm->rect_float) size += MEM_allocN_len(ibufm->rect_float);
788                         }
789                 }
790         }
791
792         return size;
793 }
794
795 void BKE_image_print_memlist(void)
796 {
797         Image *ima;
798         uintptr_t size, totsize = 0;
799
800         for (ima = G.main->image.first; ima; ima = ima->id.next)
801                 totsize += image_mem_size(ima);
802
803         printf("\ntotal image memory len: %.3f MB\n", (double)totsize / (double)(1024 * 1024));
804
805         for (ima = G.main->image.first; ima; ima = ima->id.next) {
806                 size = image_mem_size(ima);
807
808                 if (size)
809                         printf("%s len: %.3f MB\n", ima->id.name + 2, (double)size / (double)(1024 * 1024));
810         }
811 }
812
813 void BKE_image_free_all_textures(void)
814 {
815         Tex *tex;
816         Image *ima;
817         /* unsigned int totsize = 0; */
818
819         for (ima = G.main->image.first; ima; ima = ima->id.next)
820                 ima->id.flag &= ~LIB_DOIT;
821
822         for (tex = G.main->tex.first; tex; tex = tex->id.next)
823                 if (tex->ima)
824                         tex->ima->id.flag |= LIB_DOIT;
825
826         for (ima = G.main->image.first; ima; ima = ima->id.next) {
827                 if (ima->ibufs.first && (ima->id.flag & LIB_DOIT)) {
828                         ImBuf *ibuf;
829
830                         for (ibuf = ima->ibufs.first; ibuf; ibuf = ibuf->next) {
831                                 /* escape when image is painted on */
832                                 if (ibuf->userflags & IB_BITMAPDIRTY)
833                                         break;
834
835 #if 0
836                                 if (ibuf->mipmap[0])
837                                         totsize += 1.33 * ibuf->x * ibuf->y * 4;
838                                 else
839                                         totsize += ibuf->x * ibuf->y * 4;
840 #endif
841                         }
842                         if (ibuf == NULL)
843                                 image_free_buffers(ima);
844                 }
845         }
846         /* printf("freed total %d MB\n", totsize/(1024*1024)); */
847 }
848
849 /* except_frame is weak, only works for seqs without offset... */
850 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
851 {
852         ImBuf *ibuf, *nbuf;
853
854         for (ibuf = ima->ibufs.first; ibuf; ibuf = nbuf) {
855                 nbuf = ibuf->next;
856                 if (ibuf->userflags & IB_BITMAPDIRTY)
857                         continue;
858                 if (ibuf->index == IMA_NO_INDEX)
859                         continue;
860                 if (except_frame != IMA_INDEX_FRAME(ibuf->index)) {
861                         BLI_remlink(&ima->ibufs, ibuf);
862
863                         if (ibuf->userdata) {
864                                 MEM_freeN(ibuf->userdata);
865                                 ibuf->userdata = NULL;
866                         }
867                         IMB_freeImBuf(ibuf);
868                 }
869         }
870 }
871
872 void BKE_image_all_free_anim_ibufs(int cfra)
873 {
874         Image *ima;
875
876         for (ima = G.main->image.first; ima; ima = ima->id.next)
877                 if (ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE))
878                         BKE_image_free_anim_ibufs(ima, cfra);
879 }
880
881
882 /* *********** READ AND WRITE ************** */
883
884 int BKE_imtype_to_ftype(const char imtype)
885 {
886         if (imtype == R_IMF_IMTYPE_TARGA)
887                 return TGA;
888         else if (imtype == R_IMF_IMTYPE_RAWTGA)
889                 return RAWTGA;
890         else if (imtype == R_IMF_IMTYPE_IRIS)
891                 return IMAGIC;
892 #ifdef WITH_HDR
893         else if (imtype == R_IMF_IMTYPE_RADHDR)
894                 return RADHDR;
895 #endif
896         else if (imtype == R_IMF_IMTYPE_PNG)
897                 return PNG;
898 #ifdef WITH_DDS
899         else if (imtype == R_IMF_IMTYPE_DDS)
900                 return DDS;
901 #endif
902         else if (imtype == R_IMF_IMTYPE_BMP)
903                 return BMP;
904 #ifdef WITH_TIFF
905         else if (imtype == R_IMF_IMTYPE_TIFF)
906                 return TIF;
907 #endif
908         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER)
909                 return OPENEXR;
910 #ifdef WITH_CINEON
911         else if (imtype == R_IMF_IMTYPE_CINEON)
912                 return CINEON;
913         else if (imtype == R_IMF_IMTYPE_DPX)
914                 return DPX;
915 #endif
916 #ifdef WITH_OPENJPEG
917         else if (imtype == R_IMF_IMTYPE_JP2)
918                 return JP2;
919 #endif
920         else
921                 return JPG | 90;
922 }
923
924 char BKE_ftype_to_imtype(const int ftype)
925 {
926         if (ftype == 0)
927                 return R_IMF_IMTYPE_TARGA;
928         else if (ftype == IMAGIC)
929                 return R_IMF_IMTYPE_IRIS;
930 #ifdef WITH_HDR
931         else if (ftype & RADHDR)
932                 return R_IMF_IMTYPE_RADHDR;
933 #endif
934         else if (ftype & PNG)
935                 return R_IMF_IMTYPE_PNG;
936 #ifdef WITH_DDS
937         else if (ftype & DDS)
938                 return R_IMF_IMTYPE_DDS;
939 #endif
940         else if (ftype & BMP)
941                 return R_IMF_IMTYPE_BMP;
942 #ifdef WITH_TIFF
943         else if (ftype & TIF)
944                 return R_IMF_IMTYPE_TIFF;
945 #endif
946         else if (ftype & OPENEXR)
947                 return R_IMF_IMTYPE_OPENEXR;
948 #ifdef WITH_CINEON
949         else if (ftype & CINEON)
950                 return R_IMF_IMTYPE_CINEON;
951         else if (ftype & DPX)
952                 return R_IMF_IMTYPE_DPX;
953 #endif
954         else if (ftype & TGA)
955                 return R_IMF_IMTYPE_TARGA;
956         else if (ftype & RAWTGA)
957                 return R_IMF_IMTYPE_RAWTGA;
958 #ifdef WITH_OPENJPEG
959         else if (ftype & JP2)
960                 return R_IMF_IMTYPE_JP2;
961 #endif
962         else
963                 return R_IMF_IMTYPE_JPEG90;
964 }
965
966
967 int BKE_imtype_is_movie(const char imtype)
968 {
969         switch (imtype) {
970                 case R_IMF_IMTYPE_AVIRAW:
971                 case R_IMF_IMTYPE_AVIJPEG:
972                 case R_IMF_IMTYPE_QUICKTIME:
973                 case R_IMF_IMTYPE_FFMPEG:
974                 case R_IMF_IMTYPE_H264:
975                 case R_IMF_IMTYPE_THEORA:
976                 case R_IMF_IMTYPE_XVID:
977                 case R_IMF_IMTYPE_FRAMESERVER:
978                         return 1;
979         }
980         return 0;
981 }
982
983 int BKE_imtype_supports_zbuf(const char imtype)
984 {
985         switch (imtype) {
986                 case R_IMF_IMTYPE_IRIZ:
987                 case R_IMF_IMTYPE_OPENEXR: /* but not R_IMF_IMTYPE_MULTILAYER */
988                         return 1;
989         }
990         return 0;
991 }
992
993 int BKE_imtype_supports_compress(const char imtype)
994 {
995         switch (imtype) {
996                 case R_IMF_IMTYPE_PNG:
997                         return 1;
998         }
999         return 0;
1000 }
1001
1002 int BKE_imtype_supports_quality(const char imtype)
1003 {
1004         switch (imtype) {
1005                 case R_IMF_IMTYPE_JPEG90:
1006                 case R_IMF_IMTYPE_JP2:
1007                 case R_IMF_IMTYPE_AVIJPEG:
1008                         return 1;
1009         }
1010         return 0;
1011 }
1012
1013 char BKE_imtype_valid_channels(const char imtype)
1014 {
1015         char chan_flag = IMA_CHAN_FLAG_RGB; /* assume all support rgb */
1016
1017         /* alpha */
1018         switch (imtype) {
1019                 case R_IMF_IMTYPE_TARGA:
1020                 case R_IMF_IMTYPE_IRIS:
1021                 case R_IMF_IMTYPE_PNG:
1022                 /* case R_IMF_IMTYPE_BMP: */ /* read but not write */
1023                 case R_IMF_IMTYPE_RADHDR:
1024                 case R_IMF_IMTYPE_TIFF:
1025                 case R_IMF_IMTYPE_OPENEXR:
1026                 case R_IMF_IMTYPE_MULTILAYER:
1027                 case R_IMF_IMTYPE_DDS:
1028                 case R_IMF_IMTYPE_JP2:
1029                 case R_IMF_IMTYPE_QUICKTIME:
1030                         chan_flag |= IMA_CHAN_FLAG_ALPHA;
1031         }
1032
1033         /* bw */
1034         switch (imtype) {
1035                 case R_IMF_IMTYPE_PNG:
1036                 case R_IMF_IMTYPE_JPEG90:
1037                 case R_IMF_IMTYPE_TARGA:
1038                 case R_IMF_IMTYPE_RAWTGA:
1039                 case R_IMF_IMTYPE_TIFF:
1040                 case R_IMF_IMTYPE_IRIS:
1041                         chan_flag |= IMA_CHAN_FLAG_BW;
1042         }
1043
1044         return chan_flag;
1045 }
1046
1047 char BKE_imtype_valid_depths(const char imtype)
1048 {
1049         switch (imtype) {
1050                 case R_IMF_IMTYPE_RADHDR:
1051                         return R_IMF_CHAN_DEPTH_32;
1052                 case R_IMF_IMTYPE_TIFF:
1053                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
1054                 case R_IMF_IMTYPE_OPENEXR:
1055                         return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
1056                 case R_IMF_IMTYPE_MULTILAYER:
1057                         return R_IMF_CHAN_DEPTH_32;
1058                 /* eeh, cineone does some strange 10bits per channel */
1059                 case R_IMF_IMTYPE_DPX:
1060                 case R_IMF_IMTYPE_CINEON:
1061                         return R_IMF_CHAN_DEPTH_12;
1062                 case R_IMF_IMTYPE_JP2:
1063                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
1064                 /* most formats are 8bit only */
1065                 default:
1066                         return R_IMF_CHAN_DEPTH_8;
1067         }
1068 }
1069
1070
1071 /* string is from command line --render-format arg, keep in sync with
1072  * creator.c help info */
1073 char BKE_imtype_from_arg(const char *imtype_arg)
1074 {
1075         if      (!strcmp(imtype_arg, "TGA")) return R_IMF_IMTYPE_TARGA;
1076         else if (!strcmp(imtype_arg, "IRIS")) return R_IMF_IMTYPE_IRIS;
1077 #ifdef WITH_DDS
1078         else if (!strcmp(imtype_arg, "DDS")) return R_IMF_IMTYPE_DDS;
1079 #endif
1080         else if (!strcmp(imtype_arg, "JPEG")) return R_IMF_IMTYPE_JPEG90;
1081         else if (!strcmp(imtype_arg, "IRIZ")) return R_IMF_IMTYPE_IRIZ;
1082         else if (!strcmp(imtype_arg, "RAWTGA")) return R_IMF_IMTYPE_RAWTGA;
1083         else if (!strcmp(imtype_arg, "AVIRAW")) return R_IMF_IMTYPE_AVIRAW;
1084         else if (!strcmp(imtype_arg, "AVIJPEG")) return R_IMF_IMTYPE_AVIJPEG;
1085         else if (!strcmp(imtype_arg, "PNG")) return R_IMF_IMTYPE_PNG;
1086         else if (!strcmp(imtype_arg, "QUICKTIME")) return R_IMF_IMTYPE_QUICKTIME;
1087         else if (!strcmp(imtype_arg, "BMP")) return R_IMF_IMTYPE_BMP;
1088 #ifdef WITH_HDR
1089         else if (!strcmp(imtype_arg, "HDR")) return R_IMF_IMTYPE_RADHDR;
1090 #endif
1091 #ifdef WITH_TIFF
1092         else if (!strcmp(imtype_arg, "TIFF")) return R_IMF_IMTYPE_TIFF;
1093 #endif
1094 #ifdef WITH_OPENEXR
1095         else if (!strcmp(imtype_arg, "EXR")) return R_IMF_IMTYPE_OPENEXR;
1096         else if (!strcmp(imtype_arg, "MULTILAYER")) return R_IMF_IMTYPE_MULTILAYER;
1097 #endif
1098         else if (!strcmp(imtype_arg, "MPEG")) return R_IMF_IMTYPE_FFMPEG;
1099         else if (!strcmp(imtype_arg, "FRAMESERVER")) return R_IMF_IMTYPE_FRAMESERVER;
1100 #ifdef WITH_CINEON
1101         else if (!strcmp(imtype_arg, "CINEON")) return R_IMF_IMTYPE_CINEON;
1102         else if (!strcmp(imtype_arg, "DPX")) return R_IMF_IMTYPE_DPX;
1103 #endif
1104 #ifdef WITH_OPENJPEG
1105         else if (!strcmp(imtype_arg, "JP2")) return R_IMF_IMTYPE_JP2;
1106 #endif
1107         else return R_IMF_IMTYPE_INVALID;
1108 }
1109
1110 int BKE_add_image_extension(char *string, const char imtype)
1111 {
1112         const char *extension = NULL;
1113
1114         if (imtype == R_IMF_IMTYPE_IRIS) {
1115                 if (!BLI_testextensie(string, ".rgb"))
1116                         extension = ".rgb";
1117         }
1118         else if (imtype == R_IMF_IMTYPE_IRIZ) {
1119                 if (!BLI_testextensie(string, ".rgb"))
1120                         extension = ".rgb";
1121         }
1122 #ifdef WITH_HDR
1123         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1124                 if (!BLI_testextensie(string, ".hdr"))
1125                         extension = ".hdr";
1126         }
1127 #endif
1128         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1129                 if (!BLI_testextensie(string, ".png"))
1130                         extension = ".png";
1131         }
1132 #ifdef WITH_DDS
1133         else if (imtype == R_IMF_IMTYPE_DDS) {
1134                 if (!BLI_testextensie(string, ".dds"))
1135                         extension = ".dds";
1136         }
1137 #endif
1138         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
1139                 if (!BLI_testextensie(string, ".tga"))
1140                         extension = ".tga";
1141         }
1142         else if (imtype == R_IMF_IMTYPE_BMP) {
1143                 if (!BLI_testextensie(string, ".bmp"))
1144                         extension = ".bmp";
1145         }
1146 #ifdef WITH_TIFF
1147         else if (imtype == R_IMF_IMTYPE_TIFF) {
1148                 if (!BLI_testextensie(string, ".tif") &&
1149                     !BLI_testextensie(string, ".tiff"))
1150                 {
1151                         extension = ".tif";
1152                 }
1153         }
1154 #endif
1155 #ifdef WITH_OPENEXR
1156         else if (ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
1157                 if (!BLI_testextensie(string, ".exr"))
1158                         extension = ".exr";
1159         }
1160 #endif
1161 #ifdef WITH_CINEON
1162         else if (imtype == R_IMF_IMTYPE_CINEON) {
1163                 if (!BLI_testextensie(string, ".cin"))
1164                         extension = ".cin";
1165         }
1166         else if (imtype == R_IMF_IMTYPE_DPX) {
1167                 if (!BLI_testextensie(string, ".dpx"))
1168                         extension = ".dpx";
1169         }
1170 #endif
1171         else if (imtype == R_IMF_IMTYPE_TARGA) {
1172                 if (!BLI_testextensie(string, ".tga"))
1173                         extension = ".tga";
1174         }
1175 #ifdef WITH_OPENJPEG
1176         else if (imtype == R_IMF_IMTYPE_JP2) {
1177                 if (!BLI_testextensie(string, ".jp2"))
1178                         extension = ".jp2";
1179         }
1180 #endif
1181         else { //   R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90, R_IMF_IMTYPE_QUICKTIME etc
1182                 if (!(BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
1183                         extension = ".jpg";
1184         }
1185
1186         if (extension) {
1187                 /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
1188                 /* remove any other known image extension */
1189                 if (BLI_testextensie_array(string, imb_ext_image) ||
1190                     (G.have_quicktime && BLI_testextensie_array(string, imb_ext_image_qt)))
1191                 {
1192                         return BLI_replace_extension(string, FILE_MAX, extension);
1193                 }
1194                 else {
1195                         return BLI_ensure_extension(string, FILE_MAX, extension);
1196                 }
1197
1198         }
1199         else {
1200                 return FALSE;
1201         }
1202 }
1203
1204 void BKE_imformat_defaults(ImageFormatData *im_format)
1205 {
1206         memset(im_format, 0, sizeof(*im_format));
1207         im_format->planes = R_IMF_PLANES_RGB;
1208         im_format->imtype = R_IMF_IMTYPE_PNG;
1209         im_format->quality = 90;
1210         im_format->compress = 90;
1211 }
1212
1213 void BKE_imbuf_to_image_format(struct ImageFormatData *im_format, const ImBuf *imbuf)
1214 {
1215         int ftype        = imbuf->ftype & ~IB_CUSTOM_FLAGS_MASK;
1216         int custom_flags = imbuf->ftype & IB_CUSTOM_FLAGS_MASK;
1217
1218         BKE_imformat_defaults(im_format);
1219
1220         /* file type */
1221
1222         if (ftype == IMAGIC)
1223                 im_format->imtype = R_IMF_IMTYPE_IRIS;
1224
1225 #ifdef WITH_HDR
1226         else if (ftype == RADHDR)
1227                 im_format->imtype = R_IMF_IMTYPE_RADHDR;
1228 #endif
1229
1230         else if (ftype == PNG)
1231                 im_format->imtype = R_IMF_IMTYPE_PNG;
1232
1233 #ifdef WITH_DDS
1234         else if (ftype == DDS)
1235                 im_format->imtype = R_IMF_IMTYPE_DDS;
1236 #endif
1237
1238         else if (ftype == BMP)
1239                 im_format->imtype = R_IMF_IMTYPE_BMP;
1240
1241 #ifdef WITH_TIFF
1242         else if (ftype == TIF) {
1243                 im_format->imtype = R_IMF_IMTYPE_TIFF;
1244                 if (custom_flags & TIF_16BIT)
1245                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1246         }
1247 #endif
1248
1249 #ifdef WITH_OPENEXR
1250         else if (ftype == OPENEXR) {
1251                 im_format->imtype = R_IMF_IMTYPE_OPENEXR;
1252                 if (custom_flags & OPENEXR_HALF)
1253                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1254                 if (custom_flags & OPENEXR_COMPRESS)
1255                         im_format->exr_codec = R_IMF_EXR_CODEC_ZIP;  // Can't determine compression
1256                 if (imbuf->zbuf_float)
1257                         im_format->flag |= R_IMF_FLAG_ZBUF;
1258         }
1259 #endif
1260
1261 #ifdef WITH_CINEON
1262         else if (ftype == CINEON)
1263                 im_format->imtype = R_IMF_IMTYPE_CINEON;
1264         else if (ftype == DPX)
1265                 im_format->imtype = R_IMF_IMTYPE_DPX;
1266 #endif
1267
1268         else if (ftype == TGA) {
1269                 im_format->imtype = R_IMF_IMTYPE_TARGA;
1270         }
1271         else if (ftype == RAWTGA) {
1272                 im_format->imtype = R_IMF_IMTYPE_RAWTGA;
1273         }
1274
1275 #ifdef WITH_OPENJPEG
1276         else if (ftype & JP2) {
1277                 im_format->imtype = R_IMF_IMTYPE_JP2;
1278                 im_format->quality = custom_flags & ~JPG_MSK;
1279
1280                 if (ftype & JP2_16BIT)
1281                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1282                 else if (ftype & JP2_12BIT)
1283                         im_format->depth = R_IMF_CHAN_DEPTH_12;
1284
1285                 if (ftype & JP2_YCC)
1286                         im_format->jp2_flag |= R_IMF_JP2_FLAG_YCC;
1287
1288                 if (ftype & JP2_CINE) {
1289                         im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_PRESET;
1290                         if (ftype & JP2_CINE_48FPS)
1291                                 im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_48;
1292                 }
1293         }
1294 #endif
1295
1296         else {
1297                 im_format->imtype = R_IMF_IMTYPE_JPEG90;
1298                 im_format->quality = custom_flags & ~JPG_MSK;
1299         }
1300
1301         /* planes */
1302         switch (imbuf->channels) {
1303                 case 0:
1304                 case 4: im_format->planes = R_IMF_PLANES_RGBA;
1305                         break;
1306                 case 3: im_format->planes = R_IMF_PLANES_RGB;
1307                         break;
1308                 case 1: im_format->planes = R_IMF_PLANES_BW;
1309                         break;
1310                 default: im_format->planes = R_IMF_PLANES_RGB;
1311                         break;
1312         }
1313
1314 }
1315
1316 static void timecode_simple_string(char *text, size_t text_size, const int cfra, int const frs_sec)
1317 {
1318         int f = (int)(cfra % frs_sec);
1319         int s = (int)(cfra / frs_sec);
1320         int h = 0;
1321         int m = 0;
1322
1323         if (s) {
1324                 m = (int)(s / 60);
1325                 s %= 60;
1326
1327                 if (m) {
1328                         h = (int)(m / 60);
1329                         m %= 60;
1330                 }
1331         }
1332
1333         if (frs_sec < 100) {
1334                 BLI_snprintf(text, text_size, "%02d:%02d:%02d.%02d", h, m, s, f);
1335         }
1336         else {
1337                 BLI_snprintf(text, text_size, "%02d:%02d:%02d.%03d", h, m, s, f);
1338         }
1339 }
1340
1341 /* could allow access externally - 512 is for long names, 64 is for id names */
1342 typedef struct StampData {
1343         char file[512];
1344         char note[512];
1345         char date[512];
1346         char marker[512];
1347         char time[512];
1348         char frame[512];
1349         char camera[64];
1350         char cameralens[64];
1351         char scene[64];
1352         char strip[64];
1353         char rendertime[64];
1354 } StampData;
1355
1356 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1357 {
1358         char text[256];
1359         struct tm *tl;
1360         time_t t;
1361
1362         if (scene->r.stamp & R_STAMP_FILENAME) {
1363                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s" : "%s", G.relbase_valid ? G.main->name : "<untitled>");
1364         }
1365         else {
1366                 stamp_data->file[0] = '\0';
1367         }
1368
1369         if (scene->r.stamp & R_STAMP_NOTE) {
1370                 /* Never do prefix for Note */
1371                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1372         }
1373         else {
1374                 stamp_data->note[0] = '\0';
1375         }
1376
1377         if (scene->r.stamp & R_STAMP_DATE) {
1378                 t = time(NULL);
1379                 tl = localtime(&t);
1380                 BLI_snprintf(text, sizeof(text), "%04d/%02d/%02d %02d:%02d:%02d", tl->tm_year + 1900, tl->tm_mon + 1, tl->tm_mday, tl->tm_hour, tl->tm_min, tl->tm_sec);
1381                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s" : "%s", text);
1382         }
1383         else {
1384                 stamp_data->date[0] = '\0';
1385         }
1386
1387         if (scene->r.stamp & R_STAMP_MARKER) {
1388                 char *name = BKE_scene_find_last_marker_name(scene, CFRA);
1389
1390                 if (name) BLI_strncpy(text, name, sizeof(text));
1391                 else BLI_strncpy(text, "<none>", sizeof(text));
1392
1393                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s" : "%s", text);
1394         }
1395         else {
1396                 stamp_data->marker[0] = '\0';
1397         }
1398
1399         if (scene->r.stamp & R_STAMP_TIME) {
1400                 timecode_simple_string(text, sizeof(text), scene->r.cfra, scene->r.frs_sec);
1401                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Time %s" : "%s", text);
1402         }
1403         else {
1404                 stamp_data->time[0] = '\0';
1405         }
1406
1407         if (scene->r.stamp & R_STAMP_FRAME) {
1408                 char fmtstr[32];
1409                 int digits = 1;
1410
1411                 if (scene->r.efra > 9)
1412                         digits = 1 + (int) log10(scene->r.efra);
1413
1414                 BLI_snprintf(fmtstr, sizeof(fmtstr), do_prefix ? "Frame %%0%di" : "%%0%di", digits);
1415                 BLI_snprintf(stamp_data->frame, sizeof(stamp_data->frame), fmtstr, scene->r.cfra);
1416         }
1417         else {
1418                 stamp_data->frame[0] = '\0';
1419         }
1420
1421         if (scene->r.stamp & R_STAMP_CAMERA) {
1422                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s" : "%s", camera ? camera->id.name + 2 : "<none>");
1423         }
1424         else {
1425                 stamp_data->camera[0] = '\0';
1426         }
1427
1428         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1429                 if (camera && camera->type == OB_CAMERA) {
1430                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1431                 }
1432                 else BLI_strncpy(text, "<none>", sizeof(text));
1433
1434                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s" : "%s", text);
1435         }
1436         else {
1437                 stamp_data->cameralens[0] = '\0';
1438         }
1439
1440         if (scene->r.stamp & R_STAMP_SCENE) {
1441                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
1442         }
1443         else {
1444                 stamp_data->scene[0] = '\0';
1445         }
1446
1447         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1448                 Sequence *seq = BKE_sequencer_foreground_frame_get(scene, scene->r.cfra);
1449
1450                 if (seq) BLI_strncpy(text, seq->name + 2, sizeof(text));
1451                 else BLI_strncpy(text, "<none>", sizeof(text));
1452
1453                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s" : "%s", text);
1454         }
1455         else {
1456                 stamp_data->strip[0] = '\0';
1457         }
1458
1459         {
1460                 Render *re = RE_GetRender(scene->id.name);
1461                 RenderStats *stats = re ? RE_GetStats(re) : NULL;
1462
1463                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1464                         BLI_timestr(stats->lastframetime, text);
1465
1466                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s" : "%s", text);
1467                 }
1468                 else {
1469                         stamp_data->rendertime[0] = '\0';
1470                 }
1471         }
1472 }
1473
1474 void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rectf, int width, int height, int channels)
1475 {
1476         struct StampData stamp_data;
1477         float w, h, pad;
1478         int x, y, y_ofs;
1479         float h_fixed;
1480         const int mono = blf_mono_font_render; // XXX
1481
1482         /* this could be an argument if we want to operate on non linear float imbuf's
1483          * for now though this is only used for renders which use scene settings */
1484         const int do_color_management = (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) != 0;
1485
1486 #define BUFF_MARGIN_X 2
1487 #define BUFF_MARGIN_Y 1
1488
1489         if (!rect && !rectf)
1490                 return;
1491
1492         stampdata(scene, camera, &stamp_data, 1);
1493
1494         /* TODO, do_versions */
1495         if (scene->r.stamp_font_id < 8)
1496                 scene->r.stamp_font_id = 12;
1497
1498         /* set before return */
1499         BLF_size(mono, scene->r.stamp_font_id, 72);
1500
1501         BLF_buffer(mono, rectf, rect, width, height, channels, do_color_management);
1502         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1503         pad = BLF_width_max(mono);
1504
1505         /* use 'h_fixed' rather than 'h', aligns better */
1506         h_fixed = BLF_height_max(mono);
1507         y_ofs = -BLF_descender(mono);
1508
1509         x = 0;
1510         y = height;
1511
1512         if (stamp_data.file[0]) {
1513                 /* Top left corner */
1514                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h = h_fixed;
1515                 y -= h;
1516
1517                 /* also a little of space to the background. */
1518                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1519                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1520
1521                 /* and draw the text. */
1522                 BLF_position(mono, x, y + y_ofs, 0.0);
1523                 BLF_draw_buffer(mono, stamp_data.file);
1524
1525                 /* the extra pixel for background. */
1526                 y -= BUFF_MARGIN_Y * 2;
1527         }
1528
1529         /* Top left corner, below File */
1530         if (stamp_data.note[0]) {
1531                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h = h_fixed;
1532                 y -= h;
1533
1534                 /* and space for background. */
1535                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1536                                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1537
1538                 BLF_position(mono, x, y + y_ofs, 0.0);
1539                 BLF_draw_buffer(mono, stamp_data.note);
1540
1541                 /* the extra pixel for background. */
1542                 y -= BUFF_MARGIN_Y * 2;
1543         }
1544
1545         /* Top left corner, below File (or Note) */
1546         if (stamp_data.date[0]) {
1547                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h = h_fixed;
1548                 y -= h;
1549
1550                 /* and space for background. */
1551                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1552                                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1553
1554                 BLF_position(mono, x, y + y_ofs, 0.0);
1555                 BLF_draw_buffer(mono, stamp_data.date);
1556
1557                 /* the extra pixel for background. */
1558                 y -= BUFF_MARGIN_Y * 2;
1559         }
1560
1561         /* Top left corner, below File, Date or Note */
1562         if (stamp_data.rendertime[0]) {
1563                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h = h_fixed;
1564                 y -= h;
1565
1566                 /* and space for background. */
1567                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1568                                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1569
1570                 BLF_position(mono, x, y + y_ofs, 0.0);
1571                 BLF_draw_buffer(mono, stamp_data.rendertime);
1572         }
1573
1574         x = 0;
1575         y = 0;
1576
1577         /* Bottom left corner, leaving space for timing */
1578         if (stamp_data.marker[0]) {
1579                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h = h_fixed;
1580
1581                 /* extra space for background. */
1582                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp,  do_color_management,
1583                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1584
1585                 /* and pad the text. */
1586                 BLF_position(mono, x, y + y_ofs, 0.0);
1587                 BLF_draw_buffer(mono, stamp_data.marker);
1588
1589                 /* space width. */
1590                 x += w + pad;
1591         }
1592
1593         /* Left bottom corner */
1594         if (stamp_data.time[0]) {
1595                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h = h_fixed;
1596
1597                 /* extra space for background */
1598                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1599                                                   x - BUFF_MARGIN_X, y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1600
1601                 /* and pad the text. */
1602                 BLF_position(mono, x, y + y_ofs, 0.0);
1603                 BLF_draw_buffer(mono, stamp_data.time);
1604
1605                 /* space width. */
1606                 x += w + pad;
1607         }
1608
1609         if (stamp_data.frame[0]) {
1610                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h = h_fixed;
1611
1612                 /* extra space for background. */
1613                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1614                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1615
1616                 /* and pad the text. */
1617                 BLF_position(mono, x, y + y_ofs, 0.0);
1618                 BLF_draw_buffer(mono, stamp_data.frame);
1619
1620                 /* space width. */
1621                 x += w + pad;
1622         }
1623
1624         if (stamp_data.camera[0]) {
1625                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h = h_fixed;
1626
1627                 /* extra space for background. */
1628                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1629                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1630                 BLF_position(mono, x, y + y_ofs, 0.0);
1631                 BLF_draw_buffer(mono, stamp_data.camera);
1632
1633                 /* space width. */
1634                 x += w + pad;
1635         }
1636
1637         if (stamp_data.cameralens[0]) {
1638                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h = h_fixed;
1639
1640                 /* extra space for background. */
1641                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1642                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1643                 BLF_position(mono, x, y + y_ofs, 0.0);
1644                 BLF_draw_buffer(mono, stamp_data.cameralens);
1645         }
1646
1647         if (stamp_data.scene[0]) {
1648                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h = h_fixed;
1649
1650                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1651                 x = width - w - 2;
1652
1653                 /* extra space for background. */
1654                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1655                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1656
1657                 /* and pad the text. */
1658                 BLF_position(mono, x, y + y_ofs, 0.0);
1659                 BLF_draw_buffer(mono, stamp_data.scene);
1660         }
1661
1662         if (stamp_data.strip[0]) {
1663                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h = h_fixed;
1664
1665                 /* Top right corner, with an extra space because blenfont is too strict! */
1666                 x = width - w - pad;
1667                 y = height - h;
1668
1669                 /* extra space for background. */
1670                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1671                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1672
1673                 BLF_position(mono, x, y + y_ofs, 0.0);
1674                 BLF_draw_buffer(mono, stamp_data.strip);
1675         }
1676
1677         /* cleanup the buffer. */
1678         BLF_buffer(mono, NULL, NULL, 0, 0, 0, FALSE);
1679
1680 #undef BUFF_MARGIN_X
1681 #undef BUFF_MARGIN_Y
1682 }
1683
1684 void BKE_imbuf_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1685 {
1686         struct StampData stamp_data;
1687
1688         if (!ibuf) return;
1689
1690         /* fill all the data values, no prefix */
1691         stampdata(scene, camera, &stamp_data, 0);
1692
1693         if (stamp_data.file[0]) IMB_metadata_change_field(ibuf, "File",        stamp_data.file);
1694         if (stamp_data.note[0]) IMB_metadata_change_field(ibuf, "Note",        stamp_data.note);
1695         if (stamp_data.date[0]) IMB_metadata_change_field(ibuf, "Date",        stamp_data.date);
1696         if (stamp_data.marker[0]) IMB_metadata_change_field(ibuf, "Marker",    stamp_data.marker);
1697         if (stamp_data.time[0]) IMB_metadata_change_field(ibuf, "Time",        stamp_data.time);
1698         if (stamp_data.frame[0]) IMB_metadata_change_field(ibuf, "Frame",      stamp_data.frame);
1699         if (stamp_data.camera[0]) IMB_metadata_change_field(ibuf, "Camera",    stamp_data.camera);
1700         if (stamp_data.cameralens[0]) IMB_metadata_change_field(ibuf, "Lens",  stamp_data.cameralens);
1701         if (stamp_data.scene[0]) IMB_metadata_change_field(ibuf, "Scene",      stamp_data.scene);
1702         if (stamp_data.strip[0]) IMB_metadata_change_field(ibuf, "Strip",      stamp_data.strip);
1703         if (stamp_data.rendertime[0]) IMB_metadata_change_field(ibuf, "RenderTime", stamp_data.rendertime);
1704 }
1705
1706 int BKE_imbuf_alpha_test(ImBuf *ibuf)
1707 {
1708         int tot;
1709         if (ibuf->rect_float) {
1710                 float *buf = ibuf->rect_float;
1711                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1712                         if (buf[3] < 1.0f) {
1713                                 return TRUE;
1714                         }
1715                 }
1716         }
1717         else if (ibuf->rect) {
1718                 unsigned char *buf = (unsigned char *)ibuf->rect;
1719                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1720                         if (buf[3] != 255) {
1721                                 return TRUE;
1722                         }
1723                 }
1724         }
1725
1726         return FALSE;
1727 }
1728
1729 /* note: imf->planes is ignored here, its assumed the image channels
1730  * are already set */
1731 int BKE_imbuf_write(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1732 {
1733         char imtype = imf->imtype;
1734         char compress = imf->compress;
1735         char quality = imf->quality;
1736
1737         int ok;
1738
1739         if (imtype == R_IMF_IMTYPE_IRIS) {
1740                 ibuf->ftype = IMAGIC;
1741         }
1742 #ifdef WITH_HDR
1743         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1744                 ibuf->ftype = RADHDR;
1745         }
1746 #endif
1747         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1748                 ibuf->ftype = PNG;
1749
1750                 if (imtype == R_IMF_IMTYPE_PNG)
1751                         ibuf->ftype |= compress;
1752
1753         }
1754 #ifdef WITH_DDS
1755         else if (imtype == R_IMF_IMTYPE_DDS) {
1756                 ibuf->ftype = DDS;
1757         }
1758 #endif
1759         else if (imtype == R_IMF_IMTYPE_BMP) {
1760                 ibuf->ftype = BMP;
1761         }
1762 #ifdef WITH_TIFF
1763         else if (imtype == R_IMF_IMTYPE_TIFF) {
1764                 ibuf->ftype = TIF;
1765
1766                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1767                         ibuf->ftype |= TIF_16BIT;
1768         }
1769 #endif
1770 #ifdef WITH_OPENEXR
1771         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) {
1772                 ibuf->ftype = OPENEXR;
1773                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1774                         ibuf->ftype |= OPENEXR_HALF;
1775                 ibuf->ftype |= (imf->exr_codec & OPENEXR_COMPRESS);
1776
1777                 if (!(imf->flag & R_IMF_FLAG_ZBUF))
1778                         ibuf->zbuf_float = NULL;    /* signal for exr saving */
1779
1780         }
1781 #endif
1782 #ifdef WITH_CINEON
1783         else if (imtype == R_IMF_IMTYPE_CINEON) {
1784                 ibuf->ftype = CINEON;
1785         }
1786         else if (imtype == R_IMF_IMTYPE_DPX) {
1787                 ibuf->ftype = DPX;
1788         }
1789 #endif
1790         else if (imtype == R_IMF_IMTYPE_TARGA) {
1791                 ibuf->ftype = TGA;
1792         }
1793         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
1794                 ibuf->ftype = RAWTGA;
1795         }
1796 #ifdef WITH_OPENJPEG
1797         else if (imtype == R_IMF_IMTYPE_JP2) {
1798                 if (quality < 10) quality = 90;
1799                 ibuf->ftype = JP2 | quality;
1800
1801                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1802                         ibuf->ftype |= JP2_16BIT;
1803                 }
1804                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1805                         ibuf->ftype |= JP2_12BIT;
1806                 }
1807
1808                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
1809                         ibuf->ftype |= JP2_YCC;
1810                 }
1811
1812                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
1813                         ibuf->ftype |= JP2_CINE;
1814                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
1815                                 ibuf->ftype |= JP2_CINE_48FPS;
1816                 }
1817         }
1818 #endif
1819         else {
1820                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
1821                 if (quality < 10) quality = 90;
1822                 ibuf->ftype = JPG | quality;
1823         }
1824
1825         BLI_make_existing_file(name);
1826
1827         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1828         if (ok == 0) {
1829                 perror(name);
1830         }
1831
1832         return(ok);
1833 }
1834
1835 /* same as BKE_imbuf_write() but crappy workaround not to perminantly modify
1836  * _some_, values in the imbuf */
1837 int BKE_imbuf_write_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
1838                        const short save_copy)
1839 {
1840         ImBuf ibuf_back = *ibuf;
1841         int ok;
1842
1843         /* all data is rgba anyway,
1844          * this just controls how to save for some formats */
1845         ibuf->planes = imf->planes;
1846
1847         ok = BKE_imbuf_write(ibuf, name, imf);
1848
1849         if (save_copy) {
1850                 /* note that we are not restoring _all_ settings */
1851                 ibuf->planes = ibuf_back.planes;
1852                 ibuf->ftype =  ibuf_back.ftype;
1853         }
1854
1855         return ok;
1856 }
1857
1858 int BKE_imbuf_write_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
1859 {
1860         if (scene && scene->r.stamp & R_STAMP_ALL)
1861                 BKE_imbuf_stamp_info(scene, camera, ibuf);
1862
1863         return BKE_imbuf_write(ibuf, name, imf);
1864 }
1865
1866
1867 void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype, const short use_ext, const short use_frames)
1868 {
1869         if (string == NULL) return;
1870         BLI_strncpy(string, base, FILE_MAX - 10);   /* weak assumption */
1871         BLI_path_abs(string, relbase);
1872
1873         if (use_frames)
1874                 BLI_path_frame(string, frame, 4);
1875
1876         if (use_ext)
1877                 BKE_add_image_extension(string, imtype);
1878
1879 }
1880
1881 /* used by sequencer too */
1882 struct anim *openanim(const char *name, int flags, int streamindex)
1883 {
1884         struct anim *anim;
1885         struct ImBuf *ibuf;
1886
1887         anim = IMB_open_anim(name, flags, streamindex);
1888         if (anim == NULL) return NULL;
1889
1890         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1891         if (ibuf == NULL) {
1892                 if (BLI_exists(name))
1893                         printf("not an anim: %s\n", name);
1894                 else
1895                         printf("anim file doesn't exist: %s\n", name);
1896                 IMB_free_anim(anim);
1897                 return NULL;
1898         }
1899         IMB_freeImBuf(ibuf);
1900
1901         return(anim);
1902 }
1903
1904 /* ************************* New Image API *************** */
1905
1906
1907 /* Notes about Image storage
1908  * - packedfile
1909  *   -> written in .blend
1910  * - filename
1911  *   -> written in .blend
1912  * - movie
1913  *   -> comes from packedfile or filename
1914  * - renderresult
1915  *   -> comes from packedfile or filename
1916  * - listbase
1917  *   -> ibufs from exrhandle
1918  * - flipbook array
1919  *   -> ibufs come from movie, temporary renderresult or sequence
1920  * - ibuf
1921  *   -> comes from packedfile or filename or generated
1922  */
1923
1924
1925 /* forces existence of 1 Image for renderout or nodes, returns Image */
1926 /* name is only for default, when making new one */
1927 Image *BKE_image_verify_viewer(int type, const char *name)
1928 {
1929         Image *ima;
1930
1931         for (ima = G.main->image.first; ima; ima = ima->id.next)
1932                 if (ima->source == IMA_SRC_VIEWER)
1933                         if (ima->type == type)
1934                                 break;
1935
1936         if (ima == NULL)
1937                 ima = image_alloc(name, IMA_SRC_VIEWER, type);
1938
1939         /* happens on reload, imagewindow cannot be image user when hidden*/
1940         if (ima->id.us == 0)
1941                 id_us_plus(&ima->id);
1942
1943         return ima;
1944 }
1945
1946 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1947 {
1948         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1949 }
1950
1951 void BKE_image_walk_all_users(const Main *mainp, void *customdata,
1952                               void callback(Image *ima, ImageUser *iuser, void *customdata))
1953 {
1954         wmWindowManager *wm;
1955         wmWindow *win;
1956         Tex *tex;
1957
1958         /* texture users */
1959         for (tex = mainp->tex.first; tex; tex = tex->id.next) {
1960                 if (tex->type == TEX_IMAGE && tex->ima) {
1961                         if (ELEM(tex->ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
1962                                 callback(tex->ima, &tex->iuser, customdata);
1963                         }
1964                 }
1965         }
1966
1967         /* image window, compo node users */
1968         for (wm = mainp->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
1969                 for (win = wm->windows.first; win; win = win->next) {
1970                         ScrArea *sa;
1971                         for (sa = win->screen->areabase.first; sa; sa = sa->next) {
1972                                 if (sa->spacetype == SPACE_VIEW3D) {
1973                                         View3D *v3d = sa->spacedata.first;
1974                                         BGpic *bgpic;
1975                                         for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
1976                                                 callback(bgpic->ima, &bgpic->iuser, customdata);
1977                                         }
1978                                 }
1979                                 else if (sa->spacetype == SPACE_IMAGE) {
1980                                         SpaceImage *sima = sa->spacedata.first;
1981                                         callback(sima->image, &sima->iuser, customdata);
1982                                 }
1983                                 else if (sa->spacetype == SPACE_NODE) {
1984                                         SpaceNode *snode = sa->spacedata.first;
1985                                         if ((snode->treetype == NTREE_COMPOSIT) && (snode->nodetree)) {
1986                                                 bNode *node;
1987                                                 for (node = snode->nodetree->nodes.first; node; node = node->next) {
1988                                                         if (node->id && node->type == CMP_NODE_IMAGE) {
1989                                                                 Image *ima = (Image *)node->id;
1990                                                                 ImageUser *iuser = node->storage;
1991                                                                 callback(ima, iuser, customdata);
1992                                                         }
1993                                                 }
1994                                         }
1995                                 }
1996                         }
1997                 }
1998         }
1999 }
2000
2001 static void image_tag_frame_recalc(Image *ima, ImageUser *iuser, void *customdata)
2002 {
2003         Image *changed_image = customdata;
2004
2005         if (ima == changed_image) {
2006                 iuser->flag |= IMA_NEED_FRAME_RECALC;
2007         }
2008 }
2009
2010 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
2011 {
2012         if (ima == NULL)
2013                 return;
2014
2015         switch (signal) {
2016                 case IMA_SIGNAL_FREE:
2017                         image_free_buffers(ima);
2018                         if (iuser)
2019                                 iuser->ok = 1;
2020                         break;
2021                 case IMA_SIGNAL_SRC_CHANGE:
2022                         if (ima->type == IMA_TYPE_UV_TEST)
2023                                 if (ima->source != IMA_SRC_GENERATED)
2024                                         ima->type = IMA_TYPE_IMAGE;
2025
2026                         if (ima->source == IMA_SRC_GENERATED) {
2027                                 if (ima->gen_x == 0 || ima->gen_y == 0) {
2028                                         ImBuf *ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2029                                         if (ibuf) {
2030                                                 ima->gen_x = ibuf->x;
2031                                                 ima->gen_y = ibuf->y;
2032                                         }
2033                                 }
2034                         }
2035
2036                         /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
2037                         if (ima->type != IMA_TYPE_MULTILAYER)
2038                                 image_free_buffers(ima);
2039
2040                         ima->ok = 1;
2041                         if (iuser)
2042                                 iuser->ok = 1;
2043
2044                         BKE_image_walk_all_users(G.main, ima, image_tag_frame_recalc);
2045
2046                         break;
2047
2048                 case IMA_SIGNAL_RELOAD:
2049                         /* try to repack file */
2050                         if (ima->packedfile) {
2051                                 PackedFile *pf;
2052                                 pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
2053                                 if (pf) {
2054                                         freePackedFile(ima->packedfile);
2055                                         ima->packedfile = pf;
2056                                         image_free_buffers(ima);
2057                                 }
2058                                 else {
2059                                         printf("ERROR: Image not available. Keeping packed image\n");
2060                                 }
2061                         }
2062                         else
2063                                 image_free_buffers(ima);
2064
2065                         if (iuser)
2066                                 iuser->ok = 1;
2067
2068                         break;
2069                 case IMA_SIGNAL_USER_NEW_IMAGE:
2070                         if (iuser) {
2071                                 iuser->ok = 1;
2072                                 if (ima->source == IMA_SRC_FILE || ima->source == IMA_SRC_SEQUENCE) {
2073                                         if (ima->type == IMA_TYPE_MULTILAYER) {
2074                                                 iuser->multi_index = 0;
2075                                                 iuser->layer = iuser->pass = 0;
2076                                         }
2077                                 }
2078                         }
2079                         break;
2080         }
2081
2082         /* don't use notifiers because they are not 100% sure to succeeded
2083          * this also makes sure all scenes are accounted for. */
2084         {
2085                 Scene *scene;
2086                 for (scene = G.main->scene.first; scene; scene = scene->id.next) {
2087                         if (scene->nodetree) {
2088                                 nodeUpdateID(scene->nodetree, &ima->id);
2089                         }
2090                 }
2091         }
2092 }
2093
2094 /* if layer or pass changes, we need an index for the imbufs list */
2095 /* note it is called for rendered results, but it doesnt use the index! */
2096 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2097 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
2098 {
2099         RenderLayer *rl;
2100         RenderPass *rpass = NULL;
2101
2102         if (rr == NULL)
2103                 return NULL;
2104
2105         if (iuser) {
2106                 short index = 0, rl_index = 0, rp_index;
2107
2108                 for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
2109                         rp_index = 0;
2110                         for (rpass = rl->passes.first; rpass; rpass = rpass->next, index++, rp_index++)
2111                                 if (iuser->layer == rl_index && iuser->pass == rp_index)
2112                                         break;
2113                         if (rpass)
2114                                 break;
2115                 }
2116
2117                 if (rpass)
2118                         iuser->multi_index = index;
2119                 else
2120                         iuser->multi_index = 0;
2121         }
2122         if (rpass == NULL) {
2123                 rl = rr->layers.first;
2124                 if (rl)
2125                         rpass = rl->passes.first;
2126         }
2127
2128         return rpass;
2129 }
2130
2131 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
2132 {
2133         if (ima->rr) {
2134                 return ima->rr;
2135         }
2136         else if (ima->type == IMA_TYPE_R_RESULT) {
2137                 if (ima->render_slot == ima->last_render_slot)
2138                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
2139                 else
2140                         return ima->renders[ima->render_slot];
2141         }
2142         else
2143                 return NULL;
2144 }
2145
2146 void BKE_image_release_renderresult(Scene *scene, Image *ima)
2147 {
2148         if (ima->rr) {
2149                 /* pass */
2150         }
2151         else if (ima->type == IMA_TYPE_R_RESULT) {
2152                 if (ima->render_slot == ima->last_render_slot)
2153                         RE_ReleaseResult(RE_GetRender(scene->id.name));
2154         }
2155 }
2156
2157 void BKE_image_backup_render(Scene *scene, Image *ima)
2158 {
2159         /* called right before rendering, ima->renders contains render
2160          * result pointers for everything but the current render */
2161         Render *re = RE_GetRender(scene->id.name);
2162         int slot = ima->render_slot, last = ima->last_render_slot;
2163
2164         if (slot != last) {
2165                 if (ima->renders[slot]) {
2166                         RE_FreeRenderResult(ima->renders[slot]);
2167                         ima->renders[slot] = NULL;
2168                 }
2169
2170                 ima->renders[last] = NULL;
2171                 RE_SwapResult(re, &ima->renders[last]);
2172         }
2173
2174         ima->last_render_slot = slot;
2175 }
2176
2177 /* after imbuf load, openexr type can return with a exrhandle open */
2178 /* in that case we have to build a render-result */
2179 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
2180 {
2181
2182         ima->rr = RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
2183
2184 #ifdef WITH_OPENEXR
2185         IMB_exr_close(ibuf->userdata);
2186 #endif
2187
2188         ibuf->userdata = NULL;
2189         if (ima->rr)
2190                 ima->rr->framenr = framenr;
2191 }
2192
2193 /* common stuff to do with images after loading */
2194 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
2195 {
2196         /* preview is NULL when it has never been used as an icon before */
2197         if (G.background == 0 && ima->preview == NULL)
2198                 BKE_icon_changed(BKE_icon_getid(&ima->id));
2199
2200         /* fields */
2201         if (ima->flag & IMA_FIELDS) {
2202                 if (ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
2203                 else de_interlace_ng(ibuf);
2204         }
2205         /* timer */
2206         ima->lastused = clock() / CLOCKS_PER_SEC;
2207
2208         ima->ok = IMA_OK_LOADED;
2209
2210 }
2211
2212 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
2213 {
2214         struct ImBuf *ibuf;
2215         char name[FILE_MAX];
2216         int flag;
2217
2218         /* XXX temp stuff? */
2219         if (ima->lastframe != frame)
2220                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2221
2222         ima->lastframe = frame;
2223         BKE_image_user_file_path(iuser, ima, name);
2224
2225         flag = IB_rect | IB_multilayer;
2226         if (ima->flag & IMA_DO_PREMUL)
2227                 flag |= IB_premul;
2228
2229         /* read ibuf */
2230         ibuf = IMB_loadiffname(name, flag);
2231
2232 #if 0
2233         if (ibuf) {
2234                 printf(AT " loaded %s\n", name);
2235         }
2236         else {
2237                 printf(AT " missed %s\n", name);
2238         }
2239 #endif
2240
2241         if (ibuf) {
2242 #ifdef WITH_OPENEXR
2243                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2244                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2245                         image_create_multilayer(ima, ibuf, frame);
2246                         ima->type = IMA_TYPE_MULTILAYER;
2247                         IMB_freeImBuf(ibuf);
2248                         ibuf = NULL;
2249                 }
2250                 else {
2251                         image_initialize_after_load(ima, ibuf);
2252                         image_assign_ibuf(ima, ibuf, 0, frame);
2253                 }
2254 #else
2255                 image_initialize_after_load(ima, ibuf);
2256                 image_assign_ibuf(ima, ibuf, 0, frame);
2257 #endif
2258         }
2259         else
2260                 ima->ok = 0;
2261
2262         if (iuser)
2263                 iuser->ok = ima->ok;
2264
2265         return ibuf;
2266 }
2267
2268 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
2269 {
2270         struct ImBuf *ibuf = NULL;
2271
2272         /* either we load from RenderResult, or we have to load a new one */
2273
2274         /* check for new RenderResult */
2275         if (ima->rr == NULL || frame != ima->rr->framenr) {
2276                 /* copy to survive not found multilayer image */
2277                 RenderResult *oldrr = ima->rr;
2278
2279                 ima->rr = NULL;
2280                 ibuf = image_load_sequence_file(ima, iuser, frame);
2281
2282                 if (ibuf) { /* actually an error */
2283                         ima->type = IMA_TYPE_IMAGE;
2284                         printf("error, multi is normal image\n");
2285                 }
2286                 // printf("loaded new result %p\n", ima->rr);
2287                 /* free result if new one found */
2288                 if (ima->rr) {
2289                         // if (oldrr) printf("freed previous result %p\n", oldrr);
2290                         if (oldrr) RE_FreeRenderResult(oldrr);
2291                 }
2292                 else {
2293                         ima->rr = oldrr;
2294                 }
2295
2296         }
2297         if (ima->rr) {
2298                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2299
2300                 if (rpass) {
2301                         // printf("load from pass %s\n", rpass->name);
2302                         /* since we free  render results, we copy the rect */
2303                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2304                         ibuf->rect_float = MEM_dupallocN(rpass->rect);
2305                         ibuf->flags |= IB_rectfloat;
2306                         ibuf->mall = IB_rectfloat;
2307                         ibuf->channels = rpass->channels;
2308                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2309
2310                         image_initialize_after_load(ima, ibuf);
2311                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, frame);
2312
2313                 }
2314                 // else printf("pass not found\n");
2315         }
2316         else
2317                 ima->ok = 0;
2318
2319         if (iuser)
2320                 iuser->ok = ima->ok;
2321
2322         return ibuf;
2323 }
2324
2325
2326 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
2327 {
2328         struct ImBuf *ibuf = NULL;
2329
2330         ima->lastframe = frame;
2331
2332         if (ima->anim == NULL) {
2333                 char str[FILE_MAX];
2334
2335                 BKE_image_user_file_path(iuser, ima, str);
2336
2337                 /* FIXME: make several stream accessible in image editor, too*/
2338                 ima->anim = openanim(str, IB_rect, 0);
2339
2340                 /* let's initialize this user */
2341                 if (ima->anim && iuser && iuser->frames == 0)
2342                         iuser->frames = IMB_anim_get_duration(ima->anim,
2343                                                               IMB_TC_RECORD_RUN);
2344         }
2345
2346         if (ima->anim) {
2347                 int dur = IMB_anim_get_duration(ima->anim,
2348                                                 IMB_TC_RECORD_RUN);
2349                 int fra = frame - 1;
2350
2351                 if (fra < 0) fra = 0;
2352                 if (fra > (dur - 1)) fra = dur - 1;
2353                 ibuf = IMB_makeSingleUser(
2354                     IMB_anim_absolute(ima->anim, fra,
2355                                       IMB_TC_RECORD_RUN,
2356                                       IMB_PROXY_NONE));
2357
2358                 if (ibuf) {
2359                         image_initialize_after_load(ima, ibuf);
2360                         image_assign_ibuf(ima, ibuf, 0, frame);
2361                 }
2362                 else
2363                         ima->ok = 0;
2364         }
2365         else
2366                 ima->ok = 0;
2367
2368         if (iuser)
2369                 iuser->ok = ima->ok;
2370
2371         return ibuf;
2372 }
2373
2374 /* warning, 'iuser' can be NULL */
2375 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2376 {
2377         struct ImBuf *ibuf;
2378         char str[FILE_MAX];
2379         int assign = 0, flag;
2380
2381         /* always ensure clean ima */
2382         image_free_buffers(ima);
2383
2384         /* is there a PackedFile with this image ? */
2385         if (ima->packedfile) {
2386                 flag = IB_rect | IB_multilayer;
2387                 if (ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
2388
2389                 ibuf = IMB_ibImageFromMemory((unsigned char *)ima->packedfile->data,
2390                                              ima->packedfile->size, flag, "<packed data>");
2391         }
2392         else {
2393                 flag = IB_rect | IB_multilayer | IB_metadata;
2394                 if (ima->flag & IMA_DO_PREMUL)
2395                         flag |= IB_premul;
2396
2397                 /* get the right string */
2398                 BKE_image_user_frame_calc(iuser, cfra, 0);
2399                 BKE_image_user_file_path(iuser, ima, str);
2400
2401                 /* read ibuf */
2402                 ibuf = IMB_loadiffname(str, flag);
2403         }
2404
2405         if (ibuf) {
2406                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2407                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2408                         image_create_multilayer(ima, ibuf, cfra);
2409                         ima->type = IMA_TYPE_MULTILAYER;
2410                         IMB_freeImBuf(ibuf);
2411                         ibuf = NULL;
2412                 }
2413                 else {
2414                         image_initialize_after_load(ima, ibuf);
2415                         assign = 1;
2416
2417                         /* check if the image is a font image... */
2418                         detectBitmapFont(ibuf);
2419
2420                         /* make packed file for autopack */
2421                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2422                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2423                 }
2424         }
2425         else
2426                 ima->ok = 0;
2427
2428         if (assign)
2429                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2430
2431         if (iuser)
2432                 iuser->ok = ima->ok;
2433
2434         return ibuf;
2435 }
2436
2437 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2438 {
2439         ImBuf *ibuf = NULL;
2440
2441         if (ima->rr == NULL) {
2442                 ibuf = image_load_image_file(ima, iuser, 0);
2443                 if (ibuf) { /* actually an error */
2444                         ima->type = IMA_TYPE_IMAGE;
2445                         return ibuf;
2446                 }
2447         }
2448         if (ima->rr) {
2449                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2450
2451                 if (rpass) {
2452                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2453
2454                         image_initialize_after_load(ima, ibuf);
2455
2456                         ibuf->rect_float = rpass->rect;
2457                         ibuf->flags |= IB_rectfloat;
2458                         ibuf->channels = rpass->channels;
2459                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2460
2461                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2462                 }
2463         }
2464
2465         if (ibuf == NULL)
2466                 ima->ok = 0;
2467         if (iuser)
2468                 iuser->ok = ima->ok;
2469
2470         return ibuf;
2471 }
2472
2473
2474 /* showing RGBA result itself (from compo/sequence) or
2475  * like exr, using layers etc */
2476 /* always returns a single ibuf, also during render progress */
2477 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2478 {
2479         Render *re;
2480         RenderResult rres;
2481         float *rectf, *rectz;
2482         unsigned int *rect;
2483         float dither;
2484         int channels, layer, pass;
2485         ImBuf *ibuf;
2486         int from_render = (ima->render_slot == ima->last_render_slot);
2487
2488         if (!(iuser && iuser->scene))
2489                 return NULL;
2490
2491         /* if we the caller is not going to release the lock, don't give the image */
2492         if (!lock_r)
2493                 return NULL;
2494
2495         re = RE_GetRender(iuser->scene->id.name);
2496
2497         channels = 4;
2498         layer = (iuser) ? iuser->layer : 0;
2499         pass = (iuser) ? iuser->pass : 0;
2500
2501         if (from_render) {
2502                 RE_AcquireResultImage(re, &rres);
2503         }
2504         else if (ima->renders[ima->render_slot]) {
2505                 rres = *(ima->renders[ima->render_slot]);
2506                 rres.have_combined = rres.rectf != NULL;
2507         }
2508         else
2509                 memset(&rres, 0, sizeof(RenderResult));
2510
2511         if (!(rres.rectx > 0 && rres.recty > 0)) {
2512                 if (from_render)
2513                         RE_ReleaseResultImage(re);
2514                 return NULL;
2515         }
2516
2517         /* release is done in BKE_image_release_ibuf using lock_r */
2518         if (from_render) {
2519                 BLI_lock_thread(LOCK_VIEWER);
2520                 *lock_r = re;
2521         }
2522
2523         /* this gives active layer, composite or seqence result */
2524         rect = (unsigned int *)rres.rect32;
2525         rectf = rres.rectf;
2526         rectz = rres.rectz;
2527         dither = iuser->scene->r.dither_intensity;
2528
2529         /* combined layer gets added as first layer */
2530         if (rres.have_combined && layer == 0) ;
2531         else if (rres.layers.first) {
2532                 RenderLayer *rl = BLI_findlink(&rres.layers, layer - (rres.have_combined ? 1 : 0));
2533                 if (rl) {
2534                         RenderPass *rpass;
2535
2536                         /* there's no combined pass, is in renderlayer itself */
2537                         if (pass == 0) {
2538                                 rectf = rl->rectf;
2539                         }
2540                         else {
2541                                 rpass = BLI_findlink(&rl->passes, pass - 1);
2542                                 if (rpass) {
2543                                         channels = rpass->channels;
2544                                         rectf = rpass->rect;
2545                                         dither = 0.0f; /* don't dither passes */
2546                                 }
2547                         }
2548
2549                         for (rpass = rl->passes.first; rpass; rpass = rpass->next)
2550                                 if (rpass->passtype == SCE_PASS_Z)
2551                                         rectz = rpass->rect;
2552                 }
2553         }
2554
2555         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2556
2557         /* make ibuf if needed, and initialize it */
2558         if (ibuf == NULL) {
2559                 ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2560                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2561         }
2562
2563         ibuf->x = rres.rectx;
2564         ibuf->y = rres.recty;
2565
2566         /* free rect buffer if float buffer changes, so it can be recreated with
2567          * the updated result, and also in case we got byte buffer from sequencer,
2568          * so we don't keep reference to freed buffer */
2569         if (ibuf->rect_float != rectf || rect || !rectf)
2570                 imb_freerectImBuf(ibuf);
2571
2572         if (rect)
2573                 ibuf->rect = rect;
2574
2575         if (rectf) {
2576                 ibuf->rect_float = rectf;
2577                 ibuf->flags |= IB_rectfloat;
2578                 ibuf->channels = channels;
2579         }
2580         else {
2581                 ibuf->rect_float = NULL;
2582                 ibuf->flags &= ~IB_rectfloat;
2583         }
2584
2585         if (rectz) {
2586                 ibuf->zbuf_float = rectz;
2587                 ibuf->flags |= IB_zbuffloat;
2588         }
2589         else {
2590                 ibuf->zbuf_float = NULL;
2591                 ibuf->flags &= ~IB_zbuffloat;
2592         }
2593
2594         /* since its possible to access the buffer from the image directly, set the profile [#25073] */
2595         ibuf->profile = (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) ? IB_PROFILE_LINEAR_RGB : IB_PROFILE_NONE;
2596         ibuf->dither = dither;
2597
2598         if (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT_PREDIVIDE) {
2599                 ibuf->flags |= IB_cm_predivide;
2600                 ima->flag |= IMA_CM_PREDIVIDE;
2601         }
2602         else {
2603                 ibuf->flags &= ~IB_cm_predivide;
2604                 ima->flag &= ~IMA_CM_PREDIVIDE;
2605         }
2606
2607         ima->ok = IMA_OK_LOADED;
2608
2609         return ibuf;
2610 }
2611
2612 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2613 {
2614         ImBuf *ibuf = NULL;
2615         int frame = 0, index = 0;
2616
2617         /* see if we already have an appropriate ibuf, with image source and type */
2618         if (ima->source == IMA_SRC_MOVIE) {
2619                 frame = iuser ? iuser->framenr : ima->lastframe;
2620                 ibuf = image_get_ibuf(ima, 0, frame);
2621                 /* XXX temp stuff? */
2622                 if (ima->lastframe != frame)
2623                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2624                 ima->lastframe = frame;
2625         }
2626         else if (ima->source == IMA_SRC_SEQUENCE) {
2627                 if (ima->type == IMA_TYPE_IMAGE) {
2628                         frame = iuser ? iuser->framenr : ima->lastframe;
2629                         ibuf = image_get_ibuf(ima, 0, frame);
2630
2631                         /* XXX temp stuff? */
2632                         if (ima->lastframe != frame) {
2633                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2634                         }
2635                         ima->lastframe = frame;
2636                 }
2637                 else if (ima->type == IMA_TYPE_MULTILAYER) {
2638                         frame = iuser ? iuser->framenr : ima->lastframe;
2639                         index = iuser ? iuser->multi_index : IMA_NO_INDEX;
2640                         ibuf = image_get_ibuf(ima, index, frame);
2641                 }
2642         }
2643         else if (ima->source == IMA_SRC_FILE) {
2644                 if (ima->type == IMA_TYPE_IMAGE)
2645                         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2646                 else if (ima->type == IMA_TYPE_MULTILAYER)
2647                         ibuf = image_get_ibuf(ima, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2648         }
2649         else if (ima->source == IMA_SRC_GENERATED) {
2650                 ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2651         }
2652         else if (ima->source == IMA_SRC_VIEWER) {
2653                 /* always verify entirely, not that this shouldn't happen
2654                  * as part of texture sampling in rendering anyway, so not
2655                  * a big bottleneck */
2656         }
2657
2658         *frame_r = frame;
2659         *index_r = index;
2660
2661         return ibuf;
2662 }
2663
2664 /* Checks optional ImageUser and verifies/creates ImBuf. */
2665 /* use this one if you want to get a render result in progress,
2666  * if not, use BKE_image_get_ibuf which doesn't require a release */
2667 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2668 {
2669         ImBuf *ibuf = NULL;
2670         float color[] = {0, 0, 0, 1};
2671         int frame = 0, index = 0;
2672
2673         /* This function is intended to be thread-safe. It postpones the mutex lock
2674          * until it needs to load the image, if the image is already there it
2675          * should just get the pointer and return. The reason is that a lot of mutex
2676          * locks appears to be very slow on certain multicore macs, causing a render
2677          * with image textures to actually slow down as more threads are used.
2678          *
2679          * Note that all the image loading functions should also make sure they do
2680          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2681          * That means, the last two steps must be, 1) add the ibuf to the list and
2682          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2683
2684         if (lock_r)
2685                 *lock_r = NULL;
2686
2687         /* quick reject tests */
2688         if (ima == NULL)
2689                 return NULL;
2690         if (iuser) {
2691                 if (iuser->ok == 0)
2692                         return NULL;
2693         }
2694         else if (ima->ok == 0)
2695                 return NULL;
2696
2697         /* try to get the ibuf without locking */
2698         ibuf = image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2699
2700         if (ibuf == NULL) {
2701                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2702                  * load the image */
2703                 BLI_lock_thread(LOCK_IMAGE);
2704
2705                 /* need to check ok flag and loading ibuf again, because the situation
2706                  * might have changed in the meantime */
2707                 if (iuser) {
2708                         if (iuser->ok == 0) {
2709                                 BLI_unlock_thread(LOCK_IMAGE);
2710                                 return NULL;
2711                         }
2712                 }
2713                 else if (ima->ok == 0) {
2714                         BLI_unlock_thread(LOCK_IMAGE);
2715                         return NULL;
2716                 }
2717
2718                 ibuf = image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2719
2720                 if (ibuf == NULL) {
2721                         /* we are sure we have to load the ibuf, using source and type */
2722                         if (ima->source == IMA_SRC_MOVIE) {
2723                                 /* source is from single file, use flipbook to store ibuf */
2724                                 ibuf = image_load_movie_file(ima, iuser, frame);
2725                         }
2726                         else if (ima->source == IMA_SRC_SEQUENCE) {
2727                                 if (ima->type == IMA_TYPE_IMAGE) {
2728                                         /* regular files, ibufs in flipbook, allows saving */
2729                                         ibuf = image_load_sequence_file(ima, iuser, frame);
2730                                 }
2731                                 /* no else; on load the ima type can change */
2732                                 if (ima->type == IMA_TYPE_MULTILAYER) {
2733                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2734                                         ibuf = image_load_sequence_multilayer(ima, iuser, frame);
2735                                 }
2736                         }
2737                         else if (ima->source == IMA_SRC_FILE) {
2738
2739                                 if (ima->type == IMA_TYPE_IMAGE)
2740                                         ibuf = image_load_image_file(ima, iuser, frame);  /* cfra only for '#', this global is OK */
2741                                 /* no else; on load the ima type can change */
2742                                 if (ima->type == IMA_TYPE_MULTILAYER)
2743                                         /* keeps render result, stores ibufs in listbase, allows saving */
2744                                         ibuf = image_get_ibuf_multilayer(ima, iuser);
2745
2746                         }
2747                         else if (ima->source == IMA_SRC_GENERATED) {
2748                                 /* generated is: ibuf is allocated dynamically */
2749                                 /* UV testgrid or black or solid etc */
2750                                 if (ima->gen_x == 0) ima->gen_x = 1024;
2751                                 if (ima->gen_y == 0) ima->gen_y = 1024;
2752                                 ibuf = add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type, color);
2753                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2754                                 ima->ok = IMA_OK_LOADED;
2755                         }
2756                         else if (ima->source == IMA_SRC_VIEWER) {
2757                                 if (ima->type == IMA_TYPE_R_RESULT) {
2758                                         /* always verify entirely, and potentially
2759                                          * returns pointer to release later */
2760                                         ibuf = image_get_render_result(ima, iuser, lock_r);
2761                                 }
2762                                 else if (ima->type == IMA_TYPE_COMPOSITE) {
2763                                         /* requires lock/unlock, otherwise don't return image */
2764                                         if (lock_r) {
2765                                                 /* unlock in BKE_image_release_ibuf */
2766                                                 BLI_lock_thread(LOCK_VIEWER);
2767                                                 *lock_r = ima;
2768
2769                                                 /* XXX anim play for viewer nodes not yet supported */
2770                                                 frame = 0; // XXX iuser?iuser->framenr:0;
2771                                                 ibuf = image_get_ibuf(ima, 0, frame);
2772
2773                                                 if (!ibuf) {
2774                                                         /* Composite Viewer, all handled in compositor */
2775                                                         /* fake ibuf, will be filled in compositor */
2776                                                         ibuf = IMB_allocImBuf(256, 256, 32, IB_rect);
2777                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2778                                                 }
2779                                         }
2780                                 }
2781                         }
2782                 }
2783
2784                 BLI_unlock_thread(LOCK_IMAGE);
2785         }
2786
2787         BKE_image_tag_time(ima);
2788
2789         return ibuf;
2790 }
2791
2792 void BKE_image_release_ibuf(Image *ima, void *lock)
2793 {
2794         /* for getting image during threaded render / compositing, need to release */
2795         if (lock == ima) {
2796                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2797         }
2798         else if (lock) {
2799                 RE_ReleaseResultImage(lock); /* render result */
2800                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2801         }
2802 }
2803
2804 /* warning, this can allocate generated images */
2805 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2806 {
2807         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2808         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2809 }
2810
2811 int BKE_image_user_frame_get(const ImageUser *iuser, int cfra, int fieldnr, short *r_is_in_range)
2812 {
2813         const int len = (iuser->fie_ima * iuser->frames) / 2;
2814
2815         if (r_is_in_range) {
2816                 *r_is_in_range = FALSE;
2817         }
2818
2819         if (len == 0) {
2820                 return 0;
2821         }
2822         else {
2823                 int framenr;
2824                 cfra = cfra - iuser->sfra + 1;
2825
2826                 /* cyclic */
2827                 if (iuser->cycl) {
2828                         cfra = ((cfra) % len);
2829                         if (cfra < 0) cfra += len;
2830                         if (cfra == 0) cfra = len;
2831
2832                         if (r_is_in_range) {
2833                                 *r_is_in_range = TRUE;
2834                         }
2835                 }
2836
2837                 if (cfra < 0) {
2838                         cfra = 0;
2839                 }
2840                 else if (cfra > len) {
2841                         cfra = len;
2842                 }
2843                 else {
2844                         if (r_is_in_range) {
2845                                 *r_is_in_range = TRUE;
2846                         }
2847                 }
2848
2849                 /* convert current frame to current field */
2850                 cfra = 2 * (cfra);
2851                 if (fieldnr) cfra++;
2852
2853                 /* transform to images space */
2854                 framenr = (cfra + iuser->fie_ima - 2) / iuser->fie_ima;
2855                 if (framenr > iuser->frames) framenr = iuser->frames;
2856
2857                 if (iuser->cycl) {
2858                         framenr = ((framenr) % len);
2859                         while (framenr < 0) framenr += len;
2860                         if (framenr == 0) framenr = len;
2861                 }
2862
2863                 /* important to apply after else we cant loop on frames 100 - 110 for eg. */
2864                 framenr += iuser->offset;
2865
2866                 return framenr;
2867         }
2868 }
2869
2870 void BKE_image_user_frame_calc(ImageUser *iuser, int cfra, int fieldnr)
2871 {
2872         if (iuser) {
2873                 short is_in_range;
2874                 const int framenr = BKE_image_user_frame_get(iuser, cfra, fieldnr, &is_in_range);
2875
2876                 if (is_in_range) {
2877                         iuser->flag |= IMA_USER_FRAME_IN_RANGE;
2878                 }
2879                 else {
2880                         iuser->flag &= ~IMA_USER_FRAME_IN_RANGE;
2881                 }
2882
2883                 /* allows image users to handle redraws */
2884                 if (iuser->flag & IMA_ANIM_ALWAYS)
2885                         if (framenr != iuser->framenr)
2886                                 iuser->flag |= IMA_ANIM_REFRESHED;
2887
2888                 iuser->framenr = framenr;
2889                 if (iuser->ok == 0) iuser->ok = 1;
2890         }
2891 }
2892
2893 void BKE_image_user_check_frame_calc(ImageUser *iuser, int cfra, int fieldnr)
2894 {
2895         if ((iuser->flag & IMA_ANIM_ALWAYS) || (iuser->flag & IMA_NEED_FRAME_RECALC)) {
2896                 BKE_image_user_frame_calc(iuser, cfra, fieldnr);
2897
2898                 iuser->flag &= ~IMA_NEED_FRAME_RECALC;
2899         }
2900 }
2901
2902 void BKE_image_user_file_path(ImageUser *iuser, Image *ima, char *filepath)
2903 {
2904         BLI_strncpy(filepath, ima->name, FILE_MAX);
2905
2906         if (ima->source == IMA_SRC_SEQUENCE) {
2907                 char head[FILE_MAX], tail[FILE_MAX];
2908                 unsigned short numlen;
2909                 int frame = iuser ? iuser->framenr : ima->lastframe;
2910
2911                 BLI_stringdec(filepath, head, tail, &numlen);
2912                 BLI_stringenc(filepath, head, tail, numlen, frame);
2913         }
2914
2915         BLI_path_abs(filepath, ID_BLEND_PATH(G.main, &ima->id));
2916 }
2917
2918 int BKE_image_has_alpha(struct Image *image)
2919 {
2920         ImBuf *ibuf;
2921         void *lock;
2922         int planes;
2923
2924         ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
2925         planes = (ibuf ? ibuf->planes : 0);
2926         BKE_image_release_ibuf(image, lock);
2927
2928         if (planes == 32)
2929                 return 1;
2930         else
2931                 return 0;
2932 }