render stamp drawing is now done everywhere - (not just when saving
[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 "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 /* could allow access externally */
781 typedef struct StampData {
782         char    file[512];
783         char    note[512];
784         char    date[512];
785         char    marker[512];
786         char    time[512];
787         char    frame[512];
788         char    camera[512];
789         char    scene[512];
790 } StampData;
791
792 static void stampdata(StampData *stamp_data, int do_prefix)
793 {
794         char text[256];
795         
796 #ifndef WIN32
797         struct tm *tl;
798         time_t t;
799 #else
800         char sdate[9];
801 #endif /* WIN32 */
802         
803         if (do_prefix)          sprintf(stamp_data->file, "File %s", G.sce);
804         else                            sprintf(stamp_data->file, "%s", G.sce);
805         
806         if (G.scene->r.stamp & R_STAMP_NOTE) {
807                 if (do_prefix)          sprintf(stamp_data->note, "Note %s", G.scene->r.stamp_udata);
808                 else                            sprintf(stamp_data->note, "%s", G.scene->r.stamp_udata);
809         } else {
810                 stamp_data->note[0] = '\0';
811         }
812         
813         if (G.scene->r.stamp & R_STAMP_DATE) {
814 #ifdef WIN32
815                 _strdate (sdate);
816                 sprintf (text, "%s", sdate);
817 #else
818                 t = time (NULL);
819                 tl = localtime (&t);
820                 sprintf (text, "%04d-%02d-%02d", tl->tm_year+1900, tl->tm_mon+1, tl->tm_mday);
821 #endif /* WIN32 */
822                 if (do_prefix)          sprintf(stamp_data->date, "Date %s", text);
823                 else                            sprintf(stamp_data->date, "%s", text);
824         } else {
825                 stamp_data->date[0] = '\0';
826         }
827         
828         if (G.scene->r.stamp & R_STAMP_MARKER) {
829                 TimeMarker *marker = get_frame_marker(CFRA);
830         
831                 if (marker) strcpy(text, marker->name);
832                 else            strcpy(text, "<none>");
833                 
834                 if (do_prefix)          sprintf(stamp_data->marker, "Marker %s", text);
835                 else                            sprintf(stamp_data->marker, "%s", text);
836         } else {
837                 stamp_data->marker[0] = '\0';
838         }
839         
840         if (G.scene->r.stamp & R_STAMP_TIME) {
841                 int h, m, s, f;
842                 h= m= s= f= 0;
843                 f = (int)(G.scene->r.cfra % G.scene->r.frs_sec);
844                 s = (int)(G.scene->r.cfra / G.scene->r.frs_sec);
845
846                 if (s) {
847                         m = (int)(s / 60);
848                         s %= 60;
849
850                         if (m) {
851                                 h = (int)(m / 60);
852                                 m %= 60;
853                         }
854                 }
855
856                 if (G.scene->r.frs_sec < 100)
857                         sprintf (text, "%02d:%02d:%02d.%02d", h, m, s, f);
858                 else
859                         sprintf (text, "%02d:%02d:%02d.%03d", h, m, s, f);
860                 
861                 if (do_prefix)          sprintf(stamp_data->time, "Time %s", text);
862                 else                            sprintf(stamp_data->time, "%s", text);
863         } else {
864                 stamp_data->time[0] = '\0';
865         }
866         
867         if (G.scene->r.stamp & R_STAMP_FRAME) {
868                 char format[32];
869                 if (do_prefix)          sprintf(format, "Frame %%0%di\n", 1 + (int) log10(G.scene->r.efra));
870                 else                            sprintf(format, "%%0%di\n", 1 + (int) log10(G.scene->r.efra));
871                 sprintf (stamp_data->frame, format, G.scene->r.cfra);
872         } else {
873                 stamp_data->frame[0] = '\0';
874         }
875
876         if (G.scene->r.stamp & R_STAMP_CAMERA) {
877                 if (do_prefix)          sprintf(stamp_data->camera, "Camera %s", ((Camera *) G.scene->camera)->id.name+2);
878                 else                            sprintf(stamp_data->camera, "%s", ((Camera *) G.scene->camera)->id.name+2);
879         } else {
880                 stamp_data->camera[0] = '\0';
881         }
882
883         if (G.scene->r.stamp & R_STAMP_SCENE) {
884                 if (do_prefix)          sprintf(stamp_data->scene, "Camera %s", G.scene->id.name+2);
885                 else                            sprintf(stamp_data->scene, "%s", G.scene->id.name+2);
886         } else {
887                 stamp_data->scene[0] = '\0';
888         }
889 }
890
891 void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
892 {
893         struct StampData stamp_data;
894         
895         int x,y;
896         int font_height;
897         int text_width;
898         int text_pad;
899         struct BMF_Font *font;
900         
901         if (!rect && !rectf)
902                 return;
903         
904         stampdata(&stamp_data, 1);
905         
906         switch (G.scene->r.stamp_font_id) {
907         case 1: /* tiny */
908                 font = BMF_GetFont(BMF_kHelveticaBold8);
909                 break;
910         case 2: /* small */
911                 font = BMF_GetFont(BMF_kHelveticaBold10);
912                 break;
913         case 3: /* medium */
914                 font = BMF_GetFont(BMF_kScreen12);
915                 break;
916         case 0: /* large - default */
917                 font = BMF_GetFont(BMF_kScreen15);
918                 break;
919         case 4: /* huge */
920                 font = BMF_GetFont(BMF_kHelveticaBold14);
921                 break;
922         default:
923                 font = NULL;
924                 break;
925         }
926         
927         font_height = BMF_GetFontHeight(font);
928         /* All texts get halfspace+1 pixel on each side and 1 pix
929         above and below as padding against their backing rectangles */
930         text_pad = BMF_GetStringWidth(font, " ");
931         
932
933         if (stamp_data.file[0]) {
934                 /* Top left corner */
935                 x = 1; /* Inits for everyone, text position, so 1 for padding, not 0 */
936                 y = height - font_height - 1; /* Also inits for everyone, notice padding pixel */
937                 text_width = BMF_GetStringWidth(font, stamp_data.file);
938                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
939                 BMF_DrawStringBuf(font, stamp_data.file, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
940                 y -= font_height+2; /* Top and bottom 1 pix padding each */
941         }
942
943         /* Top left corner, below File */
944         if (stamp_data.note[0]) {
945                 text_width = BMF_GetStringWidth(font, stamp_data.note);
946                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
947                 BMF_DrawStringBuf(font, stamp_data.note, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
948                 y -= font_height+2; /* Top and bottom 1 pix padding each */
949         }
950         
951         /* Top left corner, below File (or Note) */
952         if (stamp_data.date[0]) {
953                 text_width = BMF_GetStringWidth(font, stamp_data.date);
954                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
955                 BMF_DrawStringBuf(font, stamp_data.date, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
956         }
957
958         /* Bottom left corner, leaving space for timing */
959         if (stamp_data.marker[0]) {
960                 x = 1;
961                 y = font_height+2+1; /* 2 for padding in TIME|FRAME fields below and 1 for padding in this one */
962                 text_width = BMF_GetStringWidth(font, stamp_data.marker);
963                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
964                 BMF_DrawStringBuf(font, stamp_data.marker, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
965         }
966         
967         /* Left bottom corner */
968         if (stamp_data.time[0]) {
969                 x = 1;
970                 y = 1;
971                 text_width = BMF_GetStringWidth(font, stamp_data.time);
972                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
973                 BMF_DrawStringBuf(font, stamp_data.time, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
974                 x += text_width+text_pad+2; /* Both sides have 1 pix additional padding each */
975         }
976         
977         if (stamp_data.frame[0]) {
978                 text_width = BMF_GetStringWidth(font, stamp_data.frame);
979                 /* Left bottom corner (after SMPTE if exists) */
980                 if (!stamp_data.time[0])        x = 1;
981                 y = 1;
982                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
983                 BMF_DrawStringBuf(font, stamp_data.frame, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
984         }
985
986         if (stamp_data.camera[0]) {
987                 text_width = BMF_GetStringWidth(font, stamp_data.camera);
988                 /* Center of bottom edge */
989                 x = (width/2) - (BMF_GetStringWidth(font, stamp_data.camera)/2);
990                 y = 1;
991                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
992                 BMF_DrawStringBuf(font, stamp_data.camera, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
993         }
994         
995         if (stamp_data.scene[0]) {
996                 text_width = BMF_GetStringWidth(font, stamp_data.scene);
997                 /* Bottom right corner */
998                 x = width - (text_width+1+text_pad);
999                 y = 1;
1000                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
1001                 BMF_DrawStringBuf(font, stamp_data.scene, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
1002         }
1003 }
1004
1005
1006 void BKE_stamp_info(struct ImBuf *ibuf)
1007 {
1008         struct StampData stamp_data;
1009
1010         if (!ibuf)      return;
1011         
1012         /* fill all the data values, no prefix */
1013         stampdata(&stamp_data, 0);
1014         
1015         if (stamp_data.file[0])         IMB_imginfo_change_field (ibuf, "File",         stamp_data.file);
1016         if (stamp_data.note[0])         IMB_imginfo_change_field (ibuf, "Note",         stamp_data.note);
1017         if (stamp_data.date[0])         IMB_imginfo_change_field (ibuf, "Date",         stamp_data.date);
1018         if (stamp_data.marker[0])       IMB_imginfo_change_field (ibuf, "Marker",       stamp_data.marker);
1019         if (stamp_data.time[0])         IMB_imginfo_change_field (ibuf, "Time",         stamp_data.time);
1020         if (stamp_data.frame[0])        IMB_imginfo_change_field (ibuf, "Frame",        stamp_data.frame);
1021         if (stamp_data.camera[0])       IMB_imginfo_change_field (ibuf, "Camera",       stamp_data.camera);
1022         if (stamp_data.scene[0])        IMB_imginfo_change_field (ibuf, "Scene",        stamp_data.scene);
1023 }
1024
1025 int BKE_write_ibuf(ImBuf *ibuf, char *name, int imtype, int subimtype, int quality)
1026 {
1027         int ok;
1028         
1029         if(imtype==0);
1030         else if(imtype== R_IRIS) 
1031                 ibuf->ftype= IMAGIC;
1032         else if ((imtype==R_RADHDR)) {
1033                 ibuf->ftype= RADHDR;
1034         }
1035         else if ((imtype==R_PNG)) {
1036                 ibuf->ftype= PNG;
1037         }
1038 #ifdef WITH_DDS
1039         else if ((imtype==R_DDS)) {
1040                 ibuf->ftype= DDS;
1041         }
1042 #endif
1043         else if ((imtype==R_BMP)) {
1044                 ibuf->ftype= BMP;
1045         }
1046         else if ((G.have_libtiff) && (imtype==R_TIFF)) {
1047                 ibuf->ftype= TIF;
1048         }
1049 #ifdef WITH_OPENEXR
1050         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
1051                 ibuf->ftype= OPENEXR;
1052                 if(subimtype & R_OPENEXR_HALF)
1053                         ibuf->ftype |= OPENEXR_HALF;
1054                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1055                 
1056                 if(!(subimtype & R_OPENEXR_ZBUF))
1057                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1058                 
1059         }
1060 #endif
1061         else if (imtype==R_CINEON) {
1062                 ibuf->ftype = CINEON;
1063         }
1064         else if (imtype==R_DPX) {
1065                 ibuf->ftype = DPX;
1066         }
1067         else if (imtype==R_TARGA) {
1068                 ibuf->ftype= TGA;
1069         }
1070         else if(imtype==R_RAWTGA) {
1071                 ibuf->ftype= RAWTGA;
1072         }
1073         else if(imtype==R_HAMX) {
1074                 ibuf->ftype= AN_hamx;
1075         }
1076         else {
1077                 /* R_JPEG90, R_MOVIE, etc. default we save jpegs */
1078                 if(quality < 10) quality= 90;
1079                 ibuf->ftype= JPG|quality;
1080                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
1081         }
1082         
1083         BLI_make_existing_file(name);
1084
1085         if(G.scene->r.scemode & R_STAMP_INFO)
1086                 BKE_stamp_info(ibuf);
1087         
1088         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1089         if (ok == 0) {
1090                 perror(name);
1091         }
1092         
1093         return(ok);
1094 }
1095
1096
1097 void BKE_makepicstring(char *string, char *base, int frame, int imtype)
1098 {
1099         short i, len, digits= 4;        /* digits in G.scene? */
1100         char num[10];
1101
1102         if (string==NULL) return;
1103
1104         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1105         BLI_convertstringcode(string, G.sce, frame);
1106
1107         len= strlen(string);
1108                         
1109         i= digits - sprintf(num, "%d", frame);
1110         for(; i>0; i--){
1111                 string[len]= '0';
1112                 len++;
1113         }
1114         string[len]= 0;
1115         strcat(string, num);
1116
1117         if(G.scene->r.scemode & R_EXTENSION) 
1118                 BKE_add_image_extension(string, imtype);
1119                 
1120 }
1121
1122 /* used by sequencer too */
1123 struct anim *openanim(char *name, int flags)
1124 {
1125         struct anim *anim;
1126         struct ImBuf *ibuf;
1127         
1128         anim = IMB_open_anim(name, flags);
1129         if (anim == NULL) return(0);
1130
1131         ibuf = IMB_anim_absolute(anim, 0);
1132         if (ibuf == NULL) {
1133                 printf("not an anim; %s\n", name);
1134                 IMB_free_anim(anim);
1135                 return(0);
1136         }
1137         IMB_freeImBuf(ibuf);
1138         
1139         return(anim);
1140 }
1141
1142 /* ************************* New Image API *************** */
1143
1144
1145 /* Notes about Image storage 
1146 - packedfile
1147   -> written in .blend
1148 - filename
1149   -> written in .blend
1150 - movie
1151   -> comes from packedfile or filename
1152 - renderresult
1153   -> comes from packedfile or filename
1154 - listbase
1155   -> ibufs from exrhandle
1156 - flipbook array
1157   -> ibufs come from movie, temporary renderresult or sequence
1158 - ibuf
1159   -> comes from packedfile or filename or generated
1160
1161 */
1162
1163
1164 /* forces existance of 1 Image for renderout or nodes, returns Image */
1165 /* name is only for default, when making new one */
1166 Image *BKE_image_verify_viewer(int type, const char *name)
1167 {
1168         Image *ima;
1169         
1170         for(ima=G.main->image.first; ima; ima= ima->id.next)
1171                 if(ima->source==IMA_SRC_VIEWER)
1172                         if(ima->type==type)
1173                                 break;
1174         
1175         if(ima==NULL)
1176                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1177         
1178         /* happens on reload, imagewindow cannot be image user when hidden*/
1179         if(ima->id.us==0)
1180                 id_us_plus(&ima->id);
1181
1182         return ima;
1183 }
1184
1185 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1186 {
1187         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1188 }
1189
1190 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1191 {
1192         if(ima==NULL)
1193                 return;
1194         
1195         switch(signal) {
1196         case IMA_SIGNAL_FREE:
1197                 image_free_buffers(ima);
1198                 if(iuser)
1199                         iuser->ok= 1;
1200                 break;
1201         case IMA_SIGNAL_SRC_CHANGE:
1202                 if(ima->type==IMA_TYPE_MULTILAYER)
1203                         image_free_buffers(ima);
1204                 else if(ima->source==IMA_SRC_GENERATED) {
1205                         if(ima->gen_x==0 || ima->gen_y==0) {
1206                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1207                                 if(ibuf) {
1208                                         ima->gen_x= ibuf->x;
1209                                         ima->gen_y= ibuf->y;
1210                                 }
1211                         }
1212                 }
1213                 ima->ok= 1;
1214                 if(iuser)
1215                         iuser->ok= 1;
1216                 break;
1217                         
1218         case IMA_SIGNAL_RELOAD:
1219                 /* try to repack file */
1220                 if(ima->packedfile) {
1221                         PackedFile *pf;
1222                         pf = newPackedFile(ima->name);
1223                         if (pf) {
1224                                 freePackedFile(ima->packedfile);
1225                                 ima->packedfile = pf;
1226                                 image_free_buffers(ima);
1227                         } else {
1228                                 printf("ERROR: Image not available. Keeping packed image\n");
1229                         }
1230                 }
1231                 else
1232                         image_free_buffers(ima);
1233                 
1234                 if(iuser)
1235                         iuser->ok= 1;
1236                 
1237                 break;
1238         case IMA_SIGNAL_USER_NEW_IMAGE:
1239                 if(iuser) {
1240                         iuser->ok= 1;
1241                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1242                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1243                                         iuser->multi_index= 0;
1244                                         iuser->layer= iuser->pass= 0;
1245                                 }
1246                         }
1247                 }
1248                 break;
1249         }
1250 }
1251
1252 /* if layer or pass changes, we need an index for the imbufs list */
1253 /* note it is called for rendered results, but it doesnt use the index! */
1254 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1255 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1256 {
1257         RenderLayer *rl;
1258         RenderPass *rpass= NULL;
1259         
1260         if(rr==NULL) 
1261                 return NULL;
1262         
1263         if(iuser) {
1264                 short index= 0, rl_index= 0, rp_index;
1265                 
1266                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1267                         rp_index= 0;
1268                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1269                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1270                                         break;
1271                         if(rpass)
1272                                 break;
1273                 }
1274                 
1275                 if(rpass)
1276                         iuser->multi_index= index;
1277                 else 
1278                         iuser->multi_index= 0;
1279         }
1280         if(rpass==NULL) {
1281                 rl= rr->layers.first;
1282                 if(rl)
1283                         rpass= rl->passes.first;
1284         }
1285         
1286         return rpass;
1287 }
1288
1289 RenderResult *BKE_image_get_renderresult(Image *ima)
1290 {
1291         if(ima->rr)
1292                 return ima->rr;
1293         if(ima->type==IMA_TYPE_R_RESULT)
1294                 return RE_GetResult(RE_GetRender(G.scene->id.name));
1295         return NULL;
1296 }
1297
1298 /* after imbuf load, openexr type can return with a exrhandle open */
1299 /* in that case we have to build a render-result */
1300 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1301 {
1302         
1303         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1304
1305 #ifdef WITH_OPENEXR
1306         IMB_exr_close(ibuf->userdata);
1307 #endif
1308
1309         ibuf->userdata= NULL;
1310         if(ima->rr)
1311                 ima->rr->framenr= framenr;
1312 }
1313
1314 /* common stuff to do with images after loading */
1315 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1316 {
1317         
1318         
1319         /* preview is NULL when it has never been used as an icon before */
1320         if(G.background==0 && ima->preview==NULL)
1321                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1322         
1323         /* stringcodes also in ibuf, ibuf->name is used to retrieve original (buttons) */
1324         BLI_strncpy(ibuf->name, ima->name, FILE_MAX);
1325         
1326         /* fields */
1327         if (ima->flag & IMA_FIELDS) {
1328                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1329                 else de_interlace_ng(ibuf);
1330         }
1331         /* timer */
1332         ima->lastused = clock() / CLOCKS_PER_SEC;
1333         
1334         ima->ok= IMA_OK_LOADED;
1335         
1336 }
1337
1338 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1339 {
1340         struct ImBuf *ibuf;
1341         unsigned short numlen;
1342         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1343         
1344         ima->lastframe= frame;
1345
1346         BLI_stringdec(ima->name, head, tail, &numlen);
1347         BLI_stringenc(ima->name, head, tail, numlen, frame);
1348         BLI_strncpy(name, ima->name, sizeof(name));
1349         
1350         if(ima->id.lib)
1351                 BLI_convertstringcode(name, ima->id.lib->filename, frame);
1352         else
1353                 BLI_convertstringcode(name, G.sce, frame);
1354         
1355         /* read ibuf */
1356         ibuf = IMB_loadiffname(name, IB_rect|IB_multilayer);
1357         if(G.f & G_DEBUG) printf("loaded %s\n", name);
1358         
1359         if (ibuf) {
1360 #ifdef WITH_OPENEXR
1361                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1362                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1363                         image_create_multilayer(ima, ibuf, frame);      
1364                         ima->type= IMA_TYPE_MULTILAYER;
1365                         IMB_freeImBuf(ibuf);
1366                         ibuf= NULL;
1367                 }
1368                 else {
1369                         image_assign_ibuf(ima, ibuf, 0, frame);
1370                         image_initialize_after_load(ima, ibuf);
1371                 }
1372 #else
1373                 image_assign_ibuf(ima, ibuf, 0, frame);
1374                 image_initialize_after_load(ima, ibuf);
1375 #endif
1376         }
1377         else
1378                 ima->ok= 0;
1379         
1380         if(iuser)
1381                 iuser->ok= ima->ok;
1382         
1383         return ibuf;
1384 }
1385
1386 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1387 {
1388         struct ImBuf *ibuf= NULL;
1389         
1390         /* either we load from RenderResult, or we have to load a new one */
1391         
1392         /* check for new RenderResult */
1393         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1394                 /* copy to survive not found multilayer image */
1395                 RenderResult *oldrr= ima->rr;
1396         
1397                 ima->rr= NULL;
1398                 ibuf = image_load_sequence_file(ima, iuser, frame);
1399                 
1400                 if(ibuf) { /* actually an error */
1401                         ima->type= IMA_TYPE_IMAGE;
1402                         printf("error, multi is normal image\n");
1403                 }
1404                 // printf("loaded new result %p\n", ima->rr);
1405                 /* free result if new one found */
1406                 if(ima->rr) {
1407                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1408                         if(oldrr) RE_FreeRenderResult(oldrr);
1409                 }
1410                 else
1411                         ima->rr= oldrr;
1412
1413         }
1414         if(ima->rr) {
1415                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1416                 
1417                 if(rpass) {
1418                         // printf("load from pass %s\n", rpass->name);
1419                         /* since we free  render results, we copy the rect */
1420                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1421                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1422                         ibuf->flags |= IB_rectfloat;
1423                         ibuf->mall= IB_rectfloat;
1424                         ibuf->channels= rpass->channels;
1425                         
1426                         image_assign_ibuf(ima, ibuf, iuser->multi_index, frame);
1427                         image_initialize_after_load(ima, ibuf);
1428                         
1429                 }
1430                 // else printf("pass not found\n");
1431         }
1432         else
1433                 ima->ok= 0;
1434         
1435         if(iuser)
1436                 iuser->ok= ima->ok;
1437         
1438         return ibuf;
1439 }
1440
1441
1442 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1443 {
1444         struct ImBuf *ibuf= NULL;
1445         
1446         ima->lastframe= frame;
1447         
1448         if(ima->anim==NULL) {
1449                 char str[FILE_MAX];
1450                 
1451                 BLI_strncpy(str, ima->name, FILE_MAX);
1452                 if(ima->id.lib)
1453                         BLI_convertstringcode(str, ima->id.lib->filename, 0);
1454                 else
1455                         BLI_convertstringcode(str, G.sce, 0);
1456                 
1457                 ima->anim = openanim(str, IB_cmap | IB_rect);
1458                 
1459                 /* let's initialize this user */
1460                 if(ima->anim && iuser && iuser->frames==0)
1461                         iuser->frames= IMB_anim_get_duration(ima->anim);
1462         }
1463         
1464         if(ima->anim) {
1465                 int dur = IMB_anim_get_duration(ima->anim);
1466                 int fra= frame-1;
1467                 
1468                 if(fra<0) fra = 0;
1469                 if(fra>(dur-1)) fra= dur-1;
1470                 ibuf = IMB_anim_absolute(ima->anim, fra);
1471                 
1472                 if(ibuf) {
1473                         image_assign_ibuf(ima, ibuf, 0, frame);
1474                         image_initialize_after_load(ima, ibuf);
1475                 }
1476                 else
1477                         ima->ok= 0;
1478         }
1479         else
1480                 ima->ok= 0;
1481         
1482         if(iuser)
1483                 iuser->ok= ima->ok;
1484         
1485         return ibuf;
1486 }
1487
1488 /* cfra used for # code, Image can only have this # for all its users */
1489 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1490 {
1491         struct ImBuf *ibuf;
1492         char str[FILE_MAX];
1493         
1494         /* always ensure clean ima */
1495         image_free_buffers(ima);
1496         
1497         /* is there a PackedFile with this image ? */
1498         if (ima->packedfile) {
1499                 ibuf = IMB_ibImageFromMemory((int *) ima->packedfile->data, ima->packedfile->size, IB_rect|IB_multilayer);
1500         } 
1501         else {
1502                         
1503                 /* get the right string */
1504                 BLI_strncpy(str, ima->name, sizeof(str));
1505                 if(ima->id.lib)
1506                         BLI_convertstringcode(str, ima->id.lib->filename, cfra);
1507                 else
1508                         BLI_convertstringcode(str, G.sce, cfra);
1509                 
1510                 /* read ibuf */
1511                 ibuf = IMB_loadiffname(str, IB_rect|IB_multilayer|IB_imginfo);
1512         }
1513         
1514         if (ibuf) {
1515                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1516                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1517                         image_create_multilayer(ima, ibuf, cfra);       
1518                         ima->type= IMA_TYPE_MULTILAYER;
1519                         IMB_freeImBuf(ibuf);
1520                         ibuf= NULL;
1521                 }
1522                 else {
1523                         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1524                         image_initialize_after_load(ima, ibuf);
1525
1526                         /* check if the image is a font image... */
1527                         detectBitmapFont(ibuf);
1528                         
1529                         /* make packed file for autopack */
1530                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
1531                                 ima->packedfile = newPackedFile(str);
1532                 }
1533         }
1534         else
1535                 ima->ok= 0;
1536         
1537         if(iuser)
1538                 iuser->ok= ima->ok;
1539         
1540         return ibuf;
1541 }
1542
1543 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1544 {
1545         ImBuf *ibuf= NULL;
1546         
1547         if(ima->rr==NULL) {
1548                 ibuf = image_load_image_file(ima, iuser, 0);
1549                 if(ibuf) { /* actually an error */
1550                         ima->type= IMA_TYPE_IMAGE;
1551                         return ibuf;
1552                 }
1553         }
1554         if(ima->rr) {
1555                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1556
1557                 if(rpass) {
1558                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1559                         
1560                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1561                         image_initialize_after_load(ima, ibuf);
1562                         
1563                         ibuf->rect_float= rpass->rect;
1564                         ibuf->flags |= IB_rectfloat;
1565                         ibuf->channels= rpass->channels;
1566                 }
1567         }
1568         
1569         if(ibuf==NULL) 
1570                 ima->ok= 0;
1571         if(iuser)
1572                 iuser->ok= ima->ok;
1573         
1574         return ibuf;
1575 }
1576
1577
1578 /* showing RGBA result itself (from compo/sequence) or
1579    like exr, using layers etc */
1580 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser)
1581 {
1582         RenderResult *rr= RE_GetResult(RE_GetRender(G.scene->id.name));
1583         
1584         if(rr && iuser) {
1585                 RenderResult rres;
1586                 float *rectf;
1587                 unsigned int *rect;
1588                 int channels= 4, layer= iuser->layer;
1589                 
1590                 /* this gives active layer, composite or seqence result */
1591                 RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
1592                 rect= (unsigned int *)rres.rect32;
1593                 rectf= rres.rectf;
1594                 
1595                 /* get compo/seq result by default */
1596                 if(rr->rectf && layer==0);
1597                 else if(rr->layers.first) {
1598                         RenderLayer *rl= BLI_findlink(&rr->layers, iuser->layer-(rr->rectf?1:0));
1599                         if(rl) {
1600                                 /* there's no combined pass, is in renderlayer itself */
1601                                 if(iuser->pass==0) {
1602                                         rectf= rl->rectf;
1603                                 }
1604                                 else {
1605                                         RenderPass *rpass= BLI_findlink(&rl->passes, iuser->pass-1);
1606                                         if(rpass) {
1607                                                 channels= rpass->channels;
1608                                                 rectf= rpass->rect;
1609                                         }
1610                                 }
1611                         }
1612                 }
1613                 
1614                 if(rectf || rect) {
1615                         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1616
1617                         /* make ibuf if needed, and initialize it */
1618                         if(ibuf==NULL) {
1619                                 ibuf= IMB_allocImBuf(rr->rectx, rr->recty, 32, 0, 0);
1620                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1621                         }
1622                         ibuf->x= rr->rectx;
1623                         ibuf->y= rr->recty;
1624                         
1625                         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
1626                                 imb_freerectImBuf(ibuf);
1627                         if(rect)
1628                                 ibuf->rect= rect;
1629                         
1630                         ibuf->rect_float= rectf;
1631                         ibuf->flags |= IB_rectfloat;
1632                         ibuf->channels= channels;
1633                         
1634                         ima->ok= IMA_OK_LOADED;
1635                         return ibuf;
1636                 }
1637         }
1638         
1639         return NULL;
1640 }
1641
1642 /* Checks optional ImageUser and verifies/creates ImBuf. */
1643 /* returns ibuf */
1644 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
1645 {
1646         ImBuf *ibuf= NULL;
1647         float color[] = {0, 0, 0, 1};
1648
1649         /* quick reject tests */
1650         if(ima==NULL) 
1651                 return NULL;
1652         if(iuser) {
1653                 if(iuser->ok==0)
1654                         return NULL;
1655         }
1656         else if(ima->ok==0)
1657                 return NULL;
1658         
1659         BLI_lock_thread(LOCK_IMAGE);
1660         
1661         /* handle image source and types */
1662         if(ima->source==IMA_SRC_MOVIE) {
1663                 /* source is from single file, use flipbook to store ibuf */
1664                 int frame= iuser?iuser->framenr:ima->lastframe;
1665                 
1666                 ibuf= image_get_ibuf(ima, 0, frame);
1667                 if(ibuf==NULL)
1668                         ibuf= image_load_movie_file(ima, iuser, frame);
1669         }
1670         else if(ima->source==IMA_SRC_SEQUENCE) {
1671                 
1672                 if(ima->type==IMA_TYPE_IMAGE) {
1673                         /* regular files, ibufs in flipbook, allows saving */
1674                         int frame= iuser?iuser->framenr:ima->lastframe;
1675                         
1676                         ibuf= image_get_ibuf(ima, 0, frame);
1677                         if(ibuf==NULL)
1678                                 ibuf= image_load_sequence_file(ima, iuser, frame);
1679                         else
1680                                 BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
1681                 }
1682                 /* no else; on load the ima type can change */
1683                 if(ima->type==IMA_TYPE_MULTILAYER) {
1684                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
1685                         int frame= iuser?iuser->framenr:ima->lastframe;
1686                         int index= iuser?iuser->multi_index:IMA_NO_INDEX;
1687                         
1688                         ibuf= image_get_ibuf(ima, index, frame);
1689                         if(G.rt) printf("seq multi fra %d id %d ibuf %p %s\n", frame, index, ibuf, ima->id.name);
1690                         if(ibuf==NULL)
1691                                 ibuf= image_load_sequence_multilayer(ima, iuser, frame);
1692                         else
1693                                 BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
1694                 }
1695
1696         }
1697         else if(ima->source==IMA_SRC_FILE) {
1698                 
1699                 if(ima->type==IMA_TYPE_IMAGE) {
1700                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1701                         if(ibuf==NULL)
1702                                 ibuf= image_load_image_file(ima, iuser, G.scene->r.cfra);       /* cfra only for '#', this global is OK */
1703                 }
1704                 /* no else; on load the ima type can change */
1705                 if(ima->type==IMA_TYPE_MULTILAYER) {
1706                         /* keeps render result, stores ibufs in listbase, allows saving */
1707                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1708                         if(ibuf==NULL)
1709                                 ibuf= image_get_ibuf_multilayer(ima, iuser);
1710                 }
1711                         
1712         }
1713         else if(ima->source == IMA_SRC_GENERATED) {
1714                 /* generated is: ibuf is allocated dynamically */
1715                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1716                 
1717                 if(ibuf==NULL) {
1718                         if(ima->type==IMA_TYPE_VERSE) {
1719                                 /* todo */
1720                         }
1721                         else { /* always fall back to IMA_TYPE_UV_TEST */
1722                                 /* UV testgrid or black or solid etc */
1723                                 if(ima->gen_x==0) ima->gen_x= 256;
1724                                 if(ima->gen_y==0) ima->gen_y= 256;
1725                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, ima->gen_type, color);
1726                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1727                                 ima->ok= IMA_OK_LOADED;
1728                         }
1729                 }
1730         }
1731         else if(ima->source == IMA_SRC_VIEWER) {
1732                 if(ima->type==IMA_TYPE_R_RESULT) {
1733                         /* always verify entirely */
1734                         ibuf= image_get_render_result(ima, iuser);
1735                 }
1736                 else if(ima->type==IMA_TYPE_COMPOSITE) {
1737                         int frame= iuser?iuser->framenr:0;
1738                         
1739                         /* Composite Viewer, all handled in compositor */
1740                         ibuf= image_get_ibuf(ima, 0, frame);
1741                         if(ibuf==NULL) {
1742                                 /* fake ibuf, will be filled in compositor */
1743                                 ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
1744                                 image_assign_ibuf(ima, ibuf, 0, frame);
1745                         }
1746                 }
1747         }
1748
1749         if(G.rendering==0)
1750                 tag_image_time(ima);
1751
1752         BLI_unlock_thread(LOCK_IMAGE);
1753
1754         return ibuf;
1755 }
1756
1757
1758 void BKE_image_user_calc_imanr(ImageUser *iuser, int cfra, int fieldnr)
1759 {
1760         int imanr, len;
1761         
1762         /* here (+fie_ima/2-1) makes sure that division happens correctly */
1763         len= (iuser->fie_ima*iuser->frames)/2;
1764         
1765         if(len==0) {
1766                 iuser->framenr= 0;
1767         }
1768         else {
1769                 cfra= cfra - iuser->sfra+1;
1770                 
1771                 /* cyclic */
1772                 if(iuser->cycl) {
1773                         cfra= ( (cfra) % len );
1774                         if(cfra < 0) cfra+= len;
1775                         if(cfra==0) cfra= len;
1776                 }
1777                 
1778                 if(cfra<1) cfra= 1;
1779                 else if(cfra>len) cfra= len;
1780                 
1781                 /* convert current frame to current field */
1782                 cfra= 2*(cfra);
1783                 if(fieldnr) cfra++;
1784                 
1785                 /* transform to images space */
1786                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
1787                 if(imanr>iuser->frames) imanr= iuser->frames;
1788                 imanr+= iuser->offset;
1789                 
1790                 if(iuser->cycl) {
1791                         imanr= ( (imanr) % len );
1792                         while(imanr < 0) imanr+= len;
1793                         if(imanr==0) imanr= len;
1794                 }
1795         
1796                 /* allows image users to handle redraws */
1797                 if(iuser->flag & IMA_ANIM_ALWAYS)
1798                         if(imanr!=iuser->framenr)
1799                                 iuser->flag |= IMA_ANIM_REFRESHED;
1800                 
1801                 iuser->framenr= imanr;
1802                 if(iuser->ok==0) iuser->ok= 1;
1803         }
1804 }
1805