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