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