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