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