Image Stamping patch by Diego (and peach request)- stamps image info into metadata...
[blender.git] / source / blender / blenkernel / intern / image.c
1 /*  image.c        
2  * 
3  * $Id$
4  *
5  * ***** BEGIN GPL LICENSE BLOCK *****
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software Foundation,
19  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20  *
21  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
22  * All rights reserved.
23  *
24  * The Original Code is: all of this file.
25  *
26  * Contributor(s): Blender Foundation, 2006
27  *
28  * ***** END GPL LICENSE BLOCK *****
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 #include "MEM_guardedalloc.h"
44
45 #include "IMB_imbuf_types.h"
46 #include "IMB_imbuf.h"
47
48 #ifdef WITH_OPENEXR
49 #include "intern/openexr/openexr_multi.h"
50 #endif
51
52 #include "DNA_image_types.h"
53 #include "DNA_packedFile_types.h"
54 #include "DNA_scene_types.h"
55 #include "DNA_camera_types.h"
56 #include "DNA_texture_types.h"
57 #include "DNA_userdef_types.h"
58
59 #include "BLI_arithb.h"
60 #include "BLI_blenlib.h"
61 #include "BLI_threads.h"
62
63 #include "BKE_bmfont.h"
64 #include "BKE_global.h"
65 #include "BKE_icons.h"
66 #include "BKE_image.h"
67 #include "BKE_library.h"
68 #include "BKE_main.h"
69 #include "BKE_packedFile.h"
70 #include "BKE_scene.h"
71 #include "BKE_texture.h"
72 #include "BKE_utildefines.h"
73
74 #include "PIL_time.h"
75
76 #include "RE_pipeline.h"
77
78 /* bad level; call to free_realtime_image */
79 #include "BKE_bad_level_calls.h"        
80
81 /* for stamp drawing to an image */
82 #include "../bmfont/BMF_Api.h"
83
84 #include "blendef.h"
85 #include "BSE_time.h"
86
87 /* max int, to indicate we don't store sequences in ibuf */
88 #define IMA_NO_INDEX    0x7FEFEFEF
89
90 /* quick lookup: supports 1 million frames, thousand passes */
91 #define IMA_MAKE_INDEX(frame, index)    ((frame)<<10)+index
92 #define IMA_INDEX_FRAME(index)                  (index>>10)
93
94 /* ******** IMAGE PROCESSING ************* */
95
96 /* used by sequencer */
97 void converttopremul(struct ImBuf *ibuf)
98 {
99         int x, y, val;
100         char *cp;
101         
102         if(ibuf==0) return;
103         if(ibuf->depth==24) {   /* put alpha at 255 */
104                 
105                 cp= (char *)(ibuf->rect);
106                 for(y=0; y<ibuf->y; y++) {
107                         for(x=0; x<ibuf->x; x++, cp+=4) {
108                                 cp[3]= 255;
109                         }
110                 }
111                 return;
112         }
113
114         cp= (char *)(ibuf->rect);
115         for(y=0; y<ibuf->y; y++) {
116                 for(x=0; x<ibuf->x; x++, cp+=4) {
117                         if(cp[3]==0) {
118                                 cp[0]= cp[1]= cp[2]= 0;
119                         }
120                         else if(cp[3]!=255) {
121                                 val= cp[3];
122                                 cp[0]= (cp[0]*val)>>8;
123                                 cp[1]= (cp[1]*val)>>8;
124                                 cp[2]= (cp[2]*val)>>8;
125                         }
126                 }
127         }
128 }
129
130 static void de_interlace_ng(struct ImBuf *ibuf) /* neogeo fields */
131 {
132         struct ImBuf * tbuf1, * tbuf2;
133         
134         if (ibuf == 0) return;
135         if (ibuf->flags & IB_fields) return;
136         ibuf->flags |= IB_fields;
137         
138         if (ibuf->rect) {
139                 /* make copies */
140                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect, (unsigned char)0);
141                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect, (unsigned char)0);
142                 
143                 ibuf->x *= 2;
144                 
145                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
146                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
147                 
148                 ibuf->x /= 2;
149                 IMB_rectcpy(ibuf, tbuf1, 0, 0, 0, 0, tbuf1->x, tbuf1->y);
150                 IMB_rectcpy(ibuf, tbuf2, 0, tbuf2->y, 0, 0, tbuf2->x, tbuf2->y);
151                 
152                 IMB_freeImBuf(tbuf1);
153                 IMB_freeImBuf(tbuf2);
154         }
155         ibuf->y /= 2;
156 }
157
158 static void de_interlace_st(struct ImBuf *ibuf) /* standard fields */
159 {
160         struct ImBuf * tbuf1, * tbuf2;
161         
162         if (ibuf == 0) return;
163         if (ibuf->flags & IB_fields) return;
164         ibuf->flags |= IB_fields;
165         
166         if (ibuf->rect) {
167                 /* make copies */
168                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect, 0);
169                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect, 0);
170                 
171                 ibuf->x *= 2;
172                 
173                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
174                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
175                 
176                 ibuf->x /= 2;
177                 IMB_rectcpy(ibuf, tbuf2, 0, 0, 0, 0, tbuf2->x, tbuf2->y);
178                 IMB_rectcpy(ibuf, tbuf1, 0, tbuf2->y, 0, 0, tbuf1->x, tbuf1->y);
179                 
180                 IMB_freeImBuf(tbuf1);
181                 IMB_freeImBuf(tbuf2);
182         }
183         ibuf->y /= 2;
184 }
185
186 void image_de_interlace(Image *ima, int odd)
187 {
188         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
189         if(ibuf) {
190                 if(odd)
191                         de_interlace_st(ibuf);
192                 else
193                         de_interlace_ng(ibuf);
194         }
195 }
196
197 /* ***************** ALLOC & FREE, DATA MANAGING *************** */
198
199 static void image_free_buffers(Image *ima)
200 {
201         ImBuf *ibuf;
202         
203         while((ibuf = ima->ibufs.first)) {
204                 BLI_remlink(&ima->ibufs, ibuf);
205                 
206                 if (ibuf->userdata) {
207                         MEM_freeN(ibuf->userdata);
208                         ibuf->userdata = NULL;
209                 }
210                 IMB_freeImBuf(ibuf);
211         }
212         
213         if(ima->anim) IMB_free_anim(ima->anim);
214         ima->anim= NULL;
215         
216         if(ima->rr) {
217                 RE_FreeRenderResult(ima->rr);
218                 ima->rr= NULL;
219         }       
220         
221         free_realtime_image(ima);
222         
223         ima->ok= IMA_OK;
224 }
225
226 /* called by library too, do not free ima itself */
227 void free_image(Image *ima)
228 {
229
230         image_free_buffers(ima);
231         if (ima->packedfile) {
232                 freePackedFile(ima->packedfile);
233                 ima->packedfile = NULL;
234         }
235         BKE_icon_delete(&ima->id);
236         ima->id.icon_id = 0;
237         if (ima->preview) {
238                 BKE_previewimg_free(&ima->preview);
239         }
240         
241 }
242
243 /* only image block itself */
244 static Image *image_alloc(const char *name, short source, short type)
245 {
246         Image *ima;
247         
248         ima= alloc_libblock(&G.main->image, ID_IM, name);
249         if(ima) {
250                 ima->ok= IMA_OK;
251                 
252                 ima->xrep= ima->yrep= 1;
253                 ima->aspx= ima->aspy= 1.0;
254                 ima->gen_x= 256; ima->gen_y= 256;
255                 ima->gen_type= 1;       /* no defines yet? */
256                 
257                 ima->source= source;
258                 ima->type= type;
259         }
260         return ima;
261 }
262
263 /* get the ibuf from an image cache, local use here only */
264 static ImBuf *image_get_ibuf(Image *ima, int index, int frame)
265 {
266         if(index==IMA_NO_INDEX)
267                 return ima->ibufs.first;
268         else {
269                 ImBuf *ibuf;
270                 
271                 index= IMA_MAKE_INDEX(frame, index);
272                 for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next)
273                         if(ibuf->index==index)
274                                 return ibuf;
275                 return NULL;
276         }
277 }
278
279 /* no ima->ibuf anymore, but listbase */
280 static void image_remove_ibuf(Image *ima, ImBuf *ibuf)
281 {
282         if(ibuf) {
283                 BLI_remlink(&ima->ibufs, ibuf);
284                 IMB_freeImBuf(ibuf);
285         }
286 }
287
288
289 /* no ima->ibuf anymore, but listbase */
290 static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
291 {
292         if(ibuf) {
293                 ImBuf *link;
294                 
295                 if(index!=IMA_NO_INDEX)
296                         index= IMA_MAKE_INDEX(frame, index);
297                 
298                 /* insert based on index */
299                 for(link= ima->ibufs.first; link; link= link->next)
300                         if(link->index>=index)
301                                 break;
302                 /* now we don't want copies? */
303                 if(link && ibuf->index==link->index) {
304                         ImBuf *prev= ibuf->prev;
305                         image_remove_ibuf(ima, link);
306                         link= prev;
307                 }
308                 
309                 /* this function accepts link==NULL */
310                 BLI_insertlinkbefore(&ima->ibufs, link, ibuf);
311                 
312                 ibuf->index= index;
313         }
314         
315 }
316
317 /* checks if image was already loaded, then returns same image */
318 /* otherwise creates new. */
319 /* does not load ibuf itself */
320 Image *BKE_add_image_file(const char *name)
321 {
322         Image *ima;
323         int file, len;
324         const char *libname;
325         char str[FILE_MAX], strtest[FILE_MAX];
326         
327         /* escape when name is directory */
328         len= strlen(name);
329         if(len) {
330                 if(name[len-1]=='/' || name[len-1]=='\\')
331                         return NULL;
332         }
333         
334         BLI_strncpy(str, name, sizeof(str));
335         BLI_convertstringcode(str, G.sce, G.scene->r.cfra);
336         
337         /* exists? */
338         file= open(str, O_BINARY|O_RDONLY);
339         if(file== -1) return NULL;
340         close(file);
341         
342         /* first search an identical image */
343         for(ima= G.main->image.first; ima; ima= ima->id.next) {
344                 if(ima->source!=IMA_SRC_VIEWER) {
345                         BLI_strncpy(strtest, ima->name, sizeof(ima->name));
346                         BLI_convertstringcode(strtest, G.sce, G.scene->r.cfra);
347                         
348                         if( strcmp(strtest, str)==0 ) {
349                                 if(ima->anim==NULL || ima->id.us==0) {
350                                         BLI_strncpy(ima->name, name, sizeof(ima->name));        /* for stringcode */
351                                         ima->id.us++;                                                                           /* officially should not, it doesn't link here! */
352                                         if(ima->ok==0)
353                                                 ima->ok= IMA_OK;
354                         /* RETURN! */
355                                         return ima;
356                                 }
357                         }
358                 }
359         }
360         /* add new image */
361         
362         /* create a short library name */
363         len= strlen(name);
364         
365         while (len > 0 && name[len - 1] != '/' && name[len - 1] != '\\') len--;
366         libname= name+len;
367         
368         ima= image_alloc(libname, IMA_SRC_FILE, IMA_TYPE_IMAGE);
369         BLI_strncpy(ima->name, name, sizeof(ima->name));
370         
371         /* do a wild guess! */
372         if(BLI_testextensie(name, ".avi") || BLI_testextensie(name, ".mov")
373                         || BLI_testextensie(name, ".mpg")  || BLI_testextensie(name, ".mp4"))
374                 ima->source= IMA_SRC_MOVIE;
375         
376         return ima;
377 }
378
379 static ImBuf *add_ibuf_size(int width, int height, char *name, short uvtestgrid, float color[4])
380 {
381         ImBuf *ibuf;
382         float h=0.0, hoffs=0.0, hue=0.0, s=0.9, v=0.9, r, g, b;
383         unsigned char *rect;
384         int x, y;
385         int checkerwidth=21, dark=1;
386         
387         ibuf= IMB_allocImBuf(width, height, 24, IB_rect, 0);
388         strcpy(ibuf->name, "Untitled");
389         ibuf->userflags |= IB_BITMAPDIRTY;
390         
391         rect= (unsigned char*)ibuf->rect;
392         
393         if (uvtestgrid) {
394                 /* these two passes could be combined into one, but it's more readable and 
395                 * easy to tweak like this, speed isn't really that much of an issue in this situation... */
396                 
397                 /* checkers */
398                 for(y=0; y<ibuf->y; y++) {
399                         dark = pow(-1, floor(y / checkerwidth));
400                         
401                         for(x=0; x<ibuf->x; x++, rect+=4) {
402                                 if (x % checkerwidth == 0) dark *= -1;
403                                 
404                                 if (dark > 0) {
405                                         rect[0] = rect[1] = rect[2] = 64;
406                                         rect[3] = 255;
407                                 } else {
408                                         rect[0] = rect[1] = rect[2] = 150;
409                                         rect[3] = 255;
410                                 }
411                         }
412                 }
413                 
414                 /* 2nd pass, colored + */
415                 rect= (unsigned char*)ibuf->rect;
416                 
417                 for(y=0; y<ibuf->y; y++) {
418                         hoffs = 0.125 * floor(y / checkerwidth);
419                         
420                         for(x=0; x<ibuf->x; x++, rect+=4) {
421                                 h = 0.125 * floor(x / checkerwidth);
422                                 
423                                 if ((fabs((x % checkerwidth) - (checkerwidth / 2)) < 4) &&
424                                         (fabs((y % checkerwidth) - (checkerwidth / 2)) < 4)) {
425                                         
426                                         if ((fabs((x % checkerwidth) - (checkerwidth / 2)) < 1) ||
427                                                 (fabs((y % checkerwidth) - (checkerwidth / 2)) < 1)) {
428                                                 
429                                                 hue = fmod(fabs(h-hoffs), 1.0);
430                                                 hsv_to_rgb(hue, s, v, &r, &g, &b);
431                                                 
432                                                 rect[0]= (char)(r * 255.0);
433                                                 rect[1]= (char)(g * 255.0);
434                                                 rect[2]= (char)(b * 255.0);
435                                                 rect[3]= 255;
436                                         }
437                                 }
438                                 
439                         }
440                 }
441         } else {        /* blank image */
442                 for(y=0; y<ibuf->y; y++) {
443                         for(x=0; x<ibuf->x; x++, rect+=4) {
444                                 rect[0]= (char)(color[0] * 255.0);
445                                 rect[1]= (char)(color[1] * 255.0);
446                                 rect[2]= (char)(color[2] * 255.0);
447                                 rect[3]= (char)(color[3] * 255.0);
448                         }
449                 }
450         }
451         return ibuf;
452 }
453
454 /* adds new image block, creates ImBuf and initializes color */
455 Image *BKE_add_image_size(int width, int height, char *name, short uvtestgrid, float color[4])
456 {
457         Image *ima;
458         
459         /* on save, type is changed to FILE in editsima.c */
460         ima= image_alloc(name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
461         
462         if (ima) {
463                 ImBuf *ibuf;
464                 
465                 BLI_strncpy(ima->name, name, FILE_MAX);
466                 ima->gen_x= width;
467                 ima->gen_y= height;
468                 ima->gen_type= uvtestgrid;
469                 
470                 ibuf= add_ibuf_size(width, height, name, uvtestgrid, color);
471                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
472                 
473                 ima->ok= IMA_OK_LOADED;
474         }
475
476         return ima;
477 }
478
479 /* packs rect from memory as PNG */
480 void BKE_image_memorypack(Image *ima)
481 {
482         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
483         
484         if(ibuf==NULL)
485                 return;
486         if (ima->packedfile) {
487                 freePackedFile(ima->packedfile);
488                 ima->packedfile = NULL;
489         }
490         
491         ibuf->ftype= PNG;
492         ibuf->depth= 32;
493         
494         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
495         if(ibuf->encodedbuffer==NULL) {
496                 printf("memory save for pack error\n");
497         }
498         else {
499                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
500                 
501                 pf->data = ibuf->encodedbuffer;
502                 pf->size = ibuf->encodedsize;
503                 ima->packedfile= pf;
504                 ibuf->encodedbuffer= NULL;
505                 ibuf->encodedsize= 0;
506                 ibuf->userflags &= ~IB_BITMAPDIRTY;
507                 
508                 if(ima->source==IMA_SRC_GENERATED) {
509                         ima->source= IMA_SRC_FILE;
510                         ima->type= IMA_TYPE_IMAGE;
511                 }
512         }
513 }
514
515 void tag_image_time(Image *ima)
516 {
517         if (ima)
518                 ima->lastused = (int)PIL_check_seconds_timer();
519 }
520
521 void tag_all_images_time() 
522 {
523         Image *ima;
524         int ctime = (int)PIL_check_seconds_timer();
525
526         ima= G.main->image.first;
527         while(ima) {
528                 if(ima->bindcode || ima->repbind || ima->ibufs.first) {
529                         ima->lastused = ctime;
530                 }
531         }
532 }
533
534 void free_old_images()
535 {
536         Image *ima;
537         static int lasttime = 0;
538         int ctime = (int)PIL_check_seconds_timer();
539         
540         /* 
541            Run garbage collector once for every collecting period of time 
542            if textimeout is 0, that's the option to NOT run the collector
543         */
544         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
545                 return;
546
547         lasttime = ctime;
548
549         ima= G.main->image.first;
550         while(ima) {
551                 if((ima->flag & IMA_NOCOLLECT)==0 && ctime - ima->lastused > U.textimeout) {
552                         /*
553                            If it's in GL memory, deallocate and set time tag to current time
554                            This gives textures a "second chance" to be used before dying.
555                         */
556                         if(ima->bindcode || ima->repbind) {
557                                 free_realtime_image(ima);
558                                 ima->lastused = ctime;
559                         }
560                         /* Otherwise, just kill the buffers */
561                         else if (ima->ibufs.first) {
562                                 image_free_buffers(ima);
563                         }
564                 }
565                 ima = ima->id.next;
566         }
567 }
568
569 void BKE_image_free_all_textures(void)
570 {
571         Tex *tex;
572         Image *ima;
573         unsigned int totsize= 0;
574         
575         for(ima= G.main->image.first; ima; ima= ima->id.next)
576                 ima->id.flag &= ~LIB_DOIT;
577         
578         for(tex= G.main->tex.first; tex; tex= tex->id.next)
579                 if(tex->ima)
580                         tex->ima->id.flag |= LIB_DOIT;
581         
582         for(ima= G.main->image.first; ima; ima= ima->id.next) {
583                 if(ima->ibufs.first && (ima->id.flag & LIB_DOIT)) {
584                         ImBuf *ibuf;
585                         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
586                                 if(ibuf->mipmap[0]) 
587                                         totsize+= 1.33*ibuf->x*ibuf->y*4;
588                                 else
589                                         totsize+= ibuf->x*ibuf->y*4;
590                         }
591                         image_free_buffers(ima);
592                 }
593         }
594         /* printf("freed total %d MB\n", totsize/(1024*1024)); */
595 }
596
597 /* except_frame is weak, only works for seqs without offset... */
598 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
599 {
600         ImBuf *ibuf, *nbuf;
601
602         for(ibuf= ima->ibufs.first; ibuf; ibuf= nbuf) {
603                 nbuf= ibuf->next;
604                 if(ibuf->userflags & IB_BITMAPDIRTY)
605                         continue;
606                 if(ibuf->index==IMA_NO_INDEX)
607                         continue;
608                 if(except_frame!=IMA_INDEX_FRAME(ibuf->index)) {
609                         BLI_remlink(&ima->ibufs, ibuf);
610                         
611                         if (ibuf->userdata) {
612                                 MEM_freeN(ibuf->userdata);
613                                 ibuf->userdata = NULL;
614                         }
615                         IMB_freeImBuf(ibuf);
616                 }                                       
617         }
618 }
619
620 void BKE_image_all_free_anim_ibufs(int cfra)
621 {
622         Image *ima;
623         
624         for(ima= G.main->image.first; ima; ima= ima->id.next)
625                 if(ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE))
626                         BKE_image_free_anim_ibufs(ima, cfra);
627 }
628
629
630 /* *********** READ AND WRITE ************** */
631
632 int BKE_imtype_to_ftype(int imtype)
633 {
634         if(imtype==0)
635                 return TGA;
636         else if(imtype== R_IRIS) 
637                 return IMAGIC;
638         else if (imtype==R_RADHDR)
639                 return RADHDR;
640         else if (imtype==R_PNG)
641                 return PNG;
642 #ifdef WITH_DDS
643         else if (imtype==R_DDS)
644                 return DDS;
645 #endif
646         else if (imtype==R_BMP)
647                 return BMP;
648         else if (imtype==R_TIFF)
649                 return TIF;
650         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER)
651                 return OPENEXR;
652         else if (imtype==R_CINEON)
653                 return CINEON;
654         else if (imtype==R_DPX)
655                 return DPX;
656         else if (imtype==R_TARGA)
657                 return TGA;
658         else if(imtype==R_RAWTGA)
659                 return RAWTGA;
660         else if(imtype==R_HAMX)
661                 return AN_hamx;
662         else
663                 return JPG|90;
664 }
665
666 int BKE_ftype_to_imtype(int ftype)
667 {
668         if(ftype==0)
669                 return TGA;
670         else if(ftype == IMAGIC) 
671                 return R_IRIS;
672         else if (ftype & RADHDR)
673                 return R_RADHDR;
674         else if (ftype & PNG)
675                 return R_PNG;
676 #ifdef WITH_DDS
677         else if (ftype & DDS)
678                 return R_DDS;
679 #endif
680         else if (ftype & BMP)
681                 return R_BMP;
682         else if (ftype & TIF)
683                 return R_TIFF;
684         else if (ftype & OPENEXR)
685                 return R_OPENEXR;
686         else if (ftype & CINEON)
687                 return R_CINEON;
688         else if (ftype & DPX)
689                 return R_DPX;
690         else if (ftype & TGA)
691                 return R_TARGA;
692         else if(ftype & RAWTGA)
693                 return R_RAWTGA;
694         else if(ftype == AN_hamx)
695                 return R_HAMX;
696         else
697                 return R_JPEG90;
698 }
699
700
701 int BKE_imtype_is_movie(int imtype)
702 {
703         switch(imtype) {
704         case R_MOVIE:
705         case R_AVIRAW:
706         case R_AVIJPEG:
707         case R_AVICODEC:
708         case R_QUICKTIME:
709         case R_FFMPEG:
710         case R_FRAMESERVER:
711                         return 1;
712         }
713         return 0;
714 }
715
716 void BKE_add_image_extension(char *string, int imtype)
717 {
718         char *extension="";
719         
720         if(G.scene->r.imtype== R_IRIS) {
721                 if(!BLI_testextensie(string, ".rgb"))
722                         extension= ".rgb";
723         }
724         else if(imtype==R_IRIZ) {
725                 if(!BLI_testextensie(string, ".rgb"))
726                         extension= ".rgb";
727         }
728         else if(imtype==R_RADHDR) {
729                 if(!BLI_testextensie(string, ".hdr"))
730                         extension= ".hdr";
731         }
732         else if(imtype==R_PNG) {
733                 if(!BLI_testextensie(string, ".png"))
734                         extension= ".png";
735         }
736 #ifdef WITH_DDS
737         else if(imtype==R_DDS) {
738                 if(!BLI_testextensie(string, ".dds"))
739                         extension= ".dds";
740         }
741 #endif
742         else if(imtype==R_RAWTGA) {
743                 if(!BLI_testextensie(string, ".tga"))
744                         extension= ".tga";
745         }
746         else if(ELEM5(imtype, R_MOVIE, R_AVICODEC, R_AVIRAW, R_AVIJPEG, R_JPEG90)) {
747                 if(!BLI_testextensie(string, ".jpg"))
748                         extension= ".jpg";
749         }
750         else if(imtype==R_BMP) {
751                 if(!BLI_testextensie(string, ".bmp"))
752                         extension= ".bmp";
753         }
754         else if(G.have_libtiff && (imtype==R_TIFF)) {
755                 if(!BLI_testextensie(string, ".tif"))
756                         extension= ".tif";
757         }
758 #ifdef WITH_OPENEXR
759         else if( ELEM(imtype, R_OPENEXR, R_MULTILAYER)) {
760                 if(!BLI_testextensie(string, ".exr"))
761                         extension= ".exr";
762         }
763 #endif
764         else if(imtype==R_CINEON){
765                 if (!BLI_testextensie(string, ".cin"))
766                         extension= ".cin";
767         }
768         else if(imtype==R_DPX){
769                 if (!BLI_testextensie(string, ".dpx"))
770                         extension= ".dpx";
771         }
772         else {  /* targa default */
773                 if(!BLI_testextensie(string, ".tga"))
774                         extension= ".tga";
775         }
776
777         strcat(string, extension);
778 }
779
780 void BKE_stamp(struct ImBuf *ibuf)
781 {
782         char text[256], infotext[256];
783         int x, y, h, m, s, f;
784         int font_height;
785         int text_width;
786         int text_pad;
787         struct BMF_Font *font;
788         
789         
790 #ifndef WIN32
791         struct tm *tl;
792         time_t t;
793 #else
794         char sdate[9];
795 #endif /* WIN32 */
796
797         if (!ibuf)
798                 return;
799         
800         switch (G.scene->r.stamp_font_id) {
801         case 1: /* tiny */
802                 font = BMF_GetFont(BMF_kHelveticaBold8);
803                 break;
804         case 2: /* small */
805                 font = BMF_GetFont(BMF_kHelveticaBold10);
806                 break;
807         case 3: /* medium */
808                 font = BMF_GetFont(BMF_kScreen12);
809                 break;
810         case 0: /* large - default */
811                 font = BMF_GetFont(BMF_kScreen15);
812                 break;
813         case 4: /* huge */
814                 font = BMF_GetFont(BMF_kHelveticaBold14);
815                 break;
816         }
817         
818         font_height = BMF_GetFontHeight(font);
819         text_pad = BMF_GetStringWidth(font, " ");
820         
821         IMB_imginfo_change_field (ibuf, "File", G.sce);
822         if (G.scene->r.stamp & R_STAMP_DRAW) {
823                 x = 1;
824                 y = ibuf->y - font_height;
825                 sprintf(text, "File: %s", G.sce);
826                 text_width = BMF_GetStringWidth(font, text);
827                 IMB_rectfill_area(ibuf, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
828                 BMF_DrawStringBuf(font, G.sce, x, y, G.scene->r.fg_stamp, (unsigned char *)ibuf->rect, ibuf->rect_float, ibuf->x, ibuf->y);
829                 x = 1;
830                 y -= font_height+1;
831         }
832
833
834         if (G.scene->r.stamp & R_STAMP_TIME) {
835                 h= m= s= f= 0;
836                 f = (int)(G.scene->r.cfra % G.scene->r.frs_sec);
837                 s = (int)(G.scene->r.cfra / G.scene->r.frs_sec);
838
839                 if (s) {
840                         m = (int)(s / 60);
841                         s %= 60;
842
843                         if (m) {
844                                 h = (int)(m / 60);
845                                 m %= 60;
846                         }
847                 }
848
849                 if (G.scene->r.frs_sec < 100)
850                         sprintf (infotext, "%02d:%02d:%02d.%02d", h, m, s, f);
851                 else
852                         sprintf (infotext, "%02d:%02d:%02d.%03d", h, m, s, f);
853                 
854                 IMB_imginfo_change_field (ibuf, "Time", infotext);
855                 
856                 if (G.scene->r.stamp & R_STAMP_DRAW) {
857                         sprintf (text, "Time %s", infotext);
858                         text_width = BMF_GetStringWidth(font, text);
859                         IMB_rectfill_area(ibuf, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
860                         BMF_DrawStringBuf(font, text, x, y, G.scene->r.fg_stamp, (unsigned char *)ibuf->rect, ibuf->rect_float, ibuf->x, ibuf->y);
861                         x += text_width;
862                 }
863         }
864
865         if (G.scene->r.stamp & R_STAMP_FRAME) {
866                 sprintf (infotext, "%i", G.scene->r.cfra);
867                 IMB_imginfo_change_field (ibuf, "Frame", infotext);
868
869                 if (G.scene->r.stamp & R_STAMP_DRAW) {
870                         sprintf (text, "    Frame %s", infotext);
871                         text_width = BMF_GetStringWidth(font, text);
872                         IMB_rectfill_area(ibuf, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
873                         BMF_DrawStringBuf(font, text, x, y, G.scene->r.fg_stamp, (unsigned char *)ibuf->rect, ibuf->rect_float, ibuf->x, ibuf->y);
874                         x += BMF_GetStringWidth(font, text);
875                 }
876         }
877
878         if (G.scene->r.stamp & R_STAMP_DATE) {
879 #ifdef WIN32
880                 _strdate (sdate);
881                 sprintf (infotext, "%s", sdate);
882 #else
883                 t = time (NULL);
884                 tl = localtime (&t);
885                 sprintf (infotext, "%02d-%02d-%02d", tl->tm_mon+1, tl->tm_mday, tl->tm_year-100);
886 #endif /* WIN32 */
887                 IMB_imginfo_change_field (ibuf, "Date", infotext);
888
889                 if (G.scene->r.stamp & R_STAMP_DRAW) {
890                         x = 1;
891                         y = 1;
892                         sprintf (text, "Date %s", infotext);
893                         text_width = BMF_GetStringWidth(font, text);
894                         IMB_rectfill_area(ibuf, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
895                         BMF_DrawStringBuf(font, text, x, y, G.scene->r.fg_stamp, (unsigned char *)ibuf->rect, ibuf->rect_float, ibuf->x, ibuf->y);
896                         x += text_width;
897                 }
898         }
899
900         if (G.scene->r.stamp & R_STAMP_CAMERA) {
901                 sprintf(infotext, ((Camera *) G.scene->camera)->id.name+2);
902                 IMB_imginfo_change_field (ibuf, "Camera", infotext);
903
904                 if (G.scene->r.stamp & R_STAMP_DRAW) {
905                         sprintf (text, "Camera: %s", infotext);
906                         text_width = BMF_GetStringWidth(font, text);
907                         x = (ibuf->x/2) - (BMF_GetStringWidth(font, text)/2);
908                         y = 1;
909                         IMB_rectfill_area(ibuf, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
910                         BMF_DrawStringBuf(font, text, x, y, G.scene->r.fg_stamp, (unsigned char *)ibuf->rect, ibuf->rect_float, ibuf->x, ibuf->y);
911                 }
912         }
913
914         if (G.scene->r.stamp & R_STAMP_SCENE) {
915                 strcpy(infotext, G.scene->id.name+2);
916                 IMB_imginfo_change_field (ibuf, "Scene", infotext);
917
918                 if (G.scene->r.stamp & R_STAMP_DRAW) {
919                         sprintf (text, "Scene: %s", infotext);
920                         text_width = BMF_GetStringWidth(font, text);
921                         x = ibuf->x - (BMF_GetStringWidth(font, text)+1+text_pad);
922                         IMB_rectfill_area(ibuf, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
923                         BMF_DrawStringBuf(font, text, x, y, G.scene->r.fg_stamp, (unsigned char *)ibuf->rect, ibuf->rect_float, ibuf->x, ibuf->y);
924                 }
925         }
926         
927         if (G.scene->r.stamp & R_STAMP_NOTE) {
928                 IMB_imginfo_change_field (ibuf, "Note", G.scene->r.stamp_udata);
929  
930                 if (G.scene->r.stamp & R_STAMP_DRAW) {
931                         x = 1;
932                         y = font_height+1;
933                         text_width = BMF_GetStringWidth(font, G.scene->r.stamp_udata);
934                         IMB_rectfill_area(ibuf, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
935                         BMF_DrawStringBuf(font, G.scene->r.stamp_udata, x, y, G.scene->r.fg_stamp, (unsigned char *)ibuf->rect, ibuf->rect_float, ibuf->x, ibuf->y);
936                 }
937         }
938         
939         if (G.scene->r.stamp & R_STAMP_MARKER) {
940                 TimeMarker *marker = get_frame_marker(CFRA);
941                 
942                 if (marker) strcpy(infotext, marker->name);
943                 else            strcpy(infotext, "None");
944                 
945                 IMB_imginfo_change_field (ibuf, "Marker", infotext);
946                 
947                 if (G.scene->r.stamp & R_STAMP_DRAW) {
948                         sprintf (text, "Marker: %s", infotext);
949                         x = 1;
950                         y = ibuf->y - (font_height+1)*3;
951                         text_width = BMF_GetStringWidth(font, text);
952                         IMB_rectfill_area(ibuf, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
953                         BMF_DrawStringBuf(font, text, x, y, G.scene->r.fg_stamp, (unsigned char *)ibuf->rect, ibuf->rect_float, ibuf->x, ibuf->y);
954                 }
955         }
956 }
957
958 int BKE_write_ibuf(ImBuf *ibuf, char *name, int imtype, int subimtype, int quality)
959 {
960         int ok;
961         
962         if(imtype==0);
963         else if(imtype== R_IRIS) 
964                 ibuf->ftype= IMAGIC;
965         else if ((imtype==R_RADHDR)) {
966                 ibuf->ftype= RADHDR;
967         }
968         else if ((imtype==R_PNG)) {
969                 ibuf->ftype= PNG;
970         }
971 #ifdef WITH_DDS
972         else if ((imtype==R_DDS)) {
973                 ibuf->ftype= DDS;
974         }
975 #endif
976         else if ((imtype==R_BMP)) {
977                 ibuf->ftype= BMP;
978         }
979         else if ((G.have_libtiff) && (imtype==R_TIFF)) {
980                 ibuf->ftype= TIF;
981         }
982 #ifdef WITH_OPENEXR
983         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
984                 ibuf->ftype= OPENEXR;
985                 if(subimtype & R_OPENEXR_HALF)
986                         ibuf->ftype |= OPENEXR_HALF;
987                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
988                 
989                 if(!(subimtype & R_OPENEXR_ZBUF))
990                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
991                 
992         }
993 #endif
994         else if (imtype==R_CINEON) {
995                 ibuf->ftype = CINEON;
996         }
997         else if (imtype==R_DPX) {
998                 ibuf->ftype = DPX;
999         }
1000         else if (imtype==R_TARGA) {
1001                 ibuf->ftype= TGA;
1002         }
1003         else if(imtype==R_RAWTGA) {
1004                 ibuf->ftype= RAWTGA;
1005         }
1006         else if(imtype==R_HAMX) {
1007                 ibuf->ftype= AN_hamx;
1008         }
1009         else {
1010                 /* R_JPEG90, R_MOVIE, etc. default we save jpegs */
1011                 if(quality < 10) quality= 90;
1012                 ibuf->ftype= JPG|quality;
1013                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
1014         }
1015         
1016         BLI_make_existing_file(name);
1017
1018         if(G.scene->r.scemode & R_STAMP_INFO)
1019                 BKE_stamp(ibuf);
1020
1021         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1022         if (ok == 0) {
1023                 perror(name);
1024         }
1025         
1026         return(ok);
1027 }
1028
1029
1030 void BKE_makepicstring(char *string, char *base, int frame, int imtype)
1031 {
1032         short i, len, digits= 4;        /* digits in G.scene? */
1033         char num[10];
1034
1035         if (string==NULL) return;
1036
1037         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1038         BLI_convertstringcode(string, G.sce, frame);
1039
1040         len= strlen(string);
1041                         
1042         i= digits - sprintf(num, "%d", frame);
1043         for(; i>0; i--){
1044                 string[len]= '0';
1045                 len++;
1046         }
1047         string[len]= 0;
1048         strcat(string, num);
1049
1050         if(G.scene->r.scemode & R_EXTENSION) 
1051                 BKE_add_image_extension(string, imtype);
1052                 
1053 }
1054
1055 /* used by sequencer too */
1056 struct anim *openanim(char *name, int flags)
1057 {
1058         struct anim *anim;
1059         struct ImBuf *ibuf;
1060         
1061         anim = IMB_open_anim(name, flags);
1062         if (anim == NULL) return(0);
1063
1064         ibuf = IMB_anim_absolute(anim, 0);
1065         if (ibuf == NULL) {
1066                 printf("not an anim; %s\n", name);
1067                 IMB_free_anim(anim);
1068                 return(0);
1069         }
1070         IMB_freeImBuf(ibuf);
1071         
1072         return(anim);
1073 }
1074
1075 /* ************************* New Image API *************** */
1076
1077
1078 /* Notes about Image storage 
1079 - packedfile
1080   -> written in .blend
1081 - filename
1082   -> written in .blend
1083 - movie
1084   -> comes from packedfile or filename
1085 - renderresult
1086   -> comes from packedfile or filename
1087 - listbase
1088   -> ibufs from exrhandle
1089 - flipbook array
1090   -> ibufs come from movie, temporary renderresult or sequence
1091 - ibuf
1092   -> comes from packedfile or filename or generated
1093
1094 */
1095
1096
1097 /* forces existance of 1 Image for renderout or nodes, returns Image */
1098 /* name is only for default, when making new one */
1099 Image *BKE_image_verify_viewer(int type, const char *name)
1100 {
1101         Image *ima;
1102         
1103         for(ima=G.main->image.first; ima; ima= ima->id.next)
1104                 if(ima->source==IMA_SRC_VIEWER)
1105                         if(ima->type==type)
1106                                 break;
1107         
1108         if(ima==NULL)
1109                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1110         
1111         /* happens on reload, imagewindow cannot be image user when hidden*/
1112         if(ima->id.us==0)
1113                 id_us_plus(&ima->id);
1114
1115         return ima;
1116 }
1117
1118 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1119 {
1120         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1121 }
1122
1123 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1124 {
1125         if(ima==NULL)
1126                 return;
1127         
1128         switch(signal) {
1129         case IMA_SIGNAL_FREE:
1130                 image_free_buffers(ima);
1131                 if(iuser)
1132                         iuser->ok= 1;
1133                 break;
1134         case IMA_SIGNAL_SRC_CHANGE:
1135                 if(ima->type==IMA_TYPE_MULTILAYER)
1136                         image_free_buffers(ima);
1137                 else if(ima->source==IMA_SRC_GENERATED) {
1138                         if(ima->gen_x==0 || ima->gen_y==0) {
1139                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1140                                 if(ibuf) {
1141                                         ima->gen_x= ibuf->x;
1142                                         ima->gen_y= ibuf->y;
1143                                 }
1144                         }
1145                 }
1146                 ima->ok= 1;
1147                 if(iuser)
1148                         iuser->ok= 1;
1149                 break;
1150                         
1151         case IMA_SIGNAL_RELOAD:
1152                 /* try to repack file */
1153                 if(ima->packedfile) {
1154                         PackedFile *pf;
1155                         pf = newPackedFile(ima->name);
1156                         if (pf) {
1157                                 freePackedFile(ima->packedfile);
1158                                 ima->packedfile = pf;
1159                                 image_free_buffers(ima);
1160                         } else {
1161                                 printf("ERROR: Image not available. Keeping packed image\n");
1162                         }
1163                 }
1164                 else
1165                         image_free_buffers(ima);
1166                 
1167                 if(iuser)
1168                         iuser->ok= 1;
1169                 
1170                 break;
1171         case IMA_SIGNAL_USER_NEW_IMAGE:
1172                 if(iuser) {
1173                         iuser->ok= 1;
1174                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1175                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1176                                         iuser->multi_index= 0;
1177                                         iuser->layer= iuser->pass= 0;
1178                                 }
1179                         }
1180                 }
1181                 break;
1182         }
1183 }
1184
1185 /* if layer or pass changes, we need an index for the imbufs list */
1186 /* note it is called for rendered results, but it doesnt use the index! */
1187 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1188 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1189 {
1190         RenderLayer *rl;
1191         RenderPass *rpass= NULL;
1192         
1193         if(rr==NULL) 
1194                 return NULL;
1195         
1196         if(iuser) {
1197                 short index= 0, rl_index= 0, rp_index;
1198                 
1199                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1200                         rp_index= 0;
1201                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1202                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1203                                         break;
1204                         if(rpass)
1205                                 break;
1206                 }
1207                 
1208                 if(rpass)
1209                         iuser->multi_index= index;
1210                 else 
1211                         iuser->multi_index= 0;
1212         }
1213         if(rpass==NULL) {
1214                 rl= rr->layers.first;
1215                 if(rl)
1216                         rpass= rl->passes.first;
1217         }
1218         
1219         return rpass;
1220 }
1221
1222 RenderResult *BKE_image_get_renderresult(Image *ima)
1223 {
1224         if(ima->rr)
1225                 return ima->rr;
1226         if(ima->type==IMA_TYPE_R_RESULT)
1227                 return RE_GetResult(RE_GetRender(G.scene->id.name));
1228         return NULL;
1229 }
1230
1231 /* after imbuf load, openexr type can return with a exrhandle open */
1232 /* in that case we have to build a render-result */
1233 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1234 {
1235         
1236         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1237
1238 #ifdef WITH_OPENEXR
1239         IMB_exr_close(ibuf->userdata);
1240 #endif
1241
1242         ibuf->userdata= NULL;
1243         if(ima->rr)
1244                 ima->rr->framenr= framenr;
1245 }
1246
1247 /* common stuff to do with images after loading */
1248 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1249 {
1250         
1251         
1252         /* preview is NULL when it has never been used as an icon before */
1253         if(G.background==0 && ima->preview==NULL)
1254                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1255         
1256         /* stringcodes also in ibuf, ibuf->name is used to retrieve original (buttons) */
1257         BLI_strncpy(ibuf->name, ima->name, FILE_MAX);
1258         
1259         /* fields */
1260         if (ima->flag & IMA_FIELDS) {
1261                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1262                 else de_interlace_ng(ibuf);
1263         }
1264         /* timer */
1265         ima->lastused = clock() / CLOCKS_PER_SEC;
1266         
1267         ima->ok= IMA_OK_LOADED;
1268         
1269 }
1270
1271 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1272 {
1273         struct ImBuf *ibuf;
1274         unsigned short numlen;
1275         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1276         
1277         ima->lastframe= frame;
1278
1279         BLI_stringdec(ima->name, head, tail, &numlen);
1280         BLI_stringenc(ima->name, head, tail, numlen, frame);
1281         BLI_strncpy(name, ima->name, sizeof(name));
1282         
1283         if(ima->id.lib)
1284                 BLI_convertstringcode(name, ima->id.lib->filename, frame);
1285         else
1286                 BLI_convertstringcode(name, G.sce, frame);
1287         
1288         /* read ibuf */
1289         ibuf = IMB_loadiffname(name, IB_rect|IB_multilayer);
1290         if(G.f & G_DEBUG) printf("loaded %s\n", name);
1291         
1292         if (ibuf) {
1293 #ifdef WITH_OPENEXR
1294                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1295                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1296                         image_create_multilayer(ima, ibuf, frame);      
1297                         ima->type= IMA_TYPE_MULTILAYER;
1298                         IMB_freeImBuf(ibuf);
1299                         ibuf= NULL;
1300                 }
1301                 else {
1302                         image_assign_ibuf(ima, ibuf, 0, frame);
1303                         image_initialize_after_load(ima, ibuf);
1304                 }
1305 #else
1306                 image_assign_ibuf(ima, ibuf, 0, frame);
1307                 image_initialize_after_load(ima, ibuf);
1308 #endif
1309         }
1310         else
1311                 ima->ok= 0;
1312         
1313         if(iuser)
1314                 iuser->ok= ima->ok;
1315         
1316         return ibuf;
1317 }
1318
1319 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1320 {
1321         struct ImBuf *ibuf= NULL;
1322         
1323         /* either we load from RenderResult, or we have to load a new one */
1324         
1325         /* check for new RenderResult */
1326         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1327                 /* copy to survive not found multilayer image */
1328                 RenderResult *oldrr= ima->rr;
1329         
1330                 ima->rr= NULL;
1331                 ibuf = image_load_sequence_file(ima, iuser, frame);
1332                 
1333                 if(ibuf) { /* actually an error */
1334                         ima->type= IMA_TYPE_IMAGE;
1335                         printf("error, multi is normal image\n");
1336                 }
1337                 // printf("loaded new result %p\n", ima->rr);
1338                 /* free result if new one found */
1339                 if(ima->rr) {
1340                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1341                         if(oldrr) RE_FreeRenderResult(oldrr);
1342                 }
1343                 else
1344                         ima->rr= oldrr;
1345
1346         }
1347         if(ima->rr) {
1348                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1349                 
1350                 if(rpass) {
1351                         // printf("load from pass %s\n", rpass->name);
1352                         /* since we free  render results, we copy the rect */
1353                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1354                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1355                         ibuf->flags |= IB_rectfloat;
1356                         ibuf->mall= IB_rectfloat;
1357                         ibuf->channels= rpass->channels;
1358                         
1359                         image_assign_ibuf(ima, ibuf, iuser->multi_index, frame);
1360                         image_initialize_after_load(ima, ibuf);
1361                         
1362                 }
1363                 // else printf("pass not found\n");
1364         }
1365         else
1366                 ima->ok= 0;
1367         
1368         if(iuser)
1369                 iuser->ok= ima->ok;
1370         
1371         return ibuf;
1372 }
1373
1374
1375 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1376 {
1377         struct ImBuf *ibuf= NULL;
1378         
1379         ima->lastframe= frame;
1380         
1381         if(ima->anim==NULL) {
1382                 char str[FILE_MAX];
1383                 
1384                 BLI_strncpy(str, ima->name, FILE_MAX);
1385                 if(ima->id.lib)
1386                         BLI_convertstringcode(str, ima->id.lib->filename, 0);
1387                 else
1388                         BLI_convertstringcode(str, G.sce, 0);
1389                 
1390                 ima->anim = openanim(str, IB_cmap | IB_rect);
1391                 
1392                 /* let's initialize this user */
1393                 if(ima->anim && iuser && iuser->frames==0)
1394                         iuser->frames= IMB_anim_get_duration(ima->anim);
1395         }
1396         
1397         if(ima->anim) {
1398                 int dur = IMB_anim_get_duration(ima->anim);
1399                 int fra= frame-1;
1400                 
1401                 if(fra<0) fra = 0;
1402                 if(fra>(dur-1)) fra= dur-1;
1403                 ibuf = IMB_anim_absolute(ima->anim, fra);
1404                 
1405                 if(ibuf) {
1406                         image_assign_ibuf(ima, ibuf, 0, frame);
1407                         image_initialize_after_load(ima, ibuf);
1408                 }
1409                 else
1410                         ima->ok= 0;
1411         }
1412         else
1413                 ima->ok= 0;
1414         
1415         if(iuser)
1416                 iuser->ok= ima->ok;
1417         
1418         return ibuf;
1419 }
1420
1421 /* cfra used for # code, Image can only have this # for all its users */
1422 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1423 {
1424         struct ImBuf *ibuf;
1425         char str[FILE_MAX];
1426         
1427         /* always ensure clean ima */
1428         image_free_buffers(ima);
1429         
1430         /* is there a PackedFile with this image ? */
1431         if (ima->packedfile) {
1432                 ibuf = IMB_ibImageFromMemory((int *) ima->packedfile->data, ima->packedfile->size, IB_rect|IB_multilayer);
1433         } 
1434         else {
1435                         
1436                 /* get the right string */
1437                 BLI_strncpy(str, ima->name, sizeof(str));
1438                 if(ima->id.lib)
1439                         BLI_convertstringcode(str, ima->id.lib->filename, cfra);
1440                 else
1441                         BLI_convertstringcode(str, G.sce, cfra);
1442                 
1443                 /* read ibuf */
1444                 ibuf = IMB_loadiffname(str, IB_rect|IB_multilayer|IB_imginfo);
1445         }
1446         
1447         if (ibuf) {
1448                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1449                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1450                         image_create_multilayer(ima, ibuf, cfra);       
1451                         ima->type= IMA_TYPE_MULTILAYER;
1452                         IMB_freeImBuf(ibuf);
1453                         ibuf= NULL;
1454                 }
1455                 else {
1456                         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1457                         image_initialize_after_load(ima, ibuf);
1458
1459                         /* check if the image is a font image... */
1460                         detectBitmapFont(ibuf);
1461                         
1462                         /* make packed file for autopack */
1463                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
1464                                 ima->packedfile = newPackedFile(str);
1465                 }
1466         }
1467         else
1468                 ima->ok= 0;
1469         
1470         if(iuser)
1471                 iuser->ok= ima->ok;
1472         
1473         return ibuf;
1474 }
1475
1476 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1477 {
1478         ImBuf *ibuf= NULL;
1479         
1480         if(ima->rr==NULL) {
1481                 ibuf = image_load_image_file(ima, iuser, 0);
1482                 if(ibuf) { /* actually an error */
1483                         ima->type= IMA_TYPE_IMAGE;
1484                         return ibuf;
1485                 }
1486         }
1487         if(ima->rr) {
1488                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1489
1490                 if(rpass) {
1491                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1492                         
1493                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1494                         image_initialize_after_load(ima, ibuf);
1495                         
1496                         ibuf->rect_float= rpass->rect;
1497                         ibuf->flags |= IB_rectfloat;
1498                         ibuf->channels= rpass->channels;
1499                 }
1500         }
1501         
1502         if(ibuf==NULL) 
1503                 ima->ok= 0;
1504         if(iuser)
1505                 iuser->ok= ima->ok;
1506         
1507         return ibuf;
1508 }
1509
1510
1511 /* showing RGBA result itself (from compo/sequence) or
1512    like exr, using layers etc */
1513 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser)
1514 {
1515         RenderResult *rr= RE_GetResult(RE_GetRender(G.scene->id.name));
1516         
1517         if(rr && iuser) {
1518                 RenderResult rres;
1519                 float *rectf;
1520                 unsigned int *rect;
1521                 int channels= 4, layer= iuser->layer;
1522                 
1523                 /* this gives active layer, composite or seqence result */
1524                 RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
1525                 rect= (unsigned int *)rres.rect32;
1526                 rectf= rres.rectf;
1527                 
1528                 /* get compo/seq result by default */
1529                 if(rr->rectf && layer==0);
1530                 else if(rr->layers.first) {
1531                         RenderLayer *rl= BLI_findlink(&rr->layers, iuser->layer-(rr->rectf?1:0));
1532                         if(rl) {
1533                                 /* there's no combined pass, is in renderlayer itself */
1534                                 if(iuser->pass==0) {
1535                                         rectf= rl->rectf;
1536                                 }
1537                                 else {
1538                                         RenderPass *rpass= BLI_findlink(&rl->passes, iuser->pass-1);
1539                                         if(rpass) {
1540                                                 channels= rpass->channels;
1541                                                 rectf= rpass->rect;
1542                                         }
1543                                 }
1544                         }
1545                 }
1546                 
1547                 if(rectf || rect) {
1548                         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1549
1550                         /* make ibuf if needed, and initialize it */
1551                         if(ibuf==NULL) {
1552                                 ibuf= IMB_allocImBuf(rr->rectx, rr->recty, 32, 0, 0);
1553                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1554                         }
1555                         ibuf->x= rr->rectx;
1556                         ibuf->y= rr->recty;
1557                         
1558                         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
1559                                 imb_freerectImBuf(ibuf);
1560                         if(rect)
1561                                 ibuf->rect= rect;
1562                         
1563                         ibuf->rect_float= rectf;
1564                         ibuf->flags |= IB_rectfloat;
1565                         ibuf->channels= channels;
1566                         
1567                         ima->ok= IMA_OK_LOADED;
1568                         return ibuf;
1569                 }
1570         }
1571         
1572         return NULL;
1573 }
1574
1575 /* Checks optional ImageUser and verifies/creates ImBuf. */
1576 /* returns ibuf */
1577 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
1578 {
1579         ImBuf *ibuf= NULL;
1580         float color[] = {0, 0, 0, 1};
1581
1582         /* quick reject tests */
1583         if(ima==NULL) 
1584                 return NULL;
1585         if(iuser) {
1586                 if(iuser->ok==0)
1587                         return NULL;
1588         }
1589         else if(ima->ok==0)
1590                 return NULL;
1591         
1592         BLI_lock_thread(LOCK_IMAGE);
1593         
1594         /* handle image source and types */
1595         if(ima->source==IMA_SRC_MOVIE) {
1596                 /* source is from single file, use flipbook to store ibuf */
1597                 int frame= iuser?iuser->framenr:ima->lastframe;
1598                 
1599                 ibuf= image_get_ibuf(ima, 0, frame);
1600                 if(ibuf==NULL)
1601                         ibuf= image_load_movie_file(ima, iuser, frame);
1602         }
1603         else if(ima->source==IMA_SRC_SEQUENCE) {
1604                 
1605                 if(ima->type==IMA_TYPE_IMAGE) {
1606                         /* regular files, ibufs in flipbook, allows saving */
1607                         int frame= iuser?iuser->framenr:ima->lastframe;
1608                         
1609                         ibuf= image_get_ibuf(ima, 0, frame);
1610                         if(ibuf==NULL)
1611                                 ibuf= image_load_sequence_file(ima, iuser, frame);
1612                         else
1613                                 BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
1614                 }
1615                 /* no else; on load the ima type can change */
1616                 if(ima->type==IMA_TYPE_MULTILAYER) {
1617                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
1618                         int frame= iuser?iuser->framenr:ima->lastframe;
1619                         int index= iuser?iuser->multi_index:IMA_NO_INDEX;
1620                         
1621                         ibuf= image_get_ibuf(ima, index, frame);
1622                         if(G.rt) printf("seq multi fra %d id %d ibuf %p %s\n", frame, index, ibuf, ima->id.name);
1623                         if(ibuf==NULL)
1624                                 ibuf= image_load_sequence_multilayer(ima, iuser, frame);
1625                         else
1626                                 BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
1627                 }
1628
1629         }
1630         else if(ima->source==IMA_SRC_FILE) {
1631                 
1632                 if(ima->type==IMA_TYPE_IMAGE) {
1633                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1634                         if(ibuf==NULL)
1635                                 ibuf= image_load_image_file(ima, iuser, G.scene->r.cfra);       /* cfra only for '#', this global is OK */
1636                 }
1637                 /* no else; on load the ima type can change */
1638                 if(ima->type==IMA_TYPE_MULTILAYER) {
1639                         /* keeps render result, stores ibufs in listbase, allows saving */
1640                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1641                         if(ibuf==NULL)
1642                                 ibuf= image_get_ibuf_multilayer(ima, iuser);
1643                 }
1644                         
1645         }
1646         else if(ima->source == IMA_SRC_GENERATED) {
1647                 /* generated is: ibuf is allocated dynamically */
1648                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1649                 
1650                 if(ibuf==NULL) {
1651                         if(ima->type==IMA_TYPE_VERSE) {
1652                                 /* todo */
1653                         }
1654                         else { /* always fall back to IMA_TYPE_UV_TEST */
1655                                 /* UV testgrid or black or solid etc */
1656                                 if(ima->gen_x==0) ima->gen_x= 256;
1657                                 if(ima->gen_y==0) ima->gen_y= 256;
1658                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, ima->gen_type, color);
1659                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1660                                 ima->ok= IMA_OK_LOADED;
1661                         }
1662                 }
1663         }
1664         else if(ima->source == IMA_SRC_VIEWER) {
1665                 if(ima->type==IMA_TYPE_R_RESULT) {
1666                         /* always verify entirely */
1667                         ibuf= image_get_render_result(ima, iuser);
1668                 }
1669                 else if(ima->type==IMA_TYPE_COMPOSITE) {
1670                         int frame= iuser?iuser->framenr:0;
1671                         
1672                         /* Composite Viewer, all handled in compositor */
1673                         ibuf= image_get_ibuf(ima, 0, frame);
1674                         if(ibuf==NULL) {
1675                                 /* fake ibuf, will be filled in compositor */
1676                                 ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
1677                                 image_assign_ibuf(ima, ibuf, 0, frame);
1678                         }
1679                 }
1680         }
1681
1682         if(G.rendering==0)
1683                 tag_image_time(ima);
1684
1685         BLI_unlock_thread(LOCK_IMAGE);
1686
1687         return ibuf;
1688 }
1689
1690
1691 void BKE_image_user_calc_imanr(ImageUser *iuser, int cfra, int fieldnr)
1692 {
1693         int imanr, len;
1694         
1695         /* here (+fie_ima/2-1) makes sure that division happens correctly */
1696         len= (iuser->fie_ima*iuser->frames)/2;
1697         
1698         if(len==0) {
1699                 iuser->framenr= 0;
1700         }
1701         else {
1702                 cfra= cfra - iuser->sfra+1;
1703                 
1704                 /* cyclic */
1705                 if(iuser->cycl) {
1706                         cfra= ( (cfra) % len );
1707                         if(cfra < 0) cfra+= len;
1708                         if(cfra==0) cfra= len;
1709                 }
1710                 
1711                 if(cfra<1) cfra= 1;
1712                 else if(cfra>len) cfra= len;
1713                 
1714                 /* convert current frame to current field */
1715                 cfra= 2*(cfra);
1716                 if(fieldnr) cfra++;
1717                 
1718                 /* transform to images space */
1719                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
1720                 if(imanr>iuser->frames) imanr= iuser->frames;
1721                 imanr+= iuser->offset;
1722                 
1723                 if(iuser->cycl) {
1724                         imanr= ( (imanr) % len );
1725                         while(imanr < 0) imanr+= len;
1726                         if(imanr==0) imanr= len;
1727                 }
1728         
1729                 /* allows image users to handle redraws */
1730                 if(iuser->flag & IMA_ANIM_ALWAYS)
1731                         if(imanr!=iuser->framenr)
1732                                 iuser->flag |= IMA_ANIM_REFRESHED;
1733                 
1734                 iuser->framenr= imanr;
1735                 if(iuser->ok==0) iuser->ok= 1;
1736         }
1737 }
1738