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