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