Implemented suggestion be Matt to slightly tweak the code for single column UI
[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  * Contributor(s): Blender Foundation, 2006, full recode
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include <stdio.h>
30 #include <string.h>
31 #include <fcntl.h>
32 #include <math.h>
33 #ifndef WIN32 
34 #include <unistd.h>
35 #else
36 #include <io.h>
37 #endif
38
39 #include <time.h>
40
41 #ifdef _WIN32
42 #define open _open
43 #define close _close
44 #endif
45
46 #include "MEM_guardedalloc.h"
47
48 #include "IMB_imbuf_types.h"
49 #include "IMB_imbuf.h"
50
51 #ifdef WITH_OPENEXR
52 #include "intern/openexr/openexr_multi.h"
53 #endif
54
55 #include "DNA_image_types.h"
56 #include "DNA_packedFile_types.h"
57 #include "DNA_scene_types.h"
58 #include "DNA_camera_types.h"
59 #include "DNA_sequence_types.h"
60 #include "DNA_texture_types.h"
61 #include "DNA_sequence_types.h"
62 #include "DNA_userdef_types.h"
63
64 #include "BLI_math.h"
65 #include "BLI_blenlib.h"
66 #include "BLI_threads.h"
67
68 #include "BKE_bmfont.h"
69 #include "BKE_global.h"
70 #include "BKE_icons.h"
71 #include "BKE_image.h"
72 #include "BKE_library.h"
73 #include "BKE_main.h"
74 #include "BKE_packedFile.h"
75 #include "BKE_scene.h"
76 #include "BKE_texture.h"
77 #include "BKE_utildefines.h"
78
79 //XXX #include "BIF_editseq.h"
80
81 #include "BLF_api.h"
82
83 #include "PIL_time.h"
84
85 #include "RE_pipeline.h"
86
87 #include "GPU_extensions.h"
88 #include "GPU_draw.h"
89
90 #include "BLO_sys_types.h" // for intptr_t support
91
92 /* max int, to indicate we don't store sequences in ibuf */
93 #define IMA_NO_INDEX    0x7FEFEFEF
94
95 /* quick lookup: supports 1 million frames, thousand passes */
96 #define IMA_MAKE_INDEX(frame, index)    ((frame)<<10)+index
97 #define IMA_INDEX_FRAME(index)                  (index>>10)
98 #define IMA_INDEX_PASS(index)                   (index & ~1023)
99
100 /* ******** IMAGE PROCESSING ************* */
101
102 /* used by sequencer and image premul option - IMA_DO_PREMUL */
103 void converttopremul(struct ImBuf *ibuf)
104 {
105         int x, y;
106         
107         if(ibuf==0) return;
108         if (ibuf->rect) {
109                 int val;
110                 char *cp;
111                 if(ibuf->depth==24) {   /* put alpha at 255 */
112                         cp= (char *)(ibuf->rect);
113                         for(y=0; y<ibuf->y; y++) {
114                                 for(x=0; x<ibuf->x; x++, cp+=4) {
115                                         cp[3]= 255;
116                                 }
117                         }
118                 } else {
119                         cp= (char *)(ibuf->rect);
120                         for(y=0; y<ibuf->y; y++) {
121                                 for(x=0; x<ibuf->x; x++, cp+=4) {
122                                         val= cp[3];
123                                         cp[0]= (cp[0]*val)>>8;
124                                         cp[1]= (cp[1]*val)>>8;
125                                         cp[2]= (cp[2]*val)>>8;
126                                 }
127                         }
128                 }
129         }
130         if (ibuf->rect_float) {
131                 float val;
132                 float *cp;
133                 if(ibuf->depth==24) {   /* put alpha at 1.0 */
134                         cp= ibuf->rect_float;;
135                         for(y=0; y<ibuf->y; y++) {
136                                 for(x=0; x<ibuf->x; x++, cp+=4) {
137                                         cp[3]= 1.0;
138                                 }
139                         }
140                 } else {
141                         cp= ibuf->rect_float;
142                         for(y=0; y<ibuf->y; y++) {
143                                 for(x=0; x<ibuf->x; x++, cp+=4) {
144                                         val= cp[3];
145                                         cp[0]= cp[0]*val;
146                                         cp[1]= cp[1]*val;
147                                         cp[2]= cp[2]*val;
148                                 }
149                         }
150                 }
151         }
152 }
153
154 static void de_interlace_ng(struct ImBuf *ibuf) /* neogeo fields */
155 {
156         struct ImBuf * tbuf1, * tbuf2;
157         
158         if (ibuf == 0) return;
159         if (ibuf->flags & IB_fields) return;
160         ibuf->flags |= IB_fields;
161         
162         if (ibuf->rect) {
163                 /* make copies */
164                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect, (unsigned char)0);
165                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect, (unsigned char)0);
166                 
167                 ibuf->x *= 2;
168                 
169                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
170                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
171                 
172                 ibuf->x /= 2;
173                 IMB_rectcpy(ibuf, tbuf1, 0, 0, 0, 0, tbuf1->x, tbuf1->y);
174                 IMB_rectcpy(ibuf, tbuf2, 0, tbuf2->y, 0, 0, tbuf2->x, tbuf2->y);
175                 
176                 IMB_freeImBuf(tbuf1);
177                 IMB_freeImBuf(tbuf2);
178         }
179         ibuf->y /= 2;
180 }
181
182 static void de_interlace_st(struct ImBuf *ibuf) /* standard fields */
183 {
184         struct ImBuf * tbuf1, * tbuf2;
185         
186         if (ibuf == 0) return;
187         if (ibuf->flags & IB_fields) return;
188         ibuf->flags |= IB_fields;
189         
190         if (ibuf->rect) {
191                 /* make copies */
192                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect, 0);
193                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect, 0);
194                 
195                 ibuf->x *= 2;
196                 
197                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
198                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
199                 
200                 ibuf->x /= 2;
201                 IMB_rectcpy(ibuf, tbuf2, 0, 0, 0, 0, tbuf2->x, tbuf2->y);
202                 IMB_rectcpy(ibuf, tbuf1, 0, tbuf2->y, 0, 0, tbuf1->x, tbuf1->y);
203                 
204                 IMB_freeImBuf(tbuf1);
205                 IMB_freeImBuf(tbuf2);
206         }
207         ibuf->y /= 2;
208 }
209
210 void image_de_interlace(Image *ima, int odd)
211 {
212         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
213         if(ibuf) {
214                 if(odd)
215                         de_interlace_st(ibuf);
216                 else
217                         de_interlace_ng(ibuf);
218         }
219 }
220
221 /* ***************** ALLOC & FREE, DATA MANAGING *************** */
222
223 static void image_free_buffers(Image *ima)
224 {
225         ImBuf *ibuf;
226         
227         while((ibuf = ima->ibufs.first)) {
228                 BLI_remlink(&ima->ibufs, ibuf);
229                 
230                 if (ibuf->userdata) {
231                         MEM_freeN(ibuf->userdata);
232                         ibuf->userdata = NULL;
233                 }
234                 IMB_freeImBuf(ibuf);
235         }
236         
237         if(ima->anim) IMB_free_anim(ima->anim);
238         ima->anim= NULL;
239         
240         if(ima->rr) {
241                 RE_FreeRenderResult(ima->rr);
242                 ima->rr= NULL;
243         }       
244         
245         GPU_free_image(ima);
246         
247         ima->ok= IMA_OK;
248 }
249
250 /* called by library too, do not free ima itself */
251 void free_image(Image *ima)
252 {
253         image_free_buffers(ima);
254         if (ima->packedfile) {
255                 freePackedFile(ima->packedfile);
256                 ima->packedfile = NULL;
257         }
258         BKE_icon_delete(&ima->id);
259         ima->id.icon_id = 0;
260         if (ima->preview) {
261                 BKE_previewimg_free(&ima->preview);
262         }
263         if (ima->render_text) {
264                 MEM_freeN(ima->render_text);
265                 ima->render_text= NULL;
266         }
267 }
268
269 /* only image block itself */
270 static Image *image_alloc(const char *name, short source, short type)
271 {
272         Image *ima;
273         
274         ima= alloc_libblock(&G.main->image, ID_IM, name);
275         if(ima) {
276                 ima->ok= IMA_OK;
277                 
278                 ima->xrep= ima->yrep= 1;
279                 ima->aspx= ima->aspy= 1.0;
280                 ima->gen_x= 1024; ima->gen_y= 1024;
281                 ima->gen_type= 1;       /* no defines yet? */
282                 
283                 ima->source= source;
284                 ima->type= type;
285         }
286         return ima;
287 }
288
289 /* get the ibuf from an image cache, local use here only */
290 static ImBuf *image_get_ibuf(Image *ima, int index, int frame)
291 {
292         /* this function is intended to be thread safe. with IMA_NO_INDEX this
293          * should be OK, but when iterating over the list this is more tricky
294          * */
295         if(index==IMA_NO_INDEX)
296                 return ima->ibufs.first;
297         else {
298                 ImBuf *ibuf;
299
300                 index= IMA_MAKE_INDEX(frame, index);
301                 for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next)
302                         if(ibuf->index==index)
303                                 return ibuf;
304
305                 return NULL;
306         }
307 }
308
309 /* no ima->ibuf anymore, but listbase */
310 static void image_remove_ibuf(Image *ima, ImBuf *ibuf)
311 {
312         if(ibuf) {
313                 BLI_remlink(&ima->ibufs, ibuf);
314                 IMB_freeImBuf(ibuf);
315         }
316 }
317
318
319 /* no ima->ibuf anymore, but listbase */
320 static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
321 {
322         if(ibuf) {
323                 ImBuf *link;
324                 
325                 if(index!=IMA_NO_INDEX)
326                         index= IMA_MAKE_INDEX(frame, index);
327                 
328                 /* insert based on index */
329                 for(link= ima->ibufs.first; link; link= link->next)
330                         if(link->index>=index)
331                                 break;
332
333                 ibuf->index= index;
334
335                 /* this function accepts link==NULL */
336                 BLI_insertlinkbefore(&ima->ibufs, link, ibuf);
337
338                 /* now we don't want copies? */
339                 if(link && ibuf->index==link->index)
340                         image_remove_ibuf(ima, link);
341         }
342 }
343
344 /* empty image block, of similar type and filename */
345 Image *BKE_image_copy(Image *ima)
346 {
347         Image *new= image_alloc(ima->id.name+2, ima->source, ima->type);
348
349         BLI_strncpy(new->name, ima->name, sizeof(ima->name));
350         
351         new->gen_x= ima->gen_x;
352         new->gen_y= ima->gen_y;
353         new->gen_type= ima->gen_type;
354         
355         return new;
356 }
357
358 void BKE_image_merge(Image *dest, Image *source)
359 {
360         ImBuf *ibuf;
361         
362         /* sanity check */
363         if(dest && source && dest!=source) {
364         
365                 while((ibuf= source->ibufs.first)) {
366                         BLI_remlink(&source->ibufs, ibuf);
367                         image_assign_ibuf(dest, ibuf, IMA_INDEX_PASS(ibuf->index), IMA_INDEX_FRAME(ibuf->index));
368                 }
369                 
370                 free_libblock(&G.main->image, source);
371         }
372 }
373
374
375 /* checks if image was already loaded, then returns same image */
376 /* otherwise creates new. */
377 /* does not load ibuf itself */
378 /* pass on optional frame for #name images */
379 Image *BKE_add_image_file(const char *name, int frame)
380 {
381         Image *ima;
382         int file, len;
383         const char *libname;
384         char str[FILE_MAX], strtest[FILE_MAX];
385         
386         /* escape when name is directory */
387         len= strlen(name);
388         if(len) {
389                 if(name[len-1]=='/' || name[len-1]=='\\')
390                         return NULL;
391         }
392         
393         BLI_strncpy(str, name, sizeof(str));
394         BLI_convertstringcode(str, G.sce);
395         BLI_convertstringframe(str, frame);
396         
397         /* exists? */
398         file= open(str, O_BINARY|O_RDONLY);
399         if(file== -1) return NULL;
400         close(file);
401         
402         /* first search an identical image */
403         for(ima= G.main->image.first; ima; ima= ima->id.next) {
404                 if(ima->source!=IMA_SRC_VIEWER && ima->source!=IMA_SRC_GENERATED) {
405                         BLI_strncpy(strtest, ima->name, sizeof(ima->name));
406                         BLI_convertstringcode(strtest, G.sce);
407                         BLI_convertstringframe(strtest, frame);
408                         
409                         if( strcmp(strtest, str)==0 ) {
410                                 if(ima->anim==NULL || ima->id.us==0) {
411                                         BLI_strncpy(ima->name, name, sizeof(ima->name));        /* for stringcode */
412                                         ima->id.us++;                                                                           /* officially should not, it doesn't link here! */
413                                         if(ima->ok==0)
414                                                 ima->ok= IMA_OK;
415                         /* RETURN! */
416                                         return ima;
417                                 }
418                         }
419                 }
420         }
421         /* add new image */
422         
423         /* create a short library name */
424         len= strlen(name);
425         
426         while (len > 0 && name[len - 1] != '/' && name[len - 1] != '\\') len--;
427         libname= name+len;
428         
429         ima= image_alloc(libname, IMA_SRC_FILE, IMA_TYPE_IMAGE);
430         BLI_strncpy(ima->name, name, sizeof(ima->name));
431         
432         /* do a wild guess! */
433         if(BLI_testextensie(name, ".avi") || BLI_testextensie(name, ".mov")
434                         || BLI_testextensie(name, ".mpg")  || BLI_testextensie(name, ".mp4"))
435                 ima->source= IMA_SRC_MOVIE;
436         
437         return ima;
438 }
439
440 static ImBuf *add_ibuf_size(int width, int height, char *name, int floatbuf, short uvtestgrid, float color[4])
441 {
442         ImBuf *ibuf;
443         float h=0.0, hoffs=0.0, hue=0.0, s=0.9, v=0.9, r, g, b;
444         unsigned char *rect= NULL;
445         float *rect_float= NULL;
446         int x, y;
447         int checkerwidth=32, dark=1;
448         
449         if (floatbuf) {
450                 ibuf= IMB_allocImBuf(width, height, 24, IB_rectfloat, 0);
451                 rect_float= (float*)ibuf->rect_float;
452         }
453         else {
454                 ibuf= IMB_allocImBuf(width, height, 24, IB_rect, 0);
455                 rect= (unsigned char*)ibuf->rect;
456         }
457         
458         strcpy(ibuf->name, "//Untitled");
459         ibuf->userflags |= IB_BITMAPDIRTY;
460         
461         if (uvtestgrid) {
462                 /* these two passes could be combined into one, but it's more readable and 
463                 * easy to tweak like this, speed isn't really that much of an issue in this situation... */
464                 
465                 /* checkers */
466                 for(y=0; y<height; y++) {
467                         dark = powf(-1.0f, floorf(y / checkerwidth));
468                         
469                         for(x=0; x<width; x++) {
470                                 if (x % checkerwidth == 0) dark *= -1;
471                                 
472                                 if (floatbuf) {
473                                         if (dark > 0) {
474                                                 rect_float[0] = rect_float[1] = rect_float[2] = 0.25f;
475                                                 rect_float[3] = 1.0f;
476                                         } else {
477                                                 rect_float[0] = rect_float[1] = rect_float[2] = 0.58f;
478                                                 rect_float[3] = 1.0f;
479                                         }
480                                         rect_float+=4;
481                                 }
482                                 else {
483                                         if (dark > 0) {
484                                                 rect[0] = rect[1] = rect[2] = 64;
485                                                 rect[3] = 255;
486                                         } else {
487                                                 rect[0] = rect[1] = rect[2] = 150;
488                                                 rect[3] = 255;
489                                         }
490                                         rect += 4;
491                                 }
492                         }
493                 }
494                 
495                 /* 2nd pass, colored + */
496                 if (floatbuf) rect_float= (float*)ibuf->rect_float;
497                 else rect= (unsigned char*)ibuf->rect;
498                 
499                 for(y=0; y<height; y++) {
500                         hoffs = 0.125f * floorf(y / checkerwidth);
501                         
502                         for(x=0; x<width; x++) {
503                                 h = 0.125f * floorf(x / checkerwidth);
504                                 
505                                 if ((fabs((x % checkerwidth) - (checkerwidth / 2)) < 4) &&
506                                         (fabs((y % checkerwidth) - (checkerwidth / 2)) < 4)) {
507                                         
508                                         if ((fabs((x % checkerwidth) - (checkerwidth / 2)) < 1) ||
509                                                 (fabs((y % checkerwidth) - (checkerwidth / 2)) < 1)) {
510                                                 
511                                                 hue = fmodf(fabs(h-hoffs), 1.0f);
512                                                 hsv_to_rgb(hue, s, v, &r, &g, &b);
513                                                 
514                                                 if (floatbuf) {
515                                                         rect_float[0]= r;
516                                                         rect_float[1]= g;
517                                                         rect_float[2]= b;
518                                                         rect_float[3]= 1.0f;
519                                                 }
520                                                 else {
521                                                         rect[0]= (char)(r * 255.0f);
522                                                         rect[1]= (char)(g * 255.0f);
523                                                         rect[2]= (char)(b * 255.0f);
524                                                         rect[3]= 255;
525                                                 }
526                                         }
527                                 }
528
529                                 if (floatbuf)
530                                         rect_float+=4;
531                                 else
532                                         rect+=4;
533                         }
534                 }
535         } else {        /* blank image */
536                 char ccol[4];
537
538                 ccol[0]= (char)(color[0]*255.0f);
539                 ccol[1]= (char)(color[1]*255.0f);
540                 ccol[2]= (char)(color[2]*255.0f);
541                 ccol[3]= (char)(color[3]*255.0f);
542
543                 for(y=0; y<height; y++) {
544                         for(x=0; x<width; x++) {
545                                 if (floatbuf) {
546                                         rect_float[0]= color[0];
547                                         rect_float[1]= color[1];
548                                         rect_float[2]= color[2];
549                                         rect_float[3]= color[3];
550                                         rect_float+=4;
551                                 }
552                                 else {
553                                         rect[0]= ccol[0];
554                                         rect[1]= ccol[1];
555                                         rect[2]= ccol[2];
556                                         rect[3]= ccol[3];
557                                         rect+=4;
558                                 }
559                         }
560                 }
561         }
562         return ibuf;
563 }
564
565 /* adds new image block, creates ImBuf and initializes color */
566 Image *BKE_add_image_size(int width, int height, char *name, int floatbuf, short uvtestgrid, float color[4])
567 {
568         Image *ima;
569         
570         /* on save, type is changed to FILE in editsima.c */
571         ima= image_alloc(name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
572         
573         if (ima) {
574                 ImBuf *ibuf;
575                 
576                 BLI_strncpy(ima->name, name, FILE_MAX);
577                 ima->gen_x= width;
578                 ima->gen_y= height;
579                 ima->gen_type= uvtestgrid;
580                 
581                 ibuf= add_ibuf_size(width, height, name, floatbuf, uvtestgrid, color);
582                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
583                 
584                 ima->ok= IMA_OK_LOADED;
585         }
586
587         return ima;
588 }
589
590 /* packs rect from memory as PNG */
591 void BKE_image_memorypack(Image *ima)
592 {
593         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
594         
595         if(ibuf==NULL)
596                 return;
597         if (ima->packedfile) {
598                 freePackedFile(ima->packedfile);
599                 ima->packedfile = NULL;
600         }
601         
602         ibuf->ftype= PNG;
603         ibuf->depth= 32;
604         
605         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
606         if(ibuf->encodedbuffer==NULL) {
607                 printf("memory save for pack error\n");
608         }
609         else {
610                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
611                 
612                 pf->data = ibuf->encodedbuffer;
613                 pf->size = ibuf->encodedsize;
614                 ima->packedfile= pf;
615                 ibuf->encodedbuffer= NULL;
616                 ibuf->encodedsize= 0;
617                 ibuf->userflags &= ~IB_BITMAPDIRTY;
618                 
619                 if(ima->source==IMA_SRC_GENERATED) {
620                         ima->source= IMA_SRC_FILE;
621                         ima->type= IMA_TYPE_IMAGE;
622                 }
623         }
624 }
625
626 void tag_image_time(Image *ima)
627 {
628         if (ima)
629                 ima->lastused = (int)PIL_check_seconds_timer();
630 }
631
632 #if 0
633 static void tag_all_images_time() 
634 {
635         Image *ima;
636         int ctime = (int)PIL_check_seconds_timer();
637
638         ima= G.main->image.first;
639         while(ima) {
640                 if(ima->bindcode || ima->repbind || ima->ibufs.first) {
641                         ima->lastused = ctime;
642                 }
643         }
644 }
645 #endif
646
647 void free_old_images()
648 {
649         Image *ima;
650         static int lasttime = 0;
651         int ctime = (int)PIL_check_seconds_timer();
652         
653         /* 
654            Run garbage collector once for every collecting period of time 
655            if textimeout is 0, that's the option to NOT run the collector
656         */
657         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
658                 return;
659
660         lasttime = ctime;
661
662         ima= G.main->image.first;
663         while(ima) {
664                 if((ima->flag & IMA_NOCOLLECT)==0 && ctime - ima->lastused > U.textimeout) {
665                         /*
666                            If it's in GL memory, deallocate and set time tag to current time
667                            This gives textures a "second chance" to be used before dying.
668                         */
669                         if(ima->bindcode || ima->repbind) {
670                                 GPU_free_image(ima);
671                                 ima->lastused = ctime;
672                         }
673                         /* Otherwise, just kill the buffers */
674                         else if (ima->ibufs.first) {
675                                 image_free_buffers(ima);
676                         }
677                 }
678                 ima = ima->id.next;
679         }
680 }
681
682 static uintptr_t image_mem_size(Image *ima)
683 {
684         ImBuf *ibuf, *ibufm;
685         int level;
686         uintptr_t size = 0;
687
688         size= 0;
689         
690         /* viewers have memory depending on other rules, has no valid rect pointer */
691         if(ima->source==IMA_SRC_VIEWER)
692                 return 0;
693         
694         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
695                 if(ibuf->rect) size += MEM_allocN_len(ibuf->rect);
696                 else if(ibuf->rect_float) size += MEM_allocN_len(ibuf->rect_float);
697
698                 for(level=0; level<IB_MIPMAP_LEVELS; level++) {
699                         ibufm= ibuf->mipmap[level];
700                         if(ibufm) {
701                                 if(ibufm->rect) size += MEM_allocN_len(ibufm->rect);
702                                 else if(ibufm->rect_float) size += MEM_allocN_len(ibufm->rect_float);
703                         }
704                 }
705         }
706
707         return size;
708 }
709
710 void BKE_image_print_memlist(void)
711 {
712         Image *ima;
713         uintptr_t size, totsize= 0;
714
715         for(ima= G.main->image.first; ima; ima= ima->id.next)
716                 totsize += image_mem_size(ima);
717
718         printf("\ntotal image memory len: %.3lf MB\n", (double)totsize/(double)(1024*1024));
719
720         for(ima= G.main->image.first; ima; ima= ima->id.next) {
721                 size= image_mem_size(ima);
722
723                 if(size)
724                         printf("%s len: %.3f MB\n", ima->id.name+2, (double)size/(double)(1024*1024));
725         }
726 }
727
728 void BKE_image_free_all_textures(void)
729 {
730         Tex *tex;
731         Image *ima;
732         unsigned int totsize= 0;
733         
734         for(ima= G.main->image.first; ima; ima= ima->id.next)
735                 ima->id.flag &= ~LIB_DOIT;
736         
737         for(tex= G.main->tex.first; tex; tex= tex->id.next)
738                 if(tex->ima)
739                         tex->ima->id.flag |= LIB_DOIT;
740         
741         for(ima= G.main->image.first; ima; ima= ima->id.next) {
742                 if(ima->ibufs.first && (ima->id.flag & LIB_DOIT)) {
743                         ImBuf *ibuf;
744                         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
745                                 if(ibuf->mipmap[0]) 
746                                         totsize+= 1.33*ibuf->x*ibuf->y*4;
747                                 else
748                                         totsize+= ibuf->x*ibuf->y*4;
749                         }
750                         image_free_buffers(ima);
751                 }
752         }
753         /* printf("freed total %d MB\n", totsize/(1024*1024)); */
754 }
755
756 /* except_frame is weak, only works for seqs without offset... */
757 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
758 {
759         ImBuf *ibuf, *nbuf;
760
761         for(ibuf= ima->ibufs.first; ibuf; ibuf= nbuf) {
762                 nbuf= ibuf->next;
763                 if(ibuf->userflags & IB_BITMAPDIRTY)
764                         continue;
765                 if(ibuf->index==IMA_NO_INDEX)
766                         continue;
767                 if(except_frame!=IMA_INDEX_FRAME(ibuf->index)) {
768                         BLI_remlink(&ima->ibufs, ibuf);
769                         
770                         if (ibuf->userdata) {
771                                 MEM_freeN(ibuf->userdata);
772                                 ibuf->userdata = NULL;
773                         }
774                         IMB_freeImBuf(ibuf);
775                 }                                       
776         }
777 }
778
779 void BKE_image_all_free_anim_ibufs(int cfra)
780 {
781         Image *ima;
782         
783         for(ima= G.main->image.first; ima; ima= ima->id.next)
784                 if(ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE))
785                         BKE_image_free_anim_ibufs(ima, cfra);
786 }
787
788
789 /* *********** READ AND WRITE ************** */
790
791 int BKE_imtype_to_ftype(int imtype)
792 {
793         if(imtype==0)
794                 return TGA;
795         else if(imtype== R_IRIS) 
796                 return IMAGIC;
797         else if (imtype==R_RADHDR)
798                 return RADHDR;
799         else if (imtype==R_PNG)
800                 return PNG;
801 #ifdef WITH_DDS
802         else if (imtype==R_DDS)
803                 return DDS;
804 #endif
805         else if (imtype==R_BMP)
806                 return BMP;
807         else if (imtype==R_TIFF)
808                 return TIF;
809         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER)
810                 return OPENEXR;
811         else if (imtype==R_CINEON)
812                 return CINEON;
813         else if (imtype==R_DPX)
814                 return DPX;
815         else if (imtype==R_TARGA)
816                 return TGA;
817         else if(imtype==R_RAWTGA)
818                 return RAWTGA;
819         else if(imtype==R_HAMX)
820                 return AN_hamx;
821 #ifdef WITH_OPENJPEG
822         else if(imtype==R_JP2)
823                 return JP2;
824 #endif
825         else
826                 return JPG|90;
827 }
828
829 int BKE_ftype_to_imtype(int ftype)
830 {
831         if(ftype==0)
832                 return TGA;
833         else if(ftype == IMAGIC) 
834                 return R_IRIS;
835         else if (ftype & RADHDR)
836                 return R_RADHDR;
837         else if (ftype & PNG)
838                 return R_PNG;
839 #ifdef WITH_DDS
840         else if (ftype & DDS)
841                 return R_DDS;
842 #endif
843         else if (ftype & BMP)
844                 return R_BMP;
845         else if (ftype & TIF)
846                 return R_TIFF;
847         else if (ftype & OPENEXR)
848                 return R_OPENEXR;
849         else if (ftype & CINEON)
850                 return R_CINEON;
851         else if (ftype & DPX)
852                 return R_DPX;
853         else if (ftype & TGA)
854                 return R_TARGA;
855         else if(ftype & RAWTGA)
856                 return R_RAWTGA;
857         else if(ftype == AN_hamx)
858                 return R_HAMX;
859 #ifdef WITH_OPENJPEG
860         else if(ftype & JP2)
861                 return R_JP2;
862 #endif
863         else
864                 return R_JPEG90;
865 }
866
867
868 int BKE_imtype_is_movie(int imtype)
869 {
870         switch(imtype) {
871         case R_MOVIE:
872         case R_AVIRAW:
873         case R_AVIJPEG:
874         case R_AVICODEC:
875         case R_QUICKTIME:
876         case R_FFMPEG:
877         case R_H264:
878         case R_THEORA:
879         case R_XVID:
880         case R_FRAMESERVER:
881                         return 1;
882         }
883         return 0;
884 }
885
886 void BKE_add_image_extension(Scene *scene, char *string, int imtype)
887 {
888         char *extension="";
889         
890         if(imtype== R_IRIS) {
891                 if(!BLI_testextensie(string, ".rgb"))
892                         extension= ".rgb";
893         }
894         else if(imtype==R_IRIZ) {
895                 if(!BLI_testextensie(string, ".rgb"))
896                         extension= ".rgb";
897         }
898         else if(imtype==R_RADHDR) {
899                 if(!BLI_testextensie(string, ".hdr"))
900                         extension= ".hdr";
901         }
902         else if (ELEM5(imtype, R_PNG, R_FFMPEG, R_H264, R_THEORA, R_XVID)) {
903                 if(!BLI_testextensie(string, ".png"))
904                         extension= ".png";
905         }
906 #ifdef WITH_DDS
907         else if(imtype==R_DDS) {
908                 if(!BLI_testextensie(string, ".dds"))
909                         extension= ".dds";
910         }
911 #endif
912         else if(imtype==R_RAWTGA) {
913                 if(!BLI_testextensie(string, ".tga"))
914                         extension= ".tga";
915         }
916         else if(imtype==R_BMP) {
917                 if(!BLI_testextensie(string, ".bmp"))
918                         extension= ".bmp";
919         }
920         else if(G.have_libtiff && (imtype==R_TIFF)) {
921                 if(!BLI_testextensie(string, ".tif") && 
922                         !BLI_testextensie(string, ".tiff")) extension= ".tif";
923         }
924 #ifdef WITH_OPENEXR
925         else if( ELEM(imtype, R_OPENEXR, R_MULTILAYER)) {
926                 if(!BLI_testextensie(string, ".exr"))
927                         extension= ".exr";
928         }
929 #endif
930         else if(imtype==R_CINEON){
931                 if (!BLI_testextensie(string, ".cin"))
932                         extension= ".cin";
933         }
934         else if(imtype==R_DPX){
935                 if (!BLI_testextensie(string, ".dpx"))
936                         extension= ".dpx";
937         }
938         else if(imtype==R_TARGA) {
939                 if(!BLI_testextensie(string, ".tga"))
940                         extension= ".tga";
941         }
942 #ifdef WITH_OPENJPEG
943         else if(imtype==R_JP2) {
944                 if(!BLI_testextensie(string, ".jp2"))
945                         extension= ".jp2";
946         }
947 #endif
948         else { //   R_MOVIE, R_AVICODEC, R_AVIRAW, R_AVIJPEG, R_JPEG90, R_QUICKTIME etc
949                 if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
950                         extension= ".jpg";
951         }
952
953         strcat(string, extension);
954 }
955
956 /* could allow access externally - 512 is for long names, 64 is for id names */
957 typedef struct StampData {
958         char    file[512];
959         char    note[512];
960         char    date[512];
961         char    marker[512];
962         char    time[512];
963         char    frame[512];
964         char    camera[64];
965         char    scene[64];
966         char    strip[64];
967         char    rendertime[64];
968 } StampData;
969
970 static void stampdata(Scene *scene, StampData *stamp_data, int do_prefix)
971 {
972         char text[256];
973         
974 #ifndef WIN32
975         struct tm *tl;
976         time_t t;
977 #else
978         char sdate[9];
979 #endif /* WIN32 */
980         
981         if (scene->r.stamp & R_STAMP_FILENAME) {
982                 if (G.relbase_valid) {
983                         if (do_prefix)          sprintf(stamp_data->file, "File %s", G.sce);
984                         else                            sprintf(stamp_data->file, "%s", G.sce);
985                 } else {
986                         if (do_prefix)          strcpy(stamp_data->file, "File <untitled>");
987                         else                            strcpy(stamp_data->file, "<untitled>");
988                 }
989         } else {
990                 stamp_data->file[0] = '\0';
991         }
992         
993         if (scene->r.stamp & R_STAMP_NOTE) {
994                 /* Never do prefix for Note */
995                 sprintf(stamp_data->note, "%s", scene->r.stamp_udata);
996         } else {
997                 stamp_data->note[0] = '\0';
998         }
999         
1000         if (scene->r.stamp & R_STAMP_DATE) {
1001 #ifdef WIN32
1002                 _strdate (sdate);
1003                 sprintf (text, "%s", sdate);
1004 #else
1005                 t = time (NULL);
1006                 tl = localtime (&t);
1007                 sprintf (text, "%04d-%02d-%02d", tl->tm_year+1900, tl->tm_mon+1, tl->tm_mday);
1008 #endif /* WIN32 */
1009                 if (do_prefix)          sprintf(stamp_data->date, "Date %s", text);
1010                 else                            sprintf(stamp_data->date, "%s", text);
1011         } else {
1012                 stamp_data->date[0] = '\0';
1013         }
1014         
1015         if (scene->r.stamp & R_STAMP_MARKER) {
1016                 TimeMarker *marker = NULL; // XXX get_frame_marker(scene->r.cfra);
1017         
1018                 if (marker) strcpy(text, marker->name);
1019                 else            strcpy(text, "<none>");
1020                 
1021                 if (do_prefix)          sprintf(stamp_data->marker, "Marker %s", text);
1022                 else                            sprintf(stamp_data->marker, "%s", text);
1023         } else {
1024                 stamp_data->marker[0] = '\0';
1025         }
1026         
1027         if (scene->r.stamp & R_STAMP_TIME) {
1028                 int h, m, s, f;
1029                 h= m= s= f= 0;
1030                 f = (int)(scene->r.cfra % scene->r.frs_sec);
1031                 s = (int)(scene->r.cfra / scene->r.frs_sec);
1032
1033                 if (s) {
1034                         m = (int)(s / 60);
1035                         s %= 60;
1036
1037                         if (m) {
1038                                 h = (int)(m / 60);
1039                                 m %= 60;
1040                         }
1041                 }
1042
1043                 if (scene->r.frs_sec < 100)
1044                         sprintf (text, "%02d:%02d:%02d.%02d", h, m, s, f);
1045                 else
1046                         sprintf (text, "%02d:%02d:%02d.%03d", h, m, s, f);
1047                 
1048                 if (do_prefix)          sprintf(stamp_data->time, "Time %s", text);
1049                 else                            sprintf(stamp_data->time, "%s", text);
1050         } else {
1051                 stamp_data->time[0] = '\0';
1052         }
1053         
1054         if (scene->r.stamp & R_STAMP_FRAME) {
1055                 char format[32];
1056                 if (do_prefix)          sprintf(format, "Frame %%0%di", 1 + (int) log10(scene->r.efra));
1057                 else                            sprintf(format, "%%0%di", 1 + (int) log10(scene->r.efra));
1058                 sprintf (stamp_data->frame, format, scene->r.cfra);
1059         } else {
1060                 stamp_data->frame[0] = '\0';
1061         }
1062
1063         if (scene->r.stamp & R_STAMP_CAMERA) {
1064                 if (scene->camera) strcpy(text, ((Camera *) scene->camera)->id.name+2);
1065                 else            strcpy(text, "<none>");
1066                 
1067                 if (do_prefix)          sprintf(stamp_data->camera, "Camera %s", text);
1068                 else                            sprintf(stamp_data->camera, "%s", text);
1069         } else {
1070                 stamp_data->camera[0] = '\0';
1071         }
1072
1073         if (scene->r.stamp & R_STAMP_SCENE) {
1074                 if (do_prefix)          sprintf(stamp_data->scene, "Scene %s", scene->id.name+2);
1075                 else                            sprintf(stamp_data->scene, "%s", scene->id.name+2);
1076         } else {
1077                 stamp_data->scene[0] = '\0';
1078         }
1079         
1080         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1081                 Sequence *seq= NULL; //XXX = get_foreground_frame_seq(scene->r.cfra);
1082         
1083                 if (seq) strcpy(text, seq->name+2);
1084                 else            strcpy(text, "<none>");
1085                 
1086                 if (do_prefix)          sprintf(stamp_data->strip, "Strip %s", text);
1087                 else                            sprintf(stamp_data->strip, "%s", text);
1088         } else {
1089                 stamp_data->strip[0] = '\0';
1090         }
1091
1092         {
1093                 Render *re= RE_GetRender(scene->id.name);
1094                 RenderStats *stats= re ? RE_GetStats(re):NULL;
1095
1096                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1097                         BLI_timestr(stats->lastframetime, text);
1098
1099                         if (do_prefix)          sprintf(stamp_data->rendertime, "RenderTime %s", text);
1100                         else                            sprintf(stamp_data->rendertime, "%s", text);
1101                 } else {
1102                         stamp_data->rendertime[0] = '\0';
1103                 }
1104         }
1105 }
1106
1107 // XXX - Bad level call.
1108 extern int datatoc_bmonofont_ttf_size;
1109 extern char datatoc_bmonofont_ttf[];
1110
1111 // XXX - copied from text_font_begin
1112 static void stamp_font_begin(int size)
1113 {
1114         static int mono= -1;
1115
1116         if (mono == -1)
1117                 mono= BLF_load_mem("monospace", (unsigned char *)datatoc_bmonofont_ttf, datatoc_bmonofont_ttf_size);
1118
1119         BLF_set(mono);
1120         BLF_aspect(1.0);
1121         BLF_size(size, 72);
1122 }
1123
1124 void BKE_stamp_buf(Scene *scene, unsigned char *rect, float *rectf, int width, int height, int channels)
1125 {
1126         struct StampData stamp_data;
1127         float w, h, pad;
1128         int x, y;
1129         
1130         if (!rect && !rectf)
1131                 return;
1132         
1133         stampdata(scene, &stamp_data, 1);
1134
1135         /* TODO, do_versions */
1136         if(scene->r.stamp_font_id < 8)
1137                 scene->r.stamp_font_id= 12;
1138
1139         stamp_font_begin(scene->r.stamp_font_id);
1140
1141         BLF_buffer(rectf, rect, width, height, channels);
1142         BLF_buffer_col(scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1143         pad= BLF_width("--");
1144
1145         x= 0;
1146         y= height;
1147
1148         if (stamp_data.file[0]) {
1149                 /* Top left corner */
1150                 BLF_width_and_height(stamp_data.file, &w, &h);
1151                 y -= h;
1152
1153                 /* also a little of space to the background. */
1154                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y-3, w+3, y+h+3);
1155
1156                 /* and draw the text. */
1157                 BLF_position(x, y, 0.0);
1158                 BLF_draw_buffer(stamp_data.file);
1159
1160                 /* the extra pixel for background. */
1161                 y -= 4;
1162         }
1163
1164         /* Top left corner, below File */
1165         if (stamp_data.note[0]) {
1166                 BLF_width_and_height(stamp_data.note, &w, &h);
1167                 y -= h;
1168
1169                 /* and space for background. */
1170                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-2, w+3, y+h+2);
1171
1172                 BLF_position(x, y+1, 0.0);
1173                 BLF_draw_buffer(stamp_data.note);
1174
1175                 /* the extra pixel for background. */
1176                 y -= 4;
1177         }
1178         
1179         /* Top left corner, below File (or Note) */
1180         if (stamp_data.date[0]) {
1181                 BLF_width_and_height(stamp_data.date, &w, &h);
1182                 y -= h;
1183
1184                 /* and space for background. */
1185                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+3);
1186
1187                 BLF_position(x, y, 0.0);
1188                 BLF_draw_buffer(stamp_data.date);
1189
1190                 /* the extra pixel for background. */
1191                 y -= 4;
1192         }
1193
1194         /* Top left corner, below File, Date or Note */
1195         if (stamp_data.rendertime[0]) {
1196                 BLF_width_and_height(stamp_data.rendertime, &w, &h);
1197                 y -= h;
1198
1199                 /* and space for background. */
1200                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+3);
1201
1202                 BLF_position(x, y, 0.0);
1203                 BLF_draw_buffer(stamp_data.rendertime);
1204         }
1205
1206         x= 0;
1207         y= 0;
1208
1209         /* Bottom left corner, leaving space for timing */
1210         if (stamp_data.marker[0]) {
1211                 BLF_width_and_height(stamp_data.marker, &w, &h);
1212
1213                 /* extra space for background. */
1214                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, w+2, y+h+3);
1215
1216                 /* and pad the text. */
1217                 BLF_position(x, y+3, 0.0);
1218                 BLF_draw_buffer(stamp_data.marker);
1219
1220                 /* space width. */
1221                 x += w + pad;
1222         }
1223         
1224         /* Left bottom corner */
1225         if (stamp_data.time[0]) {
1226                 BLF_width_and_height(stamp_data.time, &w, &h);
1227
1228                 /* extra space for background */
1229                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+3);
1230
1231                 /* and pad the text. */
1232                 BLF_position(x, y+3, 0.0);
1233                 BLF_draw_buffer(stamp_data.time);
1234
1235                 /* space width. */
1236                 x += w + pad;
1237         }
1238         
1239         if (stamp_data.frame[0]) {
1240                 BLF_width_and_height(stamp_data.frame, &w, &h);
1241
1242                 /* extra space for background. */
1243                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+3);
1244
1245                 /* and pad the text. */
1246                 BLF_position(x, y+3, 0.0);
1247
1248                 BLF_draw_buffer(stamp_data.frame);
1249
1250                 /* space width. */
1251                 x += w + pad;
1252         }
1253
1254         if (stamp_data.camera[0]) {
1255                 BLF_width_and_height(stamp_data.camera, &w, &h);
1256
1257                 /* extra space for background. */
1258                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+3);
1259                 BLF_position(x, y+3, 0.0);
1260                 BLF_draw_buffer(stamp_data.camera);
1261         }
1262         
1263         if (stamp_data.scene[0]) {
1264                 BLF_width_and_height(stamp_data.scene, &w, &h);
1265
1266                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1267                 x= width - w - 2;
1268
1269                 /* extra space for background. */
1270                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+3, y+h+3);
1271
1272                 /* and pad the text. */
1273                 BLF_position(x, y+3, 0.0);
1274                 BLF_draw_buffer(stamp_data.scene);
1275         }
1276         
1277         if (stamp_data.strip[0]) {
1278                 BLF_width_and_height(stamp_data.scene, &w, &h);
1279
1280                 /* Top right corner, with an extra space because blenfont is too strict! */
1281                 x= width - w - pad;
1282                 y= height - h;
1283
1284                 /* extra space for background. */
1285                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y-3, x+w+pad, y+h+3);
1286
1287                 BLF_position(x, y, 0.0);
1288                 BLF_draw_buffer(stamp_data.strip);
1289         }
1290
1291         /* cleanup the buffer. */
1292         BLF_buffer(NULL, NULL, 0, 0, 0);
1293 }
1294
1295 void BKE_stamp_info(Scene *scene, struct ImBuf *ibuf)
1296 {
1297         struct StampData stamp_data;
1298
1299         if (!ibuf)      return;
1300         
1301         /* fill all the data values, no prefix */
1302         stampdata(scene, &stamp_data, 0);
1303         
1304         if (stamp_data.file[0])         IMB_imginfo_change_field (ibuf, "File",         stamp_data.file);
1305         if (stamp_data.note[0])         IMB_imginfo_change_field (ibuf, "Note",         stamp_data.note);
1306         if (stamp_data.date[0])         IMB_imginfo_change_field (ibuf, "Date",         stamp_data.date);
1307         if (stamp_data.marker[0])       IMB_imginfo_change_field (ibuf, "Marker",       stamp_data.marker);
1308         if (stamp_data.time[0])         IMB_imginfo_change_field (ibuf, "Time",         stamp_data.time);
1309         if (stamp_data.frame[0])        IMB_imginfo_change_field (ibuf, "Frame",        stamp_data.frame);
1310         if (stamp_data.camera[0])       IMB_imginfo_change_field (ibuf, "Camera",       stamp_data.camera);
1311         if (stamp_data.scene[0])        IMB_imginfo_change_field (ibuf, "Scene",        stamp_data.scene);
1312         if (stamp_data.strip[0])        IMB_imginfo_change_field (ibuf, "Strip",        stamp_data.strip);
1313 }
1314
1315 int BKE_write_ibuf(Scene *scene, ImBuf *ibuf, char *name, int imtype, int subimtype, int quality)
1316 {
1317         int ok;
1318         
1319         if(imtype==0);
1320         else if(imtype== R_IRIS) 
1321                 ibuf->ftype= IMAGIC;
1322         else if ((imtype==R_RADHDR)) {
1323                 ibuf->ftype= RADHDR;
1324         }
1325         else if (ELEM5(imtype, R_PNG, R_FFMPEG, R_H264, R_THEORA, R_XVID)) {
1326                 ibuf->ftype= PNG;
1327         }
1328 #ifdef WITH_DDS
1329         else if ((imtype==R_DDS)) {
1330                 ibuf->ftype= DDS;
1331         }
1332 #endif
1333         else if ((imtype==R_BMP)) {
1334                 ibuf->ftype= BMP;
1335         }
1336         else if ((G.have_libtiff) && (imtype==R_TIFF)) {
1337                 ibuf->ftype= TIF;
1338
1339                 if(subimtype & R_TIFF_16BIT)
1340                         ibuf->ftype |= TIF_16BIT;
1341         }
1342 #ifdef WITH_OPENEXR
1343         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
1344                 ibuf->ftype= OPENEXR;
1345                 if(subimtype & R_OPENEXR_HALF)
1346                         ibuf->ftype |= OPENEXR_HALF;
1347                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1348                 
1349                 if(!(subimtype & R_OPENEXR_ZBUF))
1350                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1351                 
1352         }
1353 #endif
1354         else if (imtype==R_CINEON) {
1355                 ibuf->ftype = CINEON;
1356         }
1357         else if (imtype==R_DPX) {
1358                 ibuf->ftype = DPX;
1359         }
1360         else if (imtype==R_TARGA) {
1361                 ibuf->ftype= TGA;
1362         }
1363         else if(imtype==R_RAWTGA) {
1364                 ibuf->ftype= RAWTGA;
1365         }
1366         else if(imtype==R_HAMX) {
1367                 ibuf->ftype= AN_hamx;
1368         }
1369 #ifdef WITH_OPENJPEG
1370         else if(imtype==R_JP2) {
1371                 if(quality < 10) quality= 90;
1372                 ibuf->ftype= JP2|quality;
1373                 
1374                 if (subimtype & R_JPEG2K_16BIT) {
1375                         ibuf->ftype |= JP2_16BIT;
1376                 } else if (subimtype & R_JPEG2K_12BIT) {
1377                         ibuf->ftype |= JP2_12BIT;
1378                 }
1379                 
1380                 if (subimtype & R_JPEG2K_YCC) {
1381                         ibuf->ftype |= JP2_YCC;
1382                 }
1383                 
1384                 if (subimtype & R_JPEG2K_CINE_PRESET) {
1385                         ibuf->ftype |= JP2_CINE;
1386                         if (subimtype & R_JPEG2K_CINE_48FPS)
1387                                 ibuf->ftype |= JP2_CINE_48FPS;
1388                 }
1389         }
1390 #endif
1391         else {
1392                 /* R_JPEG90, R_MOVIE, etc. default we save jpegs */
1393                 if(quality < 10) quality= 90;
1394                 ibuf->ftype= JPG|quality;
1395                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
1396         }
1397         
1398         BLI_make_existing_file(name);
1399
1400         if(scene->r.stamp & R_STAMP_ALL)
1401                 BKE_stamp_info(scene, ibuf);
1402         
1403         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1404         if (ok == 0) {
1405                 perror(name);
1406         }
1407         
1408         return(ok);
1409 }
1410
1411
1412 void BKE_makepicstring(struct Scene *scene, char *string, char *base, int frame, int imtype)
1413 {
1414         if (string==NULL) return;
1415
1416         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1417         
1418         /* if we dont have any #'s to insert numbers into, use 4 numbers by default */
1419         if (strchr(string, '#')==NULL)
1420                 strcat(string, "####"); /* 4 numbers */
1421         
1422         BLI_convertstringcode(string, G.sce);
1423         BLI_convertstringframe(string, frame);
1424
1425         if(scene->r.scemode & R_EXTENSION) 
1426                 BKE_add_image_extension(scene, string, imtype);
1427                 
1428 }
1429
1430 /* used by sequencer too */
1431 struct anim *openanim(char *name, int flags)
1432 {
1433         struct anim *anim;
1434         struct ImBuf *ibuf;
1435         
1436         anim = IMB_open_anim(name, flags);
1437         if (anim == NULL) return(0);
1438
1439         ibuf = IMB_anim_absolute(anim, 0);
1440         if (ibuf == NULL) {
1441                 printf("not an anim; %s\n", name);
1442                 IMB_free_anim(anim);
1443                 return(0);
1444         }
1445         IMB_freeImBuf(ibuf);
1446         
1447         return(anim);
1448 }
1449
1450 /* ************************* New Image API *************** */
1451
1452
1453 /* Notes about Image storage 
1454 - packedfile
1455   -> written in .blend
1456 - filename
1457   -> written in .blend
1458 - movie
1459   -> comes from packedfile or filename
1460 - renderresult
1461   -> comes from packedfile or filename
1462 - listbase
1463   -> ibufs from exrhandle
1464 - flipbook array
1465   -> ibufs come from movie, temporary renderresult or sequence
1466 - ibuf
1467   -> comes from packedfile or filename or generated
1468
1469 */
1470
1471
1472 /* forces existance of 1 Image for renderout or nodes, returns Image */
1473 /* name is only for default, when making new one */
1474 Image *BKE_image_verify_viewer(int type, const char *name)
1475 {
1476         Image *ima;
1477         
1478         for(ima=G.main->image.first; ima; ima= ima->id.next)
1479                 if(ima->source==IMA_SRC_VIEWER)
1480                         if(ima->type==type)
1481                                 break;
1482         
1483         if(ima==NULL)
1484                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1485         
1486         /* happens on reload, imagewindow cannot be image user when hidden*/
1487         if(ima->id.us==0)
1488                 id_us_plus(&ima->id);
1489
1490         return ima;
1491 }
1492
1493 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1494 {
1495         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1496 }
1497
1498 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1499 {
1500         if(ima==NULL)
1501                 return;
1502         
1503         switch(signal) {
1504         case IMA_SIGNAL_FREE:
1505                 image_free_buffers(ima);
1506                 if(iuser)
1507                         iuser->ok= 1;
1508                 break;
1509         case IMA_SIGNAL_SRC_CHANGE:
1510                 if(ima->type == IMA_TYPE_UV_TEST)
1511                         if(ima->source != IMA_SRC_GENERATED)
1512                                 ima->type= IMA_TYPE_IMAGE;
1513
1514                 if(ima->source==IMA_SRC_GENERATED) {
1515                         if(ima->gen_x==0 || ima->gen_y==0) {
1516                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1517                                 if(ibuf) {
1518                                         ima->gen_x= ibuf->x;
1519                                         ima->gen_y= ibuf->y;
1520                                 }
1521                         }
1522                 }
1523
1524                 image_free_buffers(ima);
1525
1526                 ima->ok= 1;
1527                 if(iuser)
1528                         iuser->ok= 1;
1529                 break;
1530                         
1531         case IMA_SIGNAL_RELOAD:
1532                 /* try to repack file */
1533                 if(ima->packedfile) {
1534                         PackedFile *pf;
1535                         pf = newPackedFile(NULL, ima->name);
1536                         if (pf) {
1537                                 freePackedFile(ima->packedfile);
1538                                 ima->packedfile = pf;
1539                                 image_free_buffers(ima);
1540                         } else {
1541                                 printf("ERROR: Image not available. Keeping packed image\n");
1542                         }
1543                 }
1544                 else
1545                         image_free_buffers(ima);
1546                 
1547                 if(iuser)
1548                         iuser->ok= 1;
1549                 
1550                 break;
1551         case IMA_SIGNAL_USER_NEW_IMAGE:
1552                 if(iuser) {
1553                         iuser->ok= 1;
1554                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1555                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1556                                         iuser->multi_index= 0;
1557                                         iuser->layer= iuser->pass= 0;
1558                                 }
1559                         }
1560                 }
1561                 break;
1562         }
1563 }
1564
1565 /* if layer or pass changes, we need an index for the imbufs list */
1566 /* note it is called for rendered results, but it doesnt use the index! */
1567 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1568 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1569 {
1570         RenderLayer *rl;
1571         RenderPass *rpass= NULL;
1572         
1573         if(rr==NULL) 
1574                 return NULL;
1575         
1576         if(iuser) {
1577                 short index= 0, rl_index= 0, rp_index;
1578                 
1579                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1580                         rp_index= 0;
1581                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1582                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1583                                         break;
1584                         if(rpass)
1585                                 break;
1586                 }
1587                 
1588                 if(rpass)
1589                         iuser->multi_index= index;
1590                 else 
1591                         iuser->multi_index= 0;
1592         }
1593         if(rpass==NULL) {
1594                 rl= rr->layers.first;
1595                 if(rl)
1596                         rpass= rl->passes.first;
1597         }
1598         
1599         return rpass;
1600 }
1601
1602 RenderResult *BKE_image_acquire_renderresult(struct Scene *scene, Image *ima)
1603 {
1604         if(ima->rr)
1605                 return ima->rr;
1606         else if(ima->type==IMA_TYPE_R_RESULT)
1607                 return RE_AcquireResultRead(RE_GetRender(scene->id.name));
1608         return NULL;
1609 }
1610
1611 void BKE_image_release_renderresult(struct Scene *scene, Image *ima)
1612 {
1613         if(ima->rr);
1614         else if(ima->type==IMA_TYPE_R_RESULT)
1615                 RE_ReleaseResult(RE_GetRender(scene->id.name));
1616 }
1617
1618 /* after imbuf load, openexr type can return with a exrhandle open */
1619 /* in that case we have to build a render-result */
1620 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1621 {
1622         
1623         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1624
1625 #ifdef WITH_OPENEXR
1626         IMB_exr_close(ibuf->userdata);
1627 #endif
1628
1629         ibuf->userdata= NULL;
1630         if(ima->rr)
1631                 ima->rr->framenr= framenr;
1632 }
1633
1634 /* common stuff to do with images after loading */
1635 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1636 {
1637         
1638         
1639         /* preview is NULL when it has never been used as an icon before */
1640         if(G.background==0 && ima->preview==NULL)
1641                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1642         
1643         /* stringcodes also in ibuf, ibuf->name is used to retrieve original (buttons) */
1644         BLI_strncpy(ibuf->name, ima->name, FILE_MAX);
1645         
1646         /* fields */
1647         if (ima->flag & IMA_FIELDS) {
1648                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1649                 else de_interlace_ng(ibuf);
1650         }
1651         /* timer */
1652         ima->lastused = clock() / CLOCKS_PER_SEC;
1653         
1654         ima->ok= IMA_OK_LOADED;
1655         
1656 }
1657
1658 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1659 {
1660         struct ImBuf *ibuf;
1661         unsigned short numlen;
1662         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1663         
1664         ima->lastframe= frame;
1665
1666         BLI_stringdec(ima->name, head, tail, &numlen);
1667         BLI_stringenc(ima->name, head, tail, numlen, frame);
1668         BLI_strncpy(name, ima->name, sizeof(name));
1669         
1670         if(ima->id.lib)
1671                 BLI_convertstringcode(name, ima->id.lib->filename);
1672         else
1673                 BLI_convertstringcode(name, G.sce);
1674         
1675         BLI_convertstringframe(name, frame); /* TODO - should this be here? */
1676         
1677         /* read ibuf */
1678         ibuf = IMB_loadiffname(name, IB_rect|IB_multilayer);
1679         if(G.f & G_DEBUG) printf("loaded %s\n", name);
1680         
1681         if (ibuf) {
1682 #ifdef WITH_OPENEXR
1683                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1684                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1685                         image_create_multilayer(ima, ibuf, frame);      
1686                         ima->type= IMA_TYPE_MULTILAYER;
1687                         IMB_freeImBuf(ibuf);
1688                         ibuf= NULL;
1689                 }
1690                 else {
1691                         image_initialize_after_load(ima, ibuf);
1692                         image_assign_ibuf(ima, ibuf, 0, frame);
1693                 }
1694 #else
1695                 image_initialize_after_load(ima, ibuf);
1696                 image_assign_ibuf(ima, ibuf, 0, frame);
1697 #endif
1698                 
1699                 if(ima->flag & IMA_DO_PREMUL)
1700                         converttopremul(ibuf);
1701                 
1702         }
1703         else
1704                 ima->ok= 0;
1705         
1706         if(iuser)
1707                 iuser->ok= ima->ok;
1708         
1709         return ibuf;
1710 }
1711
1712 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1713 {
1714         struct ImBuf *ibuf= NULL;
1715         
1716         /* either we load from RenderResult, or we have to load a new one */
1717         
1718         /* check for new RenderResult */
1719         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1720                 /* copy to survive not found multilayer image */
1721                 RenderResult *oldrr= ima->rr;
1722         
1723                 ima->rr= NULL;
1724                 ibuf = image_load_sequence_file(ima, iuser, frame);
1725                 
1726                 if(ibuf) { /* actually an error */
1727                         ima->type= IMA_TYPE_IMAGE;
1728                         printf("error, multi is normal image\n");
1729                 }
1730                 // printf("loaded new result %p\n", ima->rr);
1731                 /* free result if new one found */
1732                 if(ima->rr) {
1733                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1734                         if(oldrr) RE_FreeRenderResult(oldrr);
1735                 }
1736                 else {
1737                         ima->rr= oldrr;
1738                 }
1739
1740         }
1741         if(ima->rr) {
1742                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1743                 
1744                 if(rpass) {
1745                         // printf("load from pass %s\n", rpass->name);
1746                         /* since we free  render results, we copy the rect */
1747                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1748                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1749                         ibuf->flags |= IB_rectfloat;
1750                         ibuf->mall= IB_rectfloat;
1751                         ibuf->channels= rpass->channels;
1752                         
1753                         image_initialize_after_load(ima, ibuf);
1754                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
1755                         
1756                 }
1757                 // else printf("pass not found\n");
1758         }
1759         else
1760                 ima->ok= 0;
1761         
1762         if(iuser)
1763                 iuser->ok= ima->ok;
1764         
1765         return ibuf;
1766 }
1767
1768
1769 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1770 {
1771         struct ImBuf *ibuf= NULL;
1772         
1773         ima->lastframe= frame;
1774         
1775         if(ima->anim==NULL) {
1776                 char str[FILE_MAX];
1777                 
1778                 BLI_strncpy(str, ima->name, FILE_MAX);
1779                 if(ima->id.lib)
1780                         BLI_convertstringcode(str, ima->id.lib->filename);
1781                 else
1782                         BLI_convertstringcode(str, G.sce);
1783                 
1784                 ima->anim = openanim(str, IB_cmap | IB_rect);
1785                 
1786                 /* let's initialize this user */
1787                 if(ima->anim && iuser && iuser->frames==0)
1788                         iuser->frames= IMB_anim_get_duration(ima->anim);
1789         }
1790         
1791         if(ima->anim) {
1792                 int dur = IMB_anim_get_duration(ima->anim);
1793                 int fra= frame-1;
1794                 
1795                 if(fra<0) fra = 0;
1796                 if(fra>(dur-1)) fra= dur-1;
1797                 ibuf = IMB_anim_absolute(ima->anim, fra);
1798                 
1799                 if(ibuf) {
1800                         image_initialize_after_load(ima, ibuf);
1801                         image_assign_ibuf(ima, ibuf, 0, frame);
1802                 }
1803                 else
1804                         ima->ok= 0;
1805         }
1806         else
1807                 ima->ok= 0;
1808         
1809         if(iuser)
1810                 iuser->ok= ima->ok;
1811         
1812         return ibuf;
1813 }
1814
1815 /* cfra used for # code, Image can only have this # for all its users */
1816 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1817 {
1818         struct ImBuf *ibuf;
1819         char str[FILE_MAX];
1820         int assign = 0;
1821         
1822         /* always ensure clean ima */
1823         image_free_buffers(ima);
1824         
1825         /* is there a PackedFile with this image ? */
1826         if (ima->packedfile) {
1827                 ibuf = IMB_ibImageFromMemory((int *) ima->packedfile->data, ima->packedfile->size, IB_rect|IB_multilayer);
1828         } 
1829         else {
1830                         
1831                 /* get the right string */
1832                 BLI_strncpy(str, ima->name, sizeof(str));
1833                 if(ima->id.lib)
1834                         BLI_convertstringcode(str, ima->id.lib->filename);
1835                 else
1836                         BLI_convertstringcode(str, G.sce);
1837                 
1838                 BLI_convertstringframe(str, cfra);
1839                 
1840                 /* read ibuf */
1841                 ibuf = IMB_loadiffname(str, IB_rect|IB_multilayer|IB_imginfo);
1842         }
1843         
1844         if (ibuf) {
1845                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1846                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1847                         image_create_multilayer(ima, ibuf, cfra);       
1848                         ima->type= IMA_TYPE_MULTILAYER;
1849                         IMB_freeImBuf(ibuf);
1850                         ibuf= NULL;
1851                 }
1852                 else {
1853                         image_initialize_after_load(ima, ibuf);
1854                         assign= 1;
1855
1856                         /* check if the image is a font image... */
1857                         detectBitmapFont(ibuf);
1858                         
1859                         /* make packed file for autopack */
1860                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
1861                                 ima->packedfile = newPackedFile(NULL, str);
1862                 }
1863                 
1864                 if(ima->flag & IMA_DO_PREMUL)
1865                         converttopremul(ibuf);
1866         }
1867         else
1868                 ima->ok= 0;
1869         
1870         if(assign)
1871                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1872
1873         if(iuser)
1874                 iuser->ok= ima->ok;
1875         
1876         return ibuf;
1877 }
1878
1879 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1880 {
1881         ImBuf *ibuf= NULL;
1882         
1883         if(ima->rr==NULL) {
1884                 ibuf = image_load_image_file(ima, iuser, 0);
1885                 if(ibuf) { /* actually an error */
1886                         ima->type= IMA_TYPE_IMAGE;
1887                         return ibuf;
1888                 }
1889         }
1890         if(ima->rr) {
1891                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1892
1893                 if(rpass) {
1894                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1895                         
1896                         image_initialize_after_load(ima, ibuf);
1897                         
1898                         ibuf->rect_float= rpass->rect;
1899                         ibuf->flags |= IB_rectfloat;
1900                         ibuf->channels= rpass->channels;
1901
1902                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1903                 }
1904         }
1905         
1906         if(ibuf==NULL) 
1907                 ima->ok= 0;
1908         if(iuser)
1909                 iuser->ok= ima->ok;
1910         
1911         return ibuf;
1912 }
1913
1914
1915 /* showing RGBA result itself (from compo/sequence) or
1916    like exr, using layers etc */
1917 /* always returns a single ibuf, also during render progress */
1918 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
1919 {
1920         Render *re= NULL;
1921         RenderResult *rr= NULL;
1922         
1923         /* if we the caller is not going to release the lock, don't give the image */
1924         if(!lock_r)
1925                 return NULL;
1926
1927         if(iuser && iuser->scene) {
1928                 re= RE_GetRender(iuser->scene->id.name);
1929                 rr= RE_AcquireResultRead(re);
1930
1931                 /* release is done in BKE_image_release_ibuf using lock_r */
1932                 *lock_r= re;
1933         }
1934
1935         if(rr==NULL)
1936                 return NULL;
1937         
1938         if(RE_RenderInProgress(re)) {
1939                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1940                 
1941                 /* make ibuf if needed, and initialize it */
1942                 /* this only gets called when mutex locked */
1943                 if(ibuf==NULL) {
1944                         ibuf= IMB_allocImBuf(rr->rectx, rr->recty, 32, IB_rect, 0);
1945                         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1946                 }
1947
1948                 return ibuf;
1949         }
1950         else {
1951                 RenderResult rres;
1952                 float *rectf;
1953                 unsigned int *rect;
1954                 float dither;
1955                 int channels, layer, pass;
1956
1957                 channels= 4;
1958                 layer= (iuser)? iuser->layer: 0;
1959                 pass= (iuser)? iuser->pass: 0;
1960                 
1961                 /* this gives active layer, composite or seqence result */
1962                 RE_AcquireResultImage(RE_GetRender(iuser->scene->id.name), &rres);
1963                 rect= (unsigned int *)rres.rect32;
1964                 rectf= rres.rectf;
1965                 dither= iuser->scene->r.dither_intensity;
1966
1967                 /* get compo/seq result by default */
1968                 if(rr->rectf && layer==0);
1969                 else if(rr->layers.first) {
1970                         RenderLayer *rl= BLI_findlink(&rr->layers, layer-(rr->rectf?1:0));
1971                         if(rl) {
1972                                 /* there's no combined pass, is in renderlayer itself */
1973                                 if(pass==0) {
1974                                         rectf= rl->rectf;
1975                                 }
1976                                 else {
1977                                         RenderPass *rpass= BLI_findlink(&rl->passes, pass-1);
1978                                         if(rpass) {
1979                                                 channels= rpass->channels;
1980                                                 rectf= rpass->rect;
1981                                                 dither= 0.0f; /* don't dither passes */
1982                                         }
1983                                 }
1984                         }
1985                 }
1986                 
1987                 if(rectf || rect) {
1988                         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1989
1990                         /* make ibuf if needed, and initialize it */
1991                         if(ibuf==NULL) {
1992                                 ibuf= IMB_allocImBuf(rr->rectx, rr->recty, 32, 0, 0);
1993                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1994                         }
1995                         ibuf->x= rr->rectx;
1996                         ibuf->y= rr->recty;
1997                         
1998                         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
1999                                 imb_freerectImBuf(ibuf);
2000                         if(rect)
2001                                 ibuf->rect= rect;
2002                         
2003                         ibuf->rect_float= rectf;
2004                         ibuf->flags |= IB_rectfloat;
2005                         ibuf->channels= channels;
2006                         ibuf->zbuf_float= rres.rectz;
2007                         ibuf->flags |= IB_zbuffloat;
2008                         ibuf->dither= dither;
2009
2010                         RE_ReleaseResultImage(re);
2011
2012                         ima->ok= IMA_OK_LOADED;
2013                         return ibuf;
2014                 }
2015
2016                 RE_ReleaseResultImage(re);
2017         }
2018         
2019         return NULL;
2020 }
2021
2022 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2023 {
2024         ImBuf *ibuf = NULL;
2025         int frame = 0, index = 0;
2026
2027         /* see if we already have an appropriate ibuf, with image source and type */
2028         if(ima->source==IMA_SRC_MOVIE) {
2029                 frame= iuser?iuser->framenr:ima->lastframe;
2030                 ibuf= image_get_ibuf(ima, 0, frame);
2031         }
2032         else if(ima->source==IMA_SRC_SEQUENCE) {
2033                 if(ima->type==IMA_TYPE_IMAGE) {
2034                         frame= iuser?iuser->framenr:ima->lastframe;
2035                         ibuf= image_get_ibuf(ima, 0, frame);
2036                 }
2037                 else if(ima->type==IMA_TYPE_MULTILAYER) {
2038                         frame= iuser?iuser->framenr:ima->lastframe;
2039                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
2040                         ibuf= image_get_ibuf(ima, index, frame);
2041                 }
2042         }
2043         else if(ima->source==IMA_SRC_FILE) {
2044                 if(ima->type==IMA_TYPE_IMAGE)
2045                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2046                 else if(ima->type==IMA_TYPE_MULTILAYER)
2047                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2048         }
2049         else if(ima->source == IMA_SRC_GENERATED) {
2050                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2051         }
2052         else if(ima->source == IMA_SRC_VIEWER) {
2053                 if(ima->type==IMA_TYPE_R_RESULT) {
2054                         /* always verify entirely, not that this shouldn't happen
2055                          * during render anyway */
2056                 }
2057                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2058                         frame= iuser?iuser->framenr:0;
2059                         ibuf= image_get_ibuf(ima, 0, frame);
2060                 }
2061         }
2062
2063         *frame_r = frame;
2064         *index_r = index;
2065
2066         return ibuf;
2067 }
2068
2069 /* Checks optional ImageUser and verifies/creates ImBuf. */
2070 /* use this one if you want to get a render result in progress,
2071  * if not, use BKE_image_get_ibuf which doesn't require a release */
2072 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2073 {
2074         ImBuf *ibuf= NULL;
2075         float color[] = {0, 0, 0, 1};
2076         int frame= 0, index= 0;
2077
2078         /* This function is intended to be thread-safe. It postpones the mutex lock
2079          * until it needs to load the image, if the image is already there it
2080          * should just get the pointer and return. The reason is that a lot of mutex
2081          * locks appears to be very slow on certain multicore macs, causing a render
2082          * with image textures to actually slow down as more threads are used.
2083          *
2084          * Note that all the image loading functions should also make sure they do
2085          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2086          * That means, the last two steps must be, 1) add the ibuf to the list and
2087          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2088         
2089         if(lock_r)
2090                 *lock_r= NULL;
2091
2092         /* quick reject tests */
2093         if(ima==NULL) 
2094                 return NULL;
2095         if(iuser) {
2096                 if(iuser->ok==0)
2097                         return NULL;
2098         }
2099         else if(ima->ok==0)
2100                 return NULL;
2101         
2102         /* try to get the ibuf without locking */
2103         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2104
2105         if(ibuf == NULL) {
2106                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2107                  * load the image */
2108                 BLI_lock_thread(LOCK_IMAGE);
2109
2110                 /* need to check ok flag and loading ibuf again, because the situation
2111                  * might have changed in the meantime */
2112                 if(iuser) {
2113                         if(iuser->ok==0) {
2114                                 BLI_unlock_thread(LOCK_IMAGE);
2115                                 return NULL;
2116                         }
2117                 }
2118                 else if(ima->ok==0) {
2119                         BLI_unlock_thread(LOCK_IMAGE);
2120                         return NULL;
2121                 }
2122
2123                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2124
2125                 if(ibuf == NULL) {
2126                         /* we are sure we have to load the ibuf, using source and type */
2127                         if(ima->source==IMA_SRC_MOVIE) {
2128                                 /* source is from single file, use flipbook to store ibuf */
2129                                 ibuf= image_load_movie_file(ima, iuser, frame);
2130                         }
2131                         else if(ima->source==IMA_SRC_SEQUENCE) {
2132                                 if(ima->type==IMA_TYPE_IMAGE) {
2133                                         /* regular files, ibufs in flipbook, allows saving */
2134                                         ibuf= image_load_sequence_file(ima, iuser, frame);
2135                                 }
2136                                 /* no else; on load the ima type can change */
2137                                 if(ima->type==IMA_TYPE_MULTILAYER) {
2138                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2139                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
2140                                 }
2141
2142                                 if(ibuf)
2143                                         BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
2144                         }
2145                         else if(ima->source==IMA_SRC_FILE) {
2146                                 
2147                                 if(ima->type==IMA_TYPE_IMAGE)
2148                                         ibuf= image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */
2149                                 /* no else; on load the ima type can change */
2150                                 if(ima->type==IMA_TYPE_MULTILAYER)
2151                                         /* keeps render result, stores ibufs in listbase, allows saving */
2152                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
2153                                         
2154                         }
2155                         else if(ima->source == IMA_SRC_GENERATED) {
2156                                 /* generated is: ibuf is allocated dynamically */
2157                                 /* UV testgrid or black or solid etc */
2158                                 if(ima->gen_x==0) ima->gen_x= 1024;
2159                                 if(ima->gen_y==0) ima->gen_y= 1024;
2160                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 0, ima->gen_type, color);
2161                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2162                                 ima->ok= IMA_OK_LOADED;
2163                         }
2164                         else if(ima->source == IMA_SRC_VIEWER) {
2165                                 if(ima->type==IMA_TYPE_R_RESULT) {
2166                                         /* always verify entirely, and potentially
2167                                            returns pointer to release later */
2168                                         ibuf= image_get_render_result(ima, iuser, lock_r);
2169                                 }
2170                                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2171                                         /* Composite Viewer, all handled in compositor */
2172                                         /* fake ibuf, will be filled in compositor */
2173                                         ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
2174                                         image_assign_ibuf(ima, ibuf, 0, frame);
2175                                 }
2176                         }
2177                 }
2178
2179                 BLI_unlock_thread(LOCK_IMAGE);
2180         }
2181
2182         /* we assuming that if it is not rendering, it's also not multithreaded
2183          * (a somewhat weak assumption) */
2184         if(G.rendering==0)
2185                 tag_image_time(ima);
2186
2187         return ibuf;
2188 }
2189
2190 void BKE_image_release_ibuf(Image *ima, void *lock)
2191 {
2192         /* for getting image during threaded render, need to release */
2193         if(lock)
2194                 RE_ReleaseResult(lock);
2195 }
2196
2197 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2198 {
2199         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2200 }
2201
2202 void BKE_image_user_calc_imanr(ImageUser *iuser, int cfra, int fieldnr)
2203 {
2204         int imanr, len;
2205         
2206         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2207         len= (iuser->fie_ima*iuser->frames)/2;
2208         
2209         if(len==0) {
2210                 iuser->framenr= 0;
2211         }
2212         else {
2213                 cfra= cfra - iuser->sfra+1;
2214                 
2215                 /* cyclic */
2216                 if(iuser->cycl) {
2217                         cfra= ( (cfra) % len );
2218                         if(cfra < 0) cfra+= len;
2219                         if(cfra==0) cfra= len;
2220                 }
2221                 
2222                 if(cfra<1) cfra= 1;
2223                 else if(cfra>len) cfra= len;
2224                 
2225                 /* convert current frame to current field */
2226                 cfra= 2*(cfra);
2227                 if(fieldnr) cfra++;
2228                 
2229                 /* transform to images space */
2230                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2231                 if(imanr>iuser->frames) imanr= iuser->frames;
2232                 imanr+= iuser->offset;
2233                 
2234                 if(iuser->cycl) {
2235                         imanr= ( (imanr) % len );
2236                         while(imanr < 0) imanr+= len;
2237                         if(imanr==0) imanr= len;
2238                 }
2239         
2240                 /* allows image users to handle redraws */
2241                 if(iuser->flag & IMA_ANIM_ALWAYS)
2242                         if(imanr!=iuser->framenr)
2243                                 iuser->flag |= IMA_ANIM_REFRESHED;
2244                 
2245                 iuser->framenr= imanr;
2246                 if(iuser->ok==0) iuser->ok= 1;
2247         }
2248 }
2249
2250 /*
2251   Produce image export path.
2252
2253   Fails returning 0 if image filename is empty or if destination path
2254   matches image path (i.e. both are the same file).
2255
2256   Trailing slash in dest_dir is optional.
2257
2258   Logic:
2259
2260   - if an image is "below" current .blend file directory, rebuild the
2261     same dir structure in dest_dir
2262
2263   For example //textures/foo/bar.png becomes
2264   [dest_dir]/textures/foo/bar.png.
2265
2266   - if an image is not "below" current .blend file directory,
2267   disregard it's path and copy it in the same directory where 3D file
2268   goes.
2269
2270   For example //../foo/bar.png becomes [dest_dir]/bar.png.
2271
2272   This logic will help ensure that all image paths are relative and
2273   that a user gets his images in one place. It'll also provide
2274   consistent behaviour across exporters.
2275  */
2276 int BKE_get_image_export_path(struct Image *im, const char *dest_dir, char *abs, int abs_size, char *rel, int rel_size)
2277 {
2278         char path[FILE_MAX];
2279         char dir[FILE_MAX];
2280         char base[FILE_MAX];
2281         char blend_dir[FILE_MAX];       /* directory, where current .blend file resides */
2282         char dest_path[FILE_MAX];
2283         char rel_dir[FILE_MAX];
2284         int len;
2285
2286         if (abs)
2287                 abs[0]= 0;
2288
2289         if (rel)
2290                 rel[0]= 0;
2291
2292         BLI_split_dirfile_basic(G.sce, blend_dir, NULL);
2293
2294         if (!strlen(im->name)) {
2295                 if (G.f & G_DEBUG) printf("Invalid image type.\n");
2296                 return 0;
2297         }
2298
2299         BLI_strncpy(path, im->name, sizeof(path));
2300
2301         /* expand "//" in filename and get absolute path */
2302         BLI_convertstringcode(path, G.sce);
2303
2304         /* get the directory part */
2305         BLI_split_dirfile_basic(path, dir, base);
2306
2307         len= strlen(blend_dir);
2308
2309         rel_dir[0] = 0;
2310
2311         /* if image is "below" current .blend file directory */
2312         if (!strncmp(path, blend_dir, len)) {
2313
2314                 /* if image is _in_ current .blend file directory */
2315                 if (!strcmp(dir, blend_dir)) {
2316                         BLI_join_dirfile(dest_path, dest_dir, base);
2317                 }
2318                 /* "below" */
2319                 else {
2320                         /* rel = image_path_dir - blend_dir */
2321                         BLI_strncpy(rel_dir, dir + len, sizeof(rel_dir));
2322
2323                         BLI_join_dirfile(dest_path, dest_dir, rel_dir);
2324                         BLI_join_dirfile(dest_path, dest_path, base);
2325                 }
2326                         
2327         }
2328         /* image is out of current directory */
2329         else {
2330                 BLI_join_dirfile(dest_path, dest_dir, base);
2331         }
2332
2333         if (abs)
2334                 BLI_strncpy(abs, dest_path, abs_size);
2335
2336         if (rel) {
2337                 strncat(rel, rel_dir, rel_size);
2338                 strncat(rel, base, rel_size);
2339         }
2340
2341         /* return 2 if src=dest */
2342         if (!strcmp(path, dest_path)) {
2343                 if (G.f & G_DEBUG) printf("%s and %s are the same file\n", path, dest_path);
2344                 return 2;
2345         }
2346
2347         return 1;
2348 }
2349