fix [#29459] Crash making a linked object group local
[blender.git] / source / blender / blenkernel / intern / image.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, 2006, full recode
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/image.c
27  *  \ingroup bke
28  */
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 #ifdef _WIN32
44 #define open _open
45 #define close _close
46 #endif
47
48 #include "MEM_guardedalloc.h"
49
50 #include "IMB_imbuf_types.h"
51 #include "IMB_imbuf.h"
52
53 #ifdef WITH_OPENEXR
54 #include "intern/openexr/openexr_multi.h"
55 #endif
56
57 #include "DNA_packedFile_types.h"
58 #include "DNA_scene_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_camera_types.h"
61 #include "DNA_sequence_types.h"
62 #include "DNA_userdef_types.h"
63 #include "DNA_brush_types.h"
64 #include "DNA_mesh_types.h"
65 #include "DNA_meshdata_types.h"
66
67 #include "BLI_blenlib.h"
68 #include "BLI_threads.h"
69 #include "BLI_utildefines.h"
70 #include "BLI_bpath.h"
71
72 #include "BKE_bmfont.h"
73 #include "BKE_global.h"
74 #include "BKE_icons.h"
75 #include "BKE_image.h"
76 #include "BKE_library.h"
77 #include "BKE_main.h"
78 #include "BKE_packedFile.h"
79 #include "BKE_scene.h"
80 #include "BKE_node.h"
81 #include "BKE_sequencer.h" /* seq_foreground_frame_get() */
82 #include "BKE_utildefines.h"
83
84 #include "BLF_api.h"
85
86 #include "PIL_time.h"
87
88 #include "RE_pipeline.h"
89
90 #include "GPU_draw.h"
91
92 #include "BLO_sys_types.h" // for intptr_t support
93
94 /* max int, to indicate we don't store sequences in ibuf */
95 #define IMA_NO_INDEX    0x7FEFEFEF
96
97 /* quick lookup: supports 1 million frames, thousand passes */
98 #define IMA_MAKE_INDEX(frame, index)    ((frame)<<10)+index
99 #define IMA_INDEX_FRAME(index)                  (index>>10)
100 #define IMA_INDEX_PASS(index)                   (index & ~1023)
101
102 /* ******** IMAGE PROCESSING ************* */
103
104 static void de_interlace_ng(struct ImBuf *ibuf) /* neogeo fields */
105 {
106         struct ImBuf * tbuf1, * tbuf2;
107         
108         if (ibuf == NULL) return;
109         if (ibuf->flags & IB_fields) return;
110         ibuf->flags |= IB_fields;
111         
112         if (ibuf->rect) {
113                 /* make copies */
114                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
115                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
116                 
117                 ibuf->x *= 2;
118                 
119                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
120                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
121                 
122                 ibuf->x /= 2;
123                 IMB_rectcpy(ibuf, tbuf1, 0, 0, 0, 0, tbuf1->x, tbuf1->y);
124                 IMB_rectcpy(ibuf, tbuf2, 0, tbuf2->y, 0, 0, tbuf2->x, tbuf2->y);
125                 
126                 IMB_freeImBuf(tbuf1);
127                 IMB_freeImBuf(tbuf2);
128         }
129         ibuf->y /= 2;
130 }
131
132 static void de_interlace_st(struct ImBuf *ibuf) /* standard fields */
133 {
134         struct ImBuf * tbuf1, * tbuf2;
135         
136         if (ibuf == NULL) return;
137         if (ibuf->flags & IB_fields) return;
138         ibuf->flags |= IB_fields;
139         
140         if (ibuf->rect) {
141                 /* make copies */
142                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect);
143                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect);
144                 
145                 ibuf->x *= 2;
146                 
147                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
148                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
149                 
150                 ibuf->x /= 2;
151                 IMB_rectcpy(ibuf, tbuf2, 0, 0, 0, 0, tbuf2->x, tbuf2->y);
152                 IMB_rectcpy(ibuf, tbuf1, 0, tbuf2->y, 0, 0, tbuf1->x, tbuf1->y);
153                 
154                 IMB_freeImBuf(tbuf1);
155                 IMB_freeImBuf(tbuf2);
156         }
157         ibuf->y /= 2;
158 }
159
160 void image_de_interlace(Image *ima, int odd)
161 {
162         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
163         if(ibuf) {
164                 if(odd)
165                         de_interlace_st(ibuf);
166                 else
167                         de_interlace_ng(ibuf);
168         }
169 }
170
171 /* ***************** ALLOC & FREE, DATA MANAGING *************** */
172
173 static void image_free_buffers(Image *ima)
174 {
175         ImBuf *ibuf;
176         
177         while((ibuf = ima->ibufs.first)) {
178                 BLI_remlink(&ima->ibufs, ibuf);
179                 
180                 if (ibuf->userdata) {
181                         MEM_freeN(ibuf->userdata);
182                         ibuf->userdata = NULL;
183                 }
184                 IMB_freeImBuf(ibuf);
185         }
186         
187         if(ima->anim) IMB_free_anim(ima->anim);
188         ima->anim= NULL;
189
190         if(ima->rr) {
191                 RE_FreeRenderResult(ima->rr);
192                 ima->rr= NULL;
193         }       
194         
195         GPU_free_image(ima);
196         
197         ima->ok= IMA_OK;
198 }
199
200 /* called by library too, do not free ima itself */
201 void free_image(Image *ima)
202 {
203         int a;
204
205         image_free_buffers(ima);
206         if (ima->packedfile) {
207                 freePackedFile(ima->packedfile);
208                 ima->packedfile = NULL;
209         }
210         BKE_icon_delete(&ima->id);
211         ima->id.icon_id = 0;
212
213         BKE_previewimg_free(&ima->preview);
214
215         for(a=0; a<IMA_MAX_RENDER_SLOT; a++) {
216                 if(ima->renders[a]) {
217                         RE_FreeRenderResult(ima->renders[a]);
218                         ima->renders[a]= NULL;
219                 }
220         }
221 }
222
223 /* only image block itself */
224 static Image *image_alloc(const char *name, short source, short type)
225 {
226         Image *ima;
227         
228         ima= alloc_libblock(&G.main->image, ID_IM, name);
229         if(ima) {
230                 ima->ok= IMA_OK;
231                 
232                 ima->xrep= ima->yrep= 1;
233                 ima->aspx= ima->aspy= 1.0;
234                 ima->gen_x= 1024; ima->gen_y= 1024;
235                 ima->gen_type= 1;       /* no defines yet? */
236                 
237                 ima->source= source;
238                 ima->type= type;
239         }
240         return ima;
241 }
242
243 /* get the ibuf from an image cache, local use here only */
244 static ImBuf *image_get_ibuf(Image *ima, int index, int frame)
245 {
246         /* this function is intended to be thread safe. with IMA_NO_INDEX this
247          * should be OK, but when iterating over the list this is more tricky
248          * */
249         if(index==IMA_NO_INDEX)
250                 return ima->ibufs.first;
251         else {
252                 ImBuf *ibuf;
253
254                 index= IMA_MAKE_INDEX(frame, index);
255                 for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next)
256                         if(ibuf->index==index)
257                                 return ibuf;
258
259                 return NULL;
260         }
261 }
262
263 /* no ima->ibuf anymore, but listbase */
264 static void image_remove_ibuf(Image *ima, ImBuf *ibuf)
265 {
266         if(ibuf) {
267                 BLI_remlink(&ima->ibufs, ibuf);
268                 IMB_freeImBuf(ibuf);
269         }
270 }
271
272
273 /* no ima->ibuf anymore, but listbase */
274 static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
275 {
276         if(ibuf) {
277                 ImBuf *link;
278                 
279                 if(index!=IMA_NO_INDEX)
280                         index= IMA_MAKE_INDEX(frame, index);
281                 
282                 /* insert based on index */
283                 for(link= ima->ibufs.first; link; link= link->next)
284                         if(link->index>=index)
285                                 break;
286
287                 ibuf->index= index;
288
289                 /* this function accepts link==NULL */
290                 BLI_insertlinkbefore(&ima->ibufs, link, ibuf);
291
292                 /* now we don't want copies? */
293                 if(link && ibuf->index==link->index)
294                         image_remove_ibuf(ima, link);
295         }
296 }
297
298 /* empty image block, of similar type and filename */
299 Image *copy_image(Image *ima)
300 {
301         Image *nima= image_alloc(ima->id.name+2, ima->source, ima->type);
302
303         BLI_strncpy(nima->name, ima->name, sizeof(ima->name));
304
305         nima->flag= ima->flag;
306         nima->tpageflag= ima->tpageflag;
307         
308         nima->gen_x= ima->gen_x;
309         nima->gen_y= ima->gen_y;
310         nima->gen_type= ima->gen_type;
311
312         nima->animspeed= ima->animspeed;
313
314         nima->aspx= ima->aspx;
315         nima->aspy= ima->aspy;
316
317         return nima;
318 }
319
320 static void extern_local_image(Image *UNUSED(ima))
321 {
322         /* Nothing to do: images don't link to other IDs. This function exists to
323            match id_make_local pattern. */
324 }
325
326 void make_local_image(struct Image *ima)
327 {
328         Main *bmain= G.main;
329         Tex *tex;
330         Brush *brush;
331         Mesh *me;
332         int is_local= FALSE, is_lib= FALSE;
333
334         /* - only lib users: do nothing
335          * - only local users: set flag
336          * - mixed: make copy
337          */
338
339         if(ima->id.lib==NULL) return;
340
341         /* Can't take short cut here: must check meshes at least because of bogus
342            texface ID refs. - z0r */
343 #if 0
344         if(ima->id.us==1) {
345                 id_clear_lib_data(bmain, &ima->id);
346                 extern_local_image(ima);
347                 return;
348         }
349 #endif
350
351         for(tex= bmain->tex.first; tex; tex= tex->id.next) {
352                 if(tex->ima == ima) {
353                         if(tex->id.lib) is_lib= TRUE;
354                         else is_local= TRUE;
355                 }
356         }
357         for(brush= bmain->brush.first; brush; brush= brush->id.next) {
358                 if(brush->clone.image == ima) {
359                         if(brush->id.lib) is_lib= TRUE;
360                         else is_local= TRUE;
361                 }
362         }
363         for(me= bmain->mesh.first; me; me= me->id.next) {
364                 if(me->mtface) {
365                         MTFace *tface;
366                         int a, i;
367
368                         for(i=0; i<me->fdata.totlayer; i++) {
369                                 if(me->fdata.layers[i].type == CD_MTFACE) {
370                                         tface= (MTFace*)me->fdata.layers[i].data;
371
372                                         for(a=0; a<me->totface; a++, tface++) {
373                                                 if(tface->tpage == ima) {
374                                                         if(me->id.lib) is_lib= TRUE;
375                                                         else is_local= TRUE;
376                                                 }
377                                         }
378                                 }
379                         }
380                 }
381         }
382
383         if(is_local && is_lib == FALSE) {
384                 id_clear_lib_data(bmain, &ima->id);
385                 extern_local_image(ima);
386         }
387         else if(is_local && is_lib) {
388                 Image *ima_new= copy_image(ima);
389
390                 ima_new->id.us= 0;
391
392                 /* Remap paths of new ID using old library as base. */
393                 BKE_id_lib_local_paths(bmain, ima->id.lib, &ima_new->id);
394
395                 tex= bmain->tex.first;
396                 while(tex) {
397                         if(tex->id.lib==NULL) {
398                                 if(tex->ima==ima) {
399                                         tex->ima = ima_new;
400                                         ima_new->id.us++;
401                                         ima->id.us--;
402                                 }
403                         }
404                         tex= tex->id.next;
405                 }
406                 brush= bmain->brush.first;
407                 while(brush) {
408                         if(brush->id.lib==NULL) {
409                                 if(brush->clone.image==ima) {
410                                         brush->clone.image = ima_new;
411                                         ima_new->id.us++;
412                                         ima->id.us--;
413                                 }
414                         }
415                         brush= brush->id.next;
416                 }
417                 /* Transfer references in texfaces. Texfaces don't add to image ID
418                    user count *unless* there are no other users. See
419                    readfile.c:lib_link_mtface. */
420                 me= bmain->mesh.first;
421                 while(me) {
422                         if(me->mtface) {
423                                 MTFace *tface;
424                                 int a, i;
425
426                                 for(i=0; i<me->fdata.totlayer; i++) {
427                                         if(me->fdata.layers[i].type == CD_MTFACE) {
428                                                 tface= (MTFace*)me->fdata.layers[i].data;
429
430                                                 for(a=0; a<me->totface; a++, tface++) { 
431                                                         if(tface->tpage == ima) {
432                                                                 tface->tpage = ima_new;
433                                                                 if(ima_new->id.us == 0) {
434                                                                         tface->tpage->id.us= 1;
435                                                                 }
436                                                                 id_lib_extern((ID*)ima_new);
437                                                         }
438                                                 }
439                                         }
440                                 }
441                         }
442                         me= me->id.next;
443                 }
444         }
445 }
446
447 void BKE_image_merge(Image *dest, Image *source)
448 {
449         ImBuf *ibuf;
450         
451         /* sanity check */
452         if(dest && source && dest!=source) {
453         
454                 while((ibuf= source->ibufs.first)) {
455                         BLI_remlink(&source->ibufs, ibuf);
456                         image_assign_ibuf(dest, ibuf, IMA_INDEX_PASS(ibuf->index), IMA_INDEX_FRAME(ibuf->index));
457                 }
458                 
459                 free_libblock(&G.main->image, source);
460         }
461 }
462
463
464 /* checks if image was already loaded, then returns same image */
465 /* otherwise creates new. */
466 /* does not load ibuf itself */
467 /* pass on optional frame for #name images */
468 Image *BKE_add_image_file(const char *name)
469 {
470         Image *ima;
471         int file, len;
472         const char *libname;
473         char str[FILE_MAX], strtest[FILE_MAX];
474         
475         BLI_strncpy(str, name, sizeof(str));
476         BLI_path_abs(str, G.main->name);
477         
478         /* exists? */
479         file= open(str, O_BINARY|O_RDONLY);
480         if(file== -1) return NULL;
481         close(file);
482         
483         /* first search an identical image */
484         for(ima= G.main->image.first; ima; ima= ima->id.next) {
485                 if(ima->source!=IMA_SRC_VIEWER && ima->source!=IMA_SRC_GENERATED) {
486                         BLI_strncpy(strtest, ima->name, sizeof(ima->name));
487                         BLI_path_abs(strtest, G.main->name);
488                         
489                         if( strcmp(strtest, str)==0 ) {
490                                 if(ima->anim==NULL || ima->id.us==0) {
491                                         BLI_strncpy(ima->name, name, sizeof(ima->name));        /* for stringcode */
492                                         ima->id.us++;                                                                           /* officially should not, it doesn't link here! */
493                                         if(ima->ok==0)
494                                                 ima->ok= IMA_OK;
495                         /* RETURN! */
496                                         return ima;
497                                 }
498                         }
499                 }
500         }
501         /* add new image */
502         
503         /* create a short library name */
504         len= strlen(name);
505         
506         while (len > 0 && name[len - 1] != '/' && name[len - 1] != '\\') len--;
507         libname= name+len;
508         
509         ima= image_alloc(libname, IMA_SRC_FILE, IMA_TYPE_IMAGE);
510         BLI_strncpy(ima->name, name, sizeof(ima->name));
511         
512         if(BLI_testextensie_array(name, imb_ext_movie))
513                 ima->source= IMA_SRC_MOVIE;
514         
515         return ima;
516 }
517
518 static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
519 {
520         ImBuf *ibuf;
521         unsigned char *rect= NULL;
522         float *rect_float= NULL;
523         
524         if (floatbuf) {
525                 ibuf= IMB_allocImBuf(width, height, depth, IB_rectfloat);
526                 rect_float= (float*)ibuf->rect_float;
527         }
528         else {
529                 ibuf= IMB_allocImBuf(width, height, depth, IB_rect);
530                 rect= (unsigned char*)ibuf->rect;
531         }
532         
533         BLI_strncpy(ibuf->name, name, sizeof(ibuf->name));
534         ibuf->userflags |= IB_BITMAPDIRTY;
535         
536         switch(uvtestgrid) {
537         case 1:
538                 BKE_image_buf_fill_checker(rect, rect_float, width, height);
539                 break;
540         case 2:
541                 BKE_image_buf_fill_checker_color(rect, rect_float, width, height);
542                 break;
543         default:
544                 BKE_image_buf_fill_color(rect, rect_float, width, height, color);
545         }
546
547         return ibuf;
548 }
549
550 /* adds new image block, creates ImBuf and initializes color */
551 Image *BKE_add_image_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
552 {
553         /* on save, type is changed to FILE in editsima.c */
554         Image *ima= image_alloc(name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
555         
556         if (ima) {
557                 ImBuf *ibuf;
558                 
559                 /* BLI_strncpy(ima->name, name, FILE_MAX); */ /* dont do this, this writes in ain invalid filepath! */
560                 ima->gen_x= width;
561                 ima->gen_y= height;
562                 ima->gen_type= uvtestgrid;
563                 ima->gen_flag |= (floatbuf ? IMA_GEN_FLOAT : 0);
564                 
565                 ibuf= add_ibuf_size(width, height, ima->name, depth, floatbuf, uvtestgrid, color);
566                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
567                 
568                 ima->ok= IMA_OK_LOADED;
569         }
570
571         return ima;
572 }
573
574 /* creates an image image owns the imbuf passed */
575 Image *BKE_add_image_imbuf(ImBuf *ibuf)
576 {
577         /* on save, type is changed to FILE in editsima.c */
578         Image *ima;
579
580         ima= image_alloc(BLI_path_basename(ibuf->name), IMA_SRC_FILE, IMA_TYPE_IMAGE);
581
582         if (ima) {
583                 BLI_strncpy(ima->name, ibuf->name, FILE_MAX);
584                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
585                 ima->ok= IMA_OK_LOADED;
586         }
587
588         return ima;
589 }
590
591 /* packs rect from memory as PNG */
592 void BKE_image_memorypack(Image *ima)
593 {
594         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
595         
596         if(ibuf==NULL)
597                 return;
598         if (ima->packedfile) {
599                 freePackedFile(ima->packedfile);
600                 ima->packedfile = NULL;
601         }
602         
603         ibuf->ftype= PNG;
604         ibuf->planes= R_IMF_PLANES_RGBA;
605         
606         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
607         if(ibuf->encodedbuffer==NULL) {
608                 printf("memory save for pack error\n");
609         }
610         else {
611                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
612                 
613                 pf->data = ibuf->encodedbuffer;
614                 pf->size = ibuf->encodedsize;
615                 ima->packedfile= pf;
616                 ibuf->encodedbuffer= NULL;
617                 ibuf->encodedsize= 0;
618                 ibuf->userflags &= ~IB_BITMAPDIRTY;
619                 
620                 if(ima->source==IMA_SRC_GENERATED) {
621                         ima->source= IMA_SRC_FILE;
622                         ima->type= IMA_TYPE_IMAGE;
623                 }
624         }
625 }
626
627 void tag_image_time(Image *ima)
628 {
629         if (ima)
630                 ima->lastused = (int)PIL_check_seconds_timer();
631 }
632
633 #if 0
634 static void tag_all_images_time() 
635 {
636         Image *ima;
637         int ctime = (int)PIL_check_seconds_timer();
638
639         ima= G.main->image.first;
640         while(ima) {
641                 if(ima->bindcode || ima->repbind || ima->ibufs.first) {
642                         ima->lastused = ctime;
643                 }
644         }
645 }
646 #endif
647
648 void free_old_images(void)
649 {
650         Image *ima;
651         static int lasttime = 0;
652         int ctime = (int)PIL_check_seconds_timer();
653         
654         /* 
655            Run garbage collector once for every collecting period of time 
656            if textimeout is 0, that's the option to NOT run the collector
657         */
658         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
659                 return;
660
661         /* of course not! */
662         if (G.rendering)
663                 return;
664         
665         lasttime = ctime;
666
667         ima= G.main->image.first;
668         while(ima) {
669                 if((ima->flag & IMA_NOCOLLECT)==0 && ctime - ima->lastused > U.textimeout) {
670                         /*
671                            If it's in GL memory, deallocate and set time tag to current time
672                            This gives textures a "second chance" to be used before dying.
673                         */
674                         if(ima->bindcode || ima->repbind) {
675                                 GPU_free_image(ima);
676                                 ima->lastused = ctime;
677                         }
678                         /* Otherwise, just kill the buffers */
679                         else if (ima->ibufs.first) {
680                                 image_free_buffers(ima);
681                         }
682                 }
683                 ima = ima->id.next;
684         }
685 }
686
687 static uintptr_t image_mem_size(Image *ima)
688 {
689         ImBuf *ibuf, *ibufm;
690         int level;
691         uintptr_t size = 0;
692
693         size= 0;
694         
695         /* viewers have memory depending on other rules, has no valid rect pointer */
696         if(ima->source==IMA_SRC_VIEWER)
697                 return 0;
698         
699         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
700                 if(ibuf->rect) size += MEM_allocN_len(ibuf->rect);
701                 else if(ibuf->rect_float) size += MEM_allocN_len(ibuf->rect_float);
702
703                 for(level=0; level<IB_MIPMAP_LEVELS; level++) {
704                         ibufm= ibuf->mipmap[level];
705                         if(ibufm) {
706                                 if(ibufm->rect) size += MEM_allocN_len(ibufm->rect);
707                                 else if(ibufm->rect_float) size += MEM_allocN_len(ibufm->rect_float);
708                         }
709                 }
710         }
711
712         return size;
713 }
714
715 void BKE_image_print_memlist(void)
716 {
717         Image *ima;
718         uintptr_t size, totsize= 0;
719
720         for(ima= G.main->image.first; ima; ima= ima->id.next)
721                 totsize += image_mem_size(ima);
722
723         printf("\ntotal image memory len: %.3f MB\n", (double)totsize/(double)(1024*1024));
724
725         for(ima= G.main->image.first; ima; ima= ima->id.next) {
726                 size= image_mem_size(ima);
727
728                 if(size)
729                         printf("%s len: %.3f MB\n", ima->id.name+2, (double)size/(double)(1024*1024));
730         }
731 }
732
733 void BKE_image_free_all_textures(void)
734 {
735         Tex *tex;
736         Image *ima;
737         /* unsigned int totsize= 0; */
738         
739         for(ima= G.main->image.first; ima; ima= ima->id.next)
740                 ima->id.flag &= ~LIB_DOIT;
741         
742         for(tex= G.main->tex.first; tex; tex= tex->id.next)
743                 if(tex->ima)
744                         tex->ima->id.flag |= LIB_DOIT;
745         
746         for(ima= G.main->image.first; ima; ima= ima->id.next) {
747                 if(ima->ibufs.first && (ima->id.flag & LIB_DOIT)) {
748                         ImBuf *ibuf;
749                         
750                         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
751                                 /* escape when image is painted on */
752                                 if(ibuf->userflags & IB_BITMAPDIRTY)
753                                         break;
754                                 
755                                 /* if(ibuf->mipmap[0]) 
756                                         totsize+= 1.33*ibuf->x*ibuf->y*4;
757                                 else
758                                         totsize+= ibuf->x*ibuf->y*4;*/
759                                 
760                         }
761                         if(ibuf==NULL)
762                                 image_free_buffers(ima);
763                 }
764         }
765         /* printf("freed total %d MB\n", totsize/(1024*1024)); */
766 }
767
768 /* except_frame is weak, only works for seqs without offset... */
769 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
770 {
771         ImBuf *ibuf, *nbuf;
772
773         for(ibuf= ima->ibufs.first; ibuf; ibuf= nbuf) {
774                 nbuf= ibuf->next;
775                 if(ibuf->userflags & IB_BITMAPDIRTY)
776                         continue;
777                 if(ibuf->index==IMA_NO_INDEX)
778                         continue;
779                 if(except_frame!=IMA_INDEX_FRAME(ibuf->index)) {
780                         BLI_remlink(&ima->ibufs, ibuf);
781                         
782                         if (ibuf->userdata) {
783                                 MEM_freeN(ibuf->userdata);
784                                 ibuf->userdata = NULL;
785                         }
786                         IMB_freeImBuf(ibuf);
787                 }                                       
788         }
789 }
790
791 void BKE_image_all_free_anim_ibufs(int cfra)
792 {
793         Image *ima;
794         
795         for(ima= G.main->image.first; ima; ima= ima->id.next)
796                 if(ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE))
797                         BKE_image_free_anim_ibufs(ima, cfra);
798 }
799
800
801 /* *********** READ AND WRITE ************** */
802
803 int BKE_imtype_to_ftype(const char imtype)
804 {
805         if(imtype==R_IMF_IMTYPE_TARGA)
806                 return TGA;
807         else if(imtype==R_IMF_IMTYPE_RAWTGA)
808                 return RAWTGA;
809         else if(imtype== R_IMF_IMTYPE_IRIS) 
810                 return IMAGIC;
811 #ifdef WITH_HDR
812         else if (imtype==R_IMF_IMTYPE_RADHDR)
813                 return RADHDR;
814 #endif
815         else if (imtype==R_IMF_IMTYPE_PNG)
816                 return PNG;
817 #ifdef WITH_DDS
818         else if (imtype==R_IMF_IMTYPE_DDS)
819                 return DDS;
820 #endif
821         else if (imtype==R_IMF_IMTYPE_BMP)
822                 return BMP;
823 #ifdef WITH_TIFF
824         else if (imtype==R_IMF_IMTYPE_TIFF)
825                 return TIF;
826 #endif
827         else if (imtype==R_IMF_IMTYPE_OPENEXR || imtype==R_IMF_IMTYPE_MULTILAYER)
828                 return OPENEXR;
829 #ifdef WITH_CINEON
830         else if (imtype==R_IMF_IMTYPE_CINEON)
831                 return CINEON;
832         else if (imtype==R_IMF_IMTYPE_DPX)
833                 return DPX;
834 #endif
835 #ifdef WITH_OPENJPEG
836         else if(imtype==R_IMF_IMTYPE_JP2)
837                 return JP2;
838 #endif
839         else
840                 return JPG|90;
841 }
842
843 char BKE_ftype_to_imtype(const int ftype)
844 {
845         if(ftype==0)
846                 return R_IMF_IMTYPE_TARGA;
847         else if(ftype == IMAGIC) 
848                 return R_IMF_IMTYPE_IRIS;
849 #ifdef WITH_HDR
850         else if (ftype & RADHDR)
851                 return R_IMF_IMTYPE_RADHDR;
852 #endif
853         else if (ftype & PNG)
854                 return R_IMF_IMTYPE_PNG;
855 #ifdef WITH_DDS
856         else if (ftype & DDS)
857                 return R_IMF_IMTYPE_DDS;
858 #endif
859         else if (ftype & BMP)
860                 return R_IMF_IMTYPE_BMP;
861 #ifdef WITH_TIFF
862         else if (ftype & TIF)
863                 return R_IMF_IMTYPE_TIFF;
864 #endif
865         else if (ftype & OPENEXR)
866                 return R_IMF_IMTYPE_OPENEXR;
867 #ifdef WITH_CINEON
868         else if (ftype & CINEON)
869                 return R_IMF_IMTYPE_CINEON;
870         else if (ftype & DPX)
871                 return R_IMF_IMTYPE_DPX;
872 #endif
873         else if (ftype & TGA)
874                 return R_IMF_IMTYPE_TARGA;
875         else if(ftype & RAWTGA)
876                 return R_IMF_IMTYPE_RAWTGA;
877 #ifdef WITH_OPENJPEG
878         else if(ftype & JP2)
879                 return R_IMF_IMTYPE_JP2;
880 #endif
881         else
882                 return R_IMF_IMTYPE_JPEG90;
883 }
884
885
886 int BKE_imtype_is_movie(const char imtype)
887 {
888         switch(imtype) {
889         case R_IMF_IMTYPE_AVIRAW:
890         case R_IMF_IMTYPE_AVIJPEG:
891         case R_IMF_IMTYPE_AVICODEC:
892         case R_IMF_IMTYPE_QUICKTIME:
893         case R_IMF_IMTYPE_FFMPEG:
894         case R_IMF_IMTYPE_H264:
895         case R_IMF_IMTYPE_THEORA:
896         case R_IMF_IMTYPE_XVID:
897         case R_IMF_IMTYPE_FRAMESERVER:
898                         return 1;
899         }
900         return 0;
901 }
902
903 int BKE_imtype_supports_zbuf(const char imtype)
904 {
905         switch(imtype) {
906         case R_IMF_IMTYPE_IRIZ:
907         case R_IMF_IMTYPE_OPENEXR: /* but not R_IMF_IMTYPE_MULTILAYER */
908                         return 1;
909         }
910         return 0;
911 }
912
913 int BKE_imtype_supports_compress(const char imtype)
914 {
915         switch(imtype) {
916         case R_IMF_IMTYPE_PNG:
917                         return 1;
918         }
919         return 0;
920 }
921
922 int BKE_imtype_supports_quality(const char imtype)
923 {
924         switch(imtype) {
925         case R_IMF_IMTYPE_JPEG90:
926         case R_IMF_IMTYPE_JP2:
927         case R_IMF_IMTYPE_AVIJPEG:
928                         return 1;
929         }
930         return 0;
931 }
932
933 char BKE_imtype_valid_channels(const char imtype)
934 {
935         char chan_flag= IMA_CHAN_FLAG_RGB; /* assume all support rgb */
936
937         /* alpha */
938         switch(imtype) {
939         case R_IMF_IMTYPE_TARGA:
940         case R_IMF_IMTYPE_IRIS:
941         case R_IMF_IMTYPE_PNG:
942         /* case R_IMF_IMTYPE_BMP: */ /* read but not write */
943         case R_IMF_IMTYPE_RADHDR:
944         case R_IMF_IMTYPE_TIFF:
945         case R_IMF_IMTYPE_OPENEXR:
946         case R_IMF_IMTYPE_MULTILAYER:
947         case R_IMF_IMTYPE_DDS:
948         case R_IMF_IMTYPE_JP2:
949                         chan_flag |= IMA_CHAN_FLAG_ALPHA;
950         }
951
952         /* bw */
953         switch(imtype) {
954         case R_IMF_IMTYPE_PNG:
955         case R_IMF_IMTYPE_JPEG90:
956         case R_IMF_IMTYPE_TARGA:
957         case R_IMF_IMTYPE_RAWTGA:
958         case R_IMF_IMTYPE_TIFF:
959         case R_IMF_IMTYPE_IRIS:
960                         chan_flag |= IMA_CHAN_FLAG_BW;
961         }
962
963         return chan_flag;
964 }
965
966 char BKE_imtype_valid_depths(const char imtype)
967 {
968         switch (imtype) {
969         case R_IMF_IMTYPE_RADHDR:
970                 return R_IMF_CHAN_DEPTH_32;
971         case R_IMF_IMTYPE_TIFF:
972                 return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
973         case R_IMF_IMTYPE_OPENEXR:
974                 return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
975         case R_IMF_IMTYPE_MULTILAYER:
976                 return R_IMF_CHAN_DEPTH_32;
977         /* eeh, cineone does some strange 10bits per channel */
978         case R_IMF_IMTYPE_DPX:
979         case R_IMF_IMTYPE_CINEON:
980                 return R_IMF_CHAN_DEPTH_12;
981         case R_IMF_IMTYPE_JP2:
982                 return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
983         /* most formats are 8bit only */
984         default:
985                 return R_IMF_CHAN_DEPTH_8;
986         }
987 }
988
989
990 /* string is from command line --render-format arg, keep in sync with
991  * creator.c help info */
992 char BKE_imtype_from_arg(const char *imtype_arg)
993 {
994         if      (!strcmp(imtype_arg,"TGA")) return R_IMF_IMTYPE_TARGA;
995         else if (!strcmp(imtype_arg,"IRIS")) return R_IMF_IMTYPE_IRIS;
996 #ifdef WITH_DDS
997         else if (!strcmp(imtype_arg,"DDS")) return R_IMF_IMTYPE_DDS;
998 #endif
999         else if (!strcmp(imtype_arg,"JPEG")) return R_IMF_IMTYPE_JPEG90;
1000         else if (!strcmp(imtype_arg,"IRIZ")) return R_IMF_IMTYPE_IRIZ;
1001         else if (!strcmp(imtype_arg,"RAWTGA")) return R_IMF_IMTYPE_RAWTGA;
1002         else if (!strcmp(imtype_arg,"AVIRAW")) return R_IMF_IMTYPE_AVIRAW;
1003         else if (!strcmp(imtype_arg,"AVIJPEG")) return R_IMF_IMTYPE_AVIJPEG;
1004         else if (!strcmp(imtype_arg,"PNG")) return R_IMF_IMTYPE_PNG;
1005         else if (!strcmp(imtype_arg,"AVICODEC")) return R_IMF_IMTYPE_AVICODEC;
1006         else if (!strcmp(imtype_arg,"QUICKTIME")) return R_IMF_IMTYPE_QUICKTIME;
1007         else if (!strcmp(imtype_arg,"BMP")) return R_IMF_IMTYPE_BMP;
1008 #ifdef WITH_HDR
1009         else if (!strcmp(imtype_arg,"HDR")) return R_IMF_IMTYPE_RADHDR;
1010 #endif
1011 #ifdef WITH_TIFF
1012         else if (!strcmp(imtype_arg,"TIFF")) return R_IMF_IMTYPE_TIFF;
1013 #endif
1014 #ifdef WITH_OPENEXR
1015         else if (!strcmp(imtype_arg,"EXR")) return R_IMF_IMTYPE_OPENEXR;
1016         else if (!strcmp(imtype_arg,"MULTILAYER")) return R_IMF_IMTYPE_MULTILAYER;
1017 #endif
1018         else if (!strcmp(imtype_arg,"MPEG")) return R_IMF_IMTYPE_FFMPEG;
1019         else if (!strcmp(imtype_arg,"FRAMESERVER")) return R_IMF_IMTYPE_FRAMESERVER;
1020 #ifdef WITH_CINEON
1021         else if (!strcmp(imtype_arg,"CINEON")) return R_IMF_IMTYPE_CINEON;
1022         else if (!strcmp(imtype_arg,"DPX")) return R_IMF_IMTYPE_DPX;
1023 #endif
1024 #ifdef WITH_OPENJPEG
1025         else if (!strcmp(imtype_arg,"JP2")) return R_IMF_IMTYPE_JP2;
1026 #endif
1027         else return R_IMF_IMTYPE_INVALID;
1028 }
1029
1030 int BKE_add_image_extension(char *string, const char imtype)
1031 {
1032         const char *extension= NULL;
1033         
1034         if(imtype== R_IMF_IMTYPE_IRIS) {
1035                 if(!BLI_testextensie(string, ".rgb"))
1036                         extension= ".rgb";
1037         }
1038         else if(imtype==R_IMF_IMTYPE_IRIZ) {
1039                 if(!BLI_testextensie(string, ".rgb"))
1040                         extension= ".rgb";
1041         }
1042 #ifdef WITH_HDR
1043         else if(imtype==R_IMF_IMTYPE_RADHDR) {
1044                 if(!BLI_testextensie(string, ".hdr"))
1045                         extension= ".hdr";
1046         }
1047 #endif
1048         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1049                 if(!BLI_testextensie(string, ".png"))
1050                         extension= ".png";
1051         }
1052 #ifdef WITH_DDS
1053         else if(imtype==R_IMF_IMTYPE_DDS) {
1054                 if(!BLI_testextensie(string, ".dds"))
1055                         extension= ".dds";
1056         }
1057 #endif
1058         else if(imtype==R_IMF_IMTYPE_RAWTGA) {
1059                 if(!BLI_testextensie(string, ".tga"))
1060                         extension= ".tga";
1061         }
1062         else if(imtype==R_IMF_IMTYPE_BMP) {
1063                 if(!BLI_testextensie(string, ".bmp"))
1064                         extension= ".bmp";
1065         }
1066 #ifdef WITH_TIFF
1067         else if(imtype==R_IMF_IMTYPE_TIFF) {
1068                 if(!BLI_testextensie(string, ".tif") && 
1069                         !BLI_testextensie(string, ".tiff")) extension= ".tif";
1070         }
1071 #endif
1072 #ifdef WITH_OPENEXR
1073         else if( ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
1074                 if(!BLI_testextensie(string, ".exr"))
1075                         extension= ".exr";
1076         }
1077 #endif
1078 #ifdef WITH_CINEON
1079         else if(imtype==R_IMF_IMTYPE_CINEON){
1080                 if (!BLI_testextensie(string, ".cin"))
1081                         extension= ".cin";
1082         }
1083         else if(imtype==R_IMF_IMTYPE_DPX){
1084                 if (!BLI_testextensie(string, ".dpx"))
1085                         extension= ".dpx";
1086         }
1087 #endif
1088         else if(imtype==R_IMF_IMTYPE_TARGA) {
1089                 if(!BLI_testextensie(string, ".tga"))
1090                         extension= ".tga";
1091         }
1092 #ifdef WITH_OPENJPEG
1093         else if(imtype==R_IMF_IMTYPE_JP2) {
1094                 if(!BLI_testextensie(string, ".jp2"))
1095                         extension= ".jp2";
1096         }
1097 #endif
1098         else { //   R_IMF_IMTYPE_AVICODEC, R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90, R_IMF_IMTYPE_QUICKTIME etc
1099                 if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
1100                         extension= ".jpg";
1101         }
1102
1103         if(extension) {
1104                 /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
1105                 /* remove any other known image extension */
1106                 if(BLI_testextensie_array(string, imb_ext_image)
1107                                   || (G.have_quicktime && BLI_testextensie_array(string, imb_ext_image_qt))) {
1108                         return BLI_replace_extension(string, FILE_MAX, extension);
1109                 } else {
1110                         return BLI_ensure_extension(string, FILE_MAX, extension);
1111                         return TRUE;
1112                 }
1113                 
1114         }
1115         else {
1116                 return FALSE;
1117         }
1118 }
1119
1120 /* could allow access externally - 512 is for long names, 64 is for id names */
1121 typedef struct StampData {
1122         char    file[512];
1123         char    note[512];
1124         char    date[512];
1125         char    marker[512];
1126         char    time[512];
1127         char    frame[512];
1128         char    camera[64];
1129         char    cameralens[64];
1130         char    scene[64];
1131         char    strip[64];
1132         char    rendertime[64];
1133 } StampData;
1134
1135 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1136 {
1137         char text[256];
1138         struct tm *tl;
1139         time_t t;
1140
1141         if (scene->r.stamp & R_STAMP_FILENAME) {
1142                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s":"%s", G.relbase_valid ? G.main->name:"<untitled>");
1143         } else {
1144                 stamp_data->file[0] = '\0';
1145         }
1146         
1147         if (scene->r.stamp & R_STAMP_NOTE) {
1148                 /* Never do prefix for Note */
1149                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1150         } else {
1151                 stamp_data->note[0] = '\0';
1152         }
1153         
1154         if (scene->r.stamp & R_STAMP_DATE) {
1155                 t = time(NULL);
1156                 tl = localtime(&t);
1157                 BLI_snprintf(text, sizeof(text), "%04d/%02d/%02d %02d:%02d:%02d", tl->tm_year+1900, tl->tm_mon+1, tl->tm_mday, tl->tm_hour, tl->tm_min, tl->tm_sec);
1158                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s":"%s", text);
1159         } else {
1160                 stamp_data->date[0] = '\0';
1161         }
1162         
1163         if (scene->r.stamp & R_STAMP_MARKER) {
1164                 char *name = scene_find_last_marker_name(scene, CFRA);
1165
1166                 if (name)       BLI_strncpy(text, name, sizeof(text));
1167                 else            strcpy(text, "<none>");
1168
1169                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s":"%s", text);
1170         } else {
1171                 stamp_data->marker[0] = '\0';
1172         }
1173         
1174         if (scene->r.stamp & R_STAMP_TIME) {
1175                 int f = (int)(scene->r.cfra % scene->r.frs_sec);
1176                 int s = (int)(scene->r.cfra / scene->r.frs_sec);
1177                 int h= 0;
1178                 int m= 0;
1179
1180                 if (s) {
1181                         m = (int)(s / 60);
1182                         s %= 60;
1183
1184                         if (m) {
1185                                 h = (int)(m / 60);
1186                                 m %= 60;
1187                         }
1188                 }
1189
1190                 if (scene->r.frs_sec < 100)
1191                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%02d", h, m, s, f);
1192                 else
1193                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%03d", h, m, s, f);
1194
1195                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Time %s":"%s", text);
1196         } else {
1197                 stamp_data->time[0] = '\0';
1198         }
1199         
1200         if (scene->r.stamp & R_STAMP_FRAME) {
1201                 char format[32];
1202                 int digits= 1;
1203                 
1204                 if(scene->r.efra>9)
1205                         digits= 1 + (int) log10(scene->r.efra);
1206
1207                 BLI_snprintf(format, sizeof(format), do_prefix ? "Frame %%0%di":"%%0%di", digits);
1208                 BLI_snprintf (stamp_data->frame, sizeof(stamp_data->frame), format, scene->r.cfra);
1209         } else {
1210                 stamp_data->frame[0] = '\0';
1211         }
1212
1213         if (scene->r.stamp & R_STAMP_CAMERA) {
1214                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s":"%s", camera ? camera->id.name+2 : "<none>");
1215         } else {
1216                 stamp_data->camera[0] = '\0';
1217         }
1218
1219         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1220                 if (camera && camera->type == OB_CAMERA) {
1221                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1222                 }
1223                 else            strcpy(text, "<none>");
1224
1225                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s":"%s", text);
1226         } else {
1227                 stamp_data->cameralens[0] = '\0';
1228         }
1229
1230         if (scene->r.stamp & R_STAMP_SCENE) {
1231                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s":"%s", scene->id.name+2);
1232         } else {
1233                 stamp_data->scene[0] = '\0';
1234         }
1235         
1236         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1237                 Sequence *seq= seq_foreground_frame_get(scene, scene->r.cfra);
1238         
1239                 if (seq)        BLI_strncpy(text, seq->name+2, sizeof(text));
1240                 else            strcpy(text, "<none>");
1241
1242                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s":"%s", text);
1243         } else {
1244                 stamp_data->strip[0] = '\0';
1245         }
1246
1247         {
1248                 Render *re= RE_GetRender(scene->id.name);
1249                 RenderStats *stats= re ? RE_GetStats(re):NULL;
1250
1251                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1252                         BLI_timestr(stats->lastframetime, text);
1253
1254                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s":"%s", text);
1255                 } else {
1256                         stamp_data->rendertime[0] = '\0';
1257                 }
1258         }
1259 }
1260
1261 void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rectf, int width, int height, int channels)
1262 {
1263         struct StampData stamp_data;
1264         float w, h, pad;
1265         int x, y, y_ofs;
1266         float h_fixed;
1267         const int mono= blf_mono_font_render; // XXX
1268
1269 #define BUFF_MARGIN_X 2
1270 #define BUFF_MARGIN_Y 1
1271
1272         if (!rect && !rectf)
1273                 return;
1274         
1275         stampdata(scene, camera, &stamp_data, 1);
1276
1277         /* TODO, do_versions */
1278         if(scene->r.stamp_font_id < 8)
1279                 scene->r.stamp_font_id= 12;
1280
1281         /* set before return */
1282         BLF_size(mono, scene->r.stamp_font_id, 72);
1283         
1284         BLF_buffer(mono, rectf, rect, width, height, channels);
1285         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1286         pad= BLF_width_max(mono);
1287
1288         /* use 'h_fixed' rather than 'h', aligns better */
1289         h_fixed= BLF_height_max(mono);
1290         y_ofs = -BLF_descender(mono);
1291
1292         x= 0;
1293         y= height;
1294
1295         if (stamp_data.file[0]) {
1296                 /* Top left corner */
1297                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h= h_fixed;
1298                 y -= h;
1299
1300                 /* also a little of space to the background. */
1301                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1302
1303                 /* and draw the text. */
1304                 BLF_position(mono, x, y + y_ofs, 0.0);
1305                 BLF_draw_buffer(mono, stamp_data.file);
1306
1307                 /* the extra pixel for background. */
1308                 y -= BUFF_MARGIN_Y * 2;
1309         }
1310
1311         /* Top left corner, below File */
1312         if (stamp_data.note[0]) {
1313                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h= h_fixed;
1314                 y -= h;
1315
1316                 /* and space for background. */
1317                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1318
1319                 BLF_position(mono, x, y + y_ofs, 0.0);
1320                 BLF_draw_buffer(mono, stamp_data.note);
1321
1322                 /* the extra pixel for background. */
1323                 y -= BUFF_MARGIN_Y * 2;
1324         }
1325         
1326         /* Top left corner, below File (or Note) */
1327         if (stamp_data.date[0]) {
1328                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h= h_fixed;
1329                 y -= h;
1330
1331                 /* and space for background. */
1332                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1333
1334                 BLF_position(mono, x, y + y_ofs, 0.0);
1335                 BLF_draw_buffer(mono, stamp_data.date);
1336
1337                 /* the extra pixel for background. */
1338                 y -= BUFF_MARGIN_Y * 2;
1339         }
1340
1341         /* Top left corner, below File, Date or Note */
1342         if (stamp_data.rendertime[0]) {
1343                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h= h_fixed;
1344                 y -= h;
1345
1346                 /* and space for background. */
1347                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1348
1349                 BLF_position(mono, x, y + y_ofs, 0.0);
1350                 BLF_draw_buffer(mono, stamp_data.rendertime);
1351         }
1352
1353         x= 0;
1354         y= 0;
1355
1356         /* Bottom left corner, leaving space for timing */
1357         if (stamp_data.marker[0]) {
1358                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h= h_fixed;
1359
1360                 /* extra space for background. */
1361                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1362
1363                 /* and pad the text. */
1364                 BLF_position(mono, x, y + y_ofs, 0.0);
1365                 BLF_draw_buffer(mono, stamp_data.marker);
1366
1367                 /* space width. */
1368                 x += w + pad;
1369         }
1370         
1371         /* Left bottom corner */
1372         if (stamp_data.time[0]) {
1373                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h= h_fixed;
1374
1375                 /* extra space for background */
1376                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1377
1378                 /* and pad the text. */
1379                 BLF_position(mono, x, y + y_ofs, 0.0);
1380                 BLF_draw_buffer(mono, stamp_data.time);
1381
1382                 /* space width. */
1383                 x += w + pad;
1384         }
1385         
1386         if (stamp_data.frame[0]) {
1387                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h= h_fixed;
1388
1389                 /* extra space for background. */
1390                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1391
1392                 /* and pad the text. */
1393                 BLF_position(mono, x, y + y_ofs, 0.0);
1394                 BLF_draw_buffer(mono, stamp_data.frame);
1395
1396                 /* space width. */
1397                 x += w + pad;
1398         }
1399
1400         if (stamp_data.camera[0]) {
1401                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h= h_fixed;
1402
1403                 /* extra space for background. */
1404                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1405                 BLF_position(mono, x, y + y_ofs, 0.0);
1406                 BLF_draw_buffer(mono, stamp_data.camera);
1407
1408                 /* space width. */
1409                 x += w + pad;
1410         }
1411
1412         if (stamp_data.cameralens[0]) {
1413                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h= h_fixed;
1414
1415                 /* extra space for background. */
1416                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1417                 BLF_position(mono, x, y + y_ofs, 0.0);
1418                 BLF_draw_buffer(mono, stamp_data.cameralens);
1419         }
1420         
1421         if (stamp_data.scene[0]) {
1422                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h= h_fixed;
1423
1424                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1425                 x= width - w - 2;
1426
1427                 /* extra space for background. */
1428                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1429
1430                 /* and pad the text. */
1431                 BLF_position(mono, x, y+y_ofs, 0.0);
1432                 BLF_draw_buffer(mono, stamp_data.scene);
1433         }
1434         
1435         if (stamp_data.strip[0]) {
1436                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h= h_fixed;
1437
1438                 /* Top right corner, with an extra space because blenfont is too strict! */
1439                 x= width - w - pad;
1440                 y= height - h;
1441
1442                 /* extra space for background. */
1443                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1444
1445                 BLF_position(mono, x, y + y_ofs, 0.0);
1446                 BLF_draw_buffer(mono, stamp_data.strip);
1447         }
1448
1449         /* cleanup the buffer. */
1450         BLF_buffer(mono, NULL, NULL, 0, 0, 0);
1451
1452 #undef BUFF_MARGIN_X
1453 #undef BUFF_MARGIN_Y
1454 }
1455
1456 void BKE_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1457 {
1458         struct StampData stamp_data;
1459
1460         if (!ibuf)      return;
1461         
1462         /* fill all the data values, no prefix */
1463         stampdata(scene, camera, &stamp_data, 0);
1464         
1465         if (stamp_data.file[0])         IMB_metadata_change_field (ibuf, "File",                stamp_data.file);
1466         if (stamp_data.note[0])         IMB_metadata_change_field (ibuf, "Note",                stamp_data.note);
1467         if (stamp_data.date[0])         IMB_metadata_change_field (ibuf, "Date",                stamp_data.date);
1468         if (stamp_data.marker[0])       IMB_metadata_change_field (ibuf, "Marker",      stamp_data.marker);
1469         if (stamp_data.time[0])         IMB_metadata_change_field (ibuf, "Time",                stamp_data.time);
1470         if (stamp_data.frame[0])        IMB_metadata_change_field (ibuf, "Frame",       stamp_data.frame);
1471         if (stamp_data.camera[0])       IMB_metadata_change_field (ibuf, "Camera",      stamp_data.camera);
1472         if (stamp_data.cameralens[0]) IMB_metadata_change_field (ibuf, "Lens",  stamp_data.cameralens);
1473         if (stamp_data.scene[0])        IMB_metadata_change_field (ibuf, "Scene",       stamp_data.scene);
1474         if (stamp_data.strip[0])        IMB_metadata_change_field (ibuf, "Strip",       stamp_data.strip);
1475         if (stamp_data.rendertime[0]) IMB_metadata_change_field (ibuf, "RenderTime", stamp_data.rendertime);
1476 }
1477
1478 int BKE_alphatest_ibuf(ImBuf *ibuf)
1479 {
1480         int tot;
1481         if(ibuf->rect_float) {
1482                 float *buf= ibuf->rect_float;
1483                 for(tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1484                         if(buf[3] < 1.0f) {
1485                                 return TRUE;
1486                         }
1487                 }
1488         }
1489         else if (ibuf->rect) {
1490                 unsigned char *buf= (unsigned char *)ibuf->rect;
1491                 for(tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1492                         if(buf[3] != 255) {
1493                                 return TRUE;
1494                         }
1495                 }
1496         }
1497
1498         return FALSE;
1499 }
1500
1501 /* note: imf->planes is ignored here, its assumed the image channels
1502  * are already set */
1503 int BKE_write_ibuf(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1504 {
1505         char imtype= imf->imtype;
1506         char compress= imf->compress;
1507         char quality= imf->quality;
1508
1509         int ok;
1510
1511         if(imtype == -1) {
1512                 /* use whatever existing image type is set by 'ibuf' */
1513         }
1514         else if(imtype== R_IMF_IMTYPE_IRIS) {
1515                 ibuf->ftype= IMAGIC;
1516         }
1517 #ifdef WITH_HDR
1518         else if (imtype==R_IMF_IMTYPE_RADHDR) {
1519                 ibuf->ftype= RADHDR;
1520         }
1521 #endif
1522         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1523                 ibuf->ftype= PNG;
1524
1525                 if(imtype==R_IMF_IMTYPE_PNG)
1526                         ibuf->ftype |= compress;
1527
1528         }
1529 #ifdef WITH_DDS
1530         else if (imtype==R_IMF_IMTYPE_DDS) {
1531                 ibuf->ftype= DDS;
1532         }
1533 #endif
1534         else if (imtype==R_IMF_IMTYPE_BMP) {
1535                 ibuf->ftype= BMP;
1536         }
1537 #ifdef WITH_TIFF
1538         else if (imtype==R_IMF_IMTYPE_TIFF) {
1539                 ibuf->ftype= TIF;
1540
1541                 if(imf->depth == R_IMF_CHAN_DEPTH_16)
1542                         ibuf->ftype |= TIF_16BIT;
1543         }
1544 #endif
1545 #ifdef WITH_OPENEXR
1546         else if (imtype==R_IMF_IMTYPE_OPENEXR || imtype==R_IMF_IMTYPE_MULTILAYER) {
1547                 ibuf->ftype= OPENEXR;
1548                 if(imf->depth == R_IMF_CHAN_DEPTH_16)
1549                         ibuf->ftype |= OPENEXR_HALF;
1550                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1551                 
1552                 if(!(imf->flag & R_IMF_FLAG_ZBUF))
1553                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1554                 
1555         }
1556 #endif
1557 #ifdef WITH_CINEON
1558         else if (imtype==R_IMF_IMTYPE_CINEON) {
1559                 ibuf->ftype = CINEON;
1560         }
1561         else if (imtype==R_IMF_IMTYPE_DPX) {
1562                 ibuf->ftype = DPX;
1563         }
1564 #endif
1565         else if (imtype==R_IMF_IMTYPE_TARGA) {
1566                 ibuf->ftype= TGA;
1567         }
1568         else if(imtype==R_IMF_IMTYPE_RAWTGA) {
1569                 ibuf->ftype= RAWTGA;
1570         }
1571 #ifdef WITH_OPENJPEG
1572         else if(imtype==R_IMF_IMTYPE_JP2) {
1573                 if(quality < 10) quality= 90;
1574                 ibuf->ftype= JP2|quality;
1575                 
1576                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1577                         ibuf->ftype |= JP2_16BIT;
1578                 } else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1579                         ibuf->ftype |= JP2_12BIT;
1580                 }
1581                 
1582                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
1583                         ibuf->ftype |= JP2_YCC;
1584                 }
1585
1586                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
1587                         ibuf->ftype |= JP2_CINE;
1588                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
1589                                 ibuf->ftype |= JP2_CINE_48FPS;
1590                 }
1591         }
1592 #endif
1593         else {
1594                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
1595                 if(quality < 10) quality= 90;
1596                 ibuf->ftype= JPG|quality;
1597         }
1598         
1599         BLI_make_existing_file(name);
1600         
1601         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1602         if (ok == 0) {
1603                 perror(name);
1604         }
1605         
1606         return(ok);
1607 }
1608
1609 /* same as BKE_write_ibuf_as but crappy workaround not to perminantly modify
1610  * _some_, values in the imbuf */
1611 int BKE_write_ibuf_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
1612                       const short save_copy)
1613 {
1614         ImBuf ibuf_back= *ibuf;
1615         int ok;
1616
1617         /* all data is rgba anyway,
1618          * this just controls how to save for some formats */
1619         ibuf->planes= imf->planes;
1620
1621         ok= BKE_write_ibuf(ibuf, name, imf);
1622
1623         if (save_copy) {
1624                 /* note that we are not restoring _all_ settings */
1625                 ibuf->planes= ibuf_back.planes;
1626                 ibuf->ftype=  ibuf_back.ftype;
1627         }
1628
1629         return ok;
1630 }
1631
1632 int BKE_write_ibuf_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
1633 {
1634         if(scene && scene->r.stamp & R_STAMP_ALL)
1635                 BKE_stamp_info(scene, camera, ibuf);
1636
1637         return BKE_write_ibuf(ibuf, name, imf);
1638 }
1639
1640
1641 void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype, const short use_ext, const short use_frames)
1642 {
1643         if (string==NULL) return;
1644         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1645         BLI_path_abs(string, relbase);
1646
1647         if(use_frames)
1648                 BLI_path_frame(string, frame, 4);
1649
1650         if(use_ext)
1651                 BKE_add_image_extension(string, imtype);
1652                 
1653 }
1654
1655 /* used by sequencer too */
1656 struct anim *openanim(const char *name, int flags, int streamindex)
1657 {
1658         struct anim *anim;
1659         struct ImBuf *ibuf;
1660         
1661         anim = IMB_open_anim(name, flags, streamindex);
1662         if (anim == NULL) return NULL;
1663
1664         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1665         if (ibuf == NULL) {
1666                 if(BLI_exists(name))
1667                         printf("not an anim: %s\n", name);
1668                 else
1669                         printf("anim file doesn't exist: %s\n", name);
1670                 IMB_free_anim(anim);
1671                 return NULL;
1672         }
1673         IMB_freeImBuf(ibuf);
1674         
1675         return(anim);
1676 }
1677
1678 /* ************************* New Image API *************** */
1679
1680
1681 /* Notes about Image storage 
1682 - packedfile
1683   -> written in .blend
1684 - filename
1685   -> written in .blend
1686 - movie
1687   -> comes from packedfile or filename
1688 - renderresult
1689   -> comes from packedfile or filename
1690 - listbase
1691   -> ibufs from exrhandle
1692 - flipbook array
1693   -> ibufs come from movie, temporary renderresult or sequence
1694 - ibuf
1695   -> comes from packedfile or filename or generated
1696
1697 */
1698
1699
1700 /* forces existence of 1 Image for renderout or nodes, returns Image */
1701 /* name is only for default, when making new one */
1702 Image *BKE_image_verify_viewer(int type, const char *name)
1703 {
1704         Image *ima;
1705         
1706         for(ima=G.main->image.first; ima; ima= ima->id.next)
1707                 if(ima->source==IMA_SRC_VIEWER)
1708                         if(ima->type==type)
1709                                 break;
1710         
1711         if(ima==NULL)
1712                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1713         
1714         /* happens on reload, imagewindow cannot be image user when hidden*/
1715         if(ima->id.us==0)
1716                 id_us_plus(&ima->id);
1717
1718         return ima;
1719 }
1720
1721 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1722 {
1723         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1724 }
1725
1726 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1727 {
1728         if(ima==NULL)
1729                 return;
1730         
1731         switch(signal) {
1732         case IMA_SIGNAL_FREE:
1733                 image_free_buffers(ima);
1734                 if(iuser)
1735                         iuser->ok= 1;
1736                 break;
1737         case IMA_SIGNAL_SRC_CHANGE:
1738                 if(ima->type == IMA_TYPE_UV_TEST)
1739                         if(ima->source != IMA_SRC_GENERATED)
1740                                 ima->type= IMA_TYPE_IMAGE;
1741
1742                 if(ima->source==IMA_SRC_GENERATED) {
1743                         if(ima->gen_x==0 || ima->gen_y==0) {
1744                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1745                                 if(ibuf) {
1746                                         ima->gen_x= ibuf->x;
1747                                         ima->gen_y= ibuf->y;
1748                                 }
1749                         }
1750                 }
1751
1752                 /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
1753                 if(ima->type!=IMA_TYPE_MULTILAYER)
1754                         image_free_buffers(ima);
1755
1756                 ima->ok= 1;
1757                 if(iuser)
1758                         iuser->ok= 1;
1759                 break;
1760                         
1761         case IMA_SIGNAL_RELOAD:
1762                 /* try to repack file */
1763                 if(ima->packedfile) {
1764                         PackedFile *pf;
1765                         pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
1766                         if (pf) {
1767                                 freePackedFile(ima->packedfile);
1768                                 ima->packedfile = pf;
1769                                 image_free_buffers(ima);
1770                         } else {
1771                                 printf("ERROR: Image not available. Keeping packed image\n");
1772                         }
1773                 }
1774                 else
1775                         image_free_buffers(ima);
1776                 
1777                 if(iuser)
1778                         iuser->ok= 1;
1779                 
1780                 break;
1781         case IMA_SIGNAL_USER_NEW_IMAGE:
1782                 if(iuser) {
1783                         iuser->ok= 1;
1784                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1785                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1786                                         iuser->multi_index= 0;
1787                                         iuser->layer= iuser->pass= 0;
1788                                 }
1789                         }
1790                 }
1791                 break;
1792         }
1793         
1794         /* dont use notifiers because they are not 100% sure to succseed
1795          * this also makes sure all scenes are accounted for. */
1796         {
1797                 Scene *scene;
1798                 for(scene= G.main->scene.first; scene; scene= scene->id.next) {
1799                         if(scene->nodetree) {
1800                                 nodeUpdateID(scene->nodetree, &ima->id);
1801                         }
1802                 }
1803         }
1804 }
1805
1806 /* if layer or pass changes, we need an index for the imbufs list */
1807 /* note it is called for rendered results, but it doesnt use the index! */
1808 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1809 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1810 {
1811         RenderLayer *rl;
1812         RenderPass *rpass= NULL;
1813         
1814         if(rr==NULL) 
1815                 return NULL;
1816         
1817         if(iuser) {
1818                 short index= 0, rl_index= 0, rp_index;
1819                 
1820                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1821                         rp_index= 0;
1822                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1823                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1824                                         break;
1825                         if(rpass)
1826                                 break;
1827                 }
1828                 
1829                 if(rpass)
1830                         iuser->multi_index= index;
1831                 else 
1832                         iuser->multi_index= 0;
1833         }
1834         if(rpass==NULL) {
1835                 rl= rr->layers.first;
1836                 if(rl)
1837                         rpass= rl->passes.first;
1838         }
1839         
1840         return rpass;
1841 }
1842
1843 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
1844 {
1845         if(ima->rr) {
1846                 return ima->rr;
1847         }
1848         else if(ima->type==IMA_TYPE_R_RESULT) {
1849                 if(ima->render_slot == ima->last_render_slot)
1850                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
1851                 else
1852                         return ima->renders[ima->render_slot];
1853         }
1854         else
1855                 return NULL;
1856 }
1857
1858 void BKE_image_release_renderresult(Scene *scene, Image *ima)
1859 {
1860         if(ima->rr);
1861         else if(ima->type==IMA_TYPE_R_RESULT) {
1862                 if(ima->render_slot == ima->last_render_slot)
1863                         RE_ReleaseResult(RE_GetRender(scene->id.name));
1864         }
1865 }
1866
1867 void BKE_image_backup_render(Scene *scene, Image *ima)
1868 {
1869         /* called right before rendering, ima->renders contains render
1870            result pointers for everything but the current render */
1871         Render *re= RE_GetRender(scene->id.name);
1872         int slot= ima->render_slot, last= ima->last_render_slot;
1873
1874         if(slot != last) {
1875                 if(ima->renders[slot]) {
1876                         RE_FreeRenderResult(ima->renders[slot]);
1877                         ima->renders[slot]= NULL;
1878                 }
1879
1880                 ima->renders[last]= NULL;
1881                 RE_SwapResult(re, &ima->renders[last]);
1882         }
1883
1884         ima->last_render_slot= slot;
1885 }
1886
1887 /* after imbuf load, openexr type can return with a exrhandle open */
1888 /* in that case we have to build a render-result */
1889 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1890 {
1891         
1892         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1893
1894 #ifdef WITH_OPENEXR
1895         IMB_exr_close(ibuf->userdata);
1896 #endif
1897
1898         ibuf->userdata= NULL;
1899         if(ima->rr)
1900                 ima->rr->framenr= framenr;
1901 }
1902
1903 /* common stuff to do with images after loading */
1904 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1905 {
1906         /* preview is NULL when it has never been used as an icon before */
1907         if(G.background==0 && ima->preview==NULL)
1908                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1909
1910         /* fields */
1911         if (ima->flag & IMA_FIELDS) {
1912                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1913                 else de_interlace_ng(ibuf);
1914         }
1915         /* timer */
1916         ima->lastused = clock() / CLOCKS_PER_SEC;
1917         
1918         ima->ok= IMA_OK_LOADED;
1919         
1920 }
1921
1922 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1923 {
1924         struct ImBuf *ibuf;
1925         unsigned short numlen;
1926         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1927         int flag;
1928         
1929         /* XXX temp stuff? */
1930         if(ima->lastframe != frame)
1931                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1932
1933         ima->lastframe= frame;
1934         BLI_strncpy(name, ima->name, sizeof(name));
1935         BLI_stringdec(name, head, tail, &numlen);
1936         BLI_stringenc(name, head, tail, numlen, frame);
1937
1938         BLI_path_abs(name, ID_BLEND_PATH(G.main, &ima->id));
1939         
1940         flag= IB_rect|IB_multilayer;
1941         if(ima->flag & IMA_DO_PREMUL)
1942                 flag |= IB_premul;
1943
1944         /* read ibuf */
1945         ibuf = IMB_loadiffname(name, flag);
1946
1947 #if 0
1948         if(ibuf) {
1949                 printf(AT" loaded %s\n", name);
1950         } else {
1951                 printf(AT" missed %s\n", name);
1952         }
1953 #endif
1954
1955         if (ibuf) {
1956 #ifdef WITH_OPENEXR
1957                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1958                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1959                         image_create_multilayer(ima, ibuf, frame);      
1960                         ima->type= IMA_TYPE_MULTILAYER;
1961                         IMB_freeImBuf(ibuf);
1962                         ibuf= NULL;
1963                 }
1964                 else {
1965                         image_initialize_after_load(ima, ibuf);
1966                         image_assign_ibuf(ima, ibuf, 0, frame);
1967                 }
1968 #else
1969                 image_initialize_after_load(ima, ibuf);
1970                 image_assign_ibuf(ima, ibuf, 0, frame);
1971 #endif
1972         }
1973         else
1974                 ima->ok= 0;
1975         
1976         if(iuser)
1977                 iuser->ok= ima->ok;
1978         
1979         return ibuf;
1980 }
1981
1982 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1983 {
1984         struct ImBuf *ibuf= NULL;
1985         
1986         /* either we load from RenderResult, or we have to load a new one */
1987         
1988         /* check for new RenderResult */
1989         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1990                 /* copy to survive not found multilayer image */
1991                 RenderResult *oldrr= ima->rr;
1992         
1993                 ima->rr= NULL;
1994                 ibuf = image_load_sequence_file(ima, iuser, frame);
1995                 
1996                 if(ibuf) { /* actually an error */
1997                         ima->type= IMA_TYPE_IMAGE;
1998                         printf("error, multi is normal image\n");
1999                 }
2000                 // printf("loaded new result %p\n", ima->rr);
2001                 /* free result if new one found */
2002                 if(ima->rr) {
2003                         // if(oldrr) printf("freed previous result %p\n", oldrr);
2004                         if(oldrr) RE_FreeRenderResult(oldrr);
2005                 }
2006                 else {
2007                         ima->rr= oldrr;
2008                 }
2009
2010         }
2011         if(ima->rr) {
2012                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
2013                 
2014                 if(rpass) {
2015                         // printf("load from pass %s\n", rpass->name);
2016                         /* since we free  render results, we copy the rect */
2017                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2018                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
2019                         ibuf->flags |= IB_rectfloat;
2020                         ibuf->mall= IB_rectfloat;
2021                         ibuf->channels= rpass->channels;
2022                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2023                         
2024                         image_initialize_after_load(ima, ibuf);
2025                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
2026                         
2027                 }
2028                 // else printf("pass not found\n");
2029         }
2030         else
2031                 ima->ok= 0;
2032         
2033         if(iuser)
2034                 iuser->ok= ima->ok;
2035         
2036         return ibuf;
2037 }
2038
2039
2040 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
2041 {
2042         struct ImBuf *ibuf= NULL;
2043         
2044         ima->lastframe= frame;
2045         
2046         if(ima->anim==NULL) {
2047                 char str[FILE_MAX];
2048                 
2049                 BLI_strncpy(str, ima->name, FILE_MAX);
2050                 BLI_path_abs(str, ID_BLEND_PATH(G.main, &ima->id));
2051
2052                 /* FIXME: make several stream accessible in image editor, too*/
2053                 ima->anim = openanim(str, IB_rect, 0);
2054                 
2055                 /* let's initialize this user */
2056                 if(ima->anim && iuser && iuser->frames==0)
2057                         iuser->frames= IMB_anim_get_duration(ima->anim,
2058                                                              IMB_TC_RECORD_RUN);
2059         }
2060         
2061         if(ima->anim) {
2062                 int dur = IMB_anim_get_duration(ima->anim,
2063                                                 IMB_TC_RECORD_RUN);
2064                 int fra= frame-1;
2065                 
2066                 if(fra<0) fra = 0;
2067                 if(fra>(dur-1)) fra= dur-1;
2068                 ibuf = IMB_makeSingleUser(
2069                         IMB_anim_absolute(ima->anim, fra,
2070                                           IMB_TC_RECORD_RUN,
2071                                           IMB_PROXY_NONE));
2072                 
2073                 if(ibuf) {
2074                         image_initialize_after_load(ima, ibuf);
2075                         image_assign_ibuf(ima, ibuf, 0, frame);
2076                 }
2077                 else
2078                         ima->ok= 0;
2079         }
2080         else
2081                 ima->ok= 0;
2082         
2083         if(iuser)
2084                 iuser->ok= ima->ok;
2085         
2086         return ibuf;
2087 }
2088
2089 /* warning, 'iuser' can be NULL */
2090 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2091 {
2092         struct ImBuf *ibuf;
2093         char str[FILE_MAX];
2094         int assign = 0, flag;
2095         
2096         /* always ensure clean ima */
2097         image_free_buffers(ima);
2098         
2099         /* is there a PackedFile with this image ? */
2100         if (ima->packedfile) {
2101                 flag = IB_rect|IB_multilayer;
2102                 if(ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
2103                 
2104                 ibuf = IMB_ibImageFromMemory((unsigned char*)ima->packedfile->data, ima->packedfile->size, flag, "<packed data>");
2105         } 
2106         else {
2107                 flag= IB_rect|IB_multilayer|IB_metadata;
2108                 if(ima->flag & IMA_DO_PREMUL)
2109                         flag |= IB_premul;
2110                         
2111                 /* get the right string */
2112                 BLI_strncpy(str, ima->name, sizeof(str));
2113                 BLI_path_abs(str, ID_BLEND_PATH(G.main, &ima->id));
2114                 
2115                 /* read ibuf */
2116                 ibuf = IMB_loadiffname(str, flag);
2117         }
2118         
2119         if (ibuf) {
2120                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2121                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
2122                         image_create_multilayer(ima, ibuf, cfra);       
2123                         ima->type= IMA_TYPE_MULTILAYER;
2124                         IMB_freeImBuf(ibuf);
2125                         ibuf= NULL;
2126                 }
2127                 else {
2128                         image_initialize_after_load(ima, ibuf);
2129                         assign= 1;
2130
2131                         /* check if the image is a font image... */
2132                         detectBitmapFont(ibuf);
2133                         
2134                         /* make packed file for autopack */
2135                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2136                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2137                 }
2138         }
2139         else
2140                 ima->ok= 0;
2141         
2142         if(assign)
2143                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2144
2145         if(iuser)
2146                 iuser->ok= ima->ok;
2147         
2148         return ibuf;
2149 }
2150
2151 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2152 {
2153         ImBuf *ibuf= NULL;
2154         
2155         if(ima->rr==NULL) {
2156                 ibuf = image_load_image_file(ima, iuser, 0);
2157                 if(ibuf) { /* actually an error */
2158                         ima->type= IMA_TYPE_IMAGE;
2159                         return ibuf;
2160                 }
2161         }
2162         if(ima->rr) {
2163                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
2164
2165                 if(rpass) {
2166                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2167                         
2168                         image_initialize_after_load(ima, ibuf);
2169                         
2170                         ibuf->rect_float= rpass->rect;
2171                         ibuf->flags |= IB_rectfloat;
2172                         ibuf->channels= rpass->channels;
2173                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2174
2175                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2176                 }
2177         }
2178         
2179         if(ibuf==NULL) 
2180                 ima->ok= 0;
2181         if(iuser)
2182                 iuser->ok= ima->ok;
2183         
2184         return ibuf;
2185 }
2186
2187
2188 /* showing RGBA result itself (from compo/sequence) or
2189    like exr, using layers etc */
2190 /* always returns a single ibuf, also during render progress */
2191 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2192 {
2193         Render *re;
2194         RenderResult rres;
2195         float *rectf, *rectz;
2196         unsigned int *rect;
2197         float dither;
2198         int channels, layer, pass;
2199         ImBuf *ibuf;
2200         int from_render= (ima->render_slot == ima->last_render_slot);
2201
2202         if(!(iuser && iuser->scene))
2203                 return NULL;
2204
2205         /* if we the caller is not going to release the lock, don't give the image */
2206         if(!lock_r)
2207                 return NULL;
2208
2209         re= RE_GetRender(iuser->scene->id.name);
2210
2211         channels= 4;
2212         layer= (iuser)? iuser->layer: 0;
2213         pass= (iuser)? iuser->pass: 0;
2214
2215         if(from_render) {
2216                 RE_AcquireResultImage(re, &rres);
2217         }
2218         else if(ima->renders[ima->render_slot]) {
2219                 rres= *(ima->renders[ima->render_slot]);
2220                 rres.have_combined= rres.rectf != NULL;
2221         }
2222         else
2223                 memset(&rres, 0, sizeof(RenderResult));
2224         
2225         if(!(rres.rectx > 0 && rres.recty > 0)) {
2226                 if(from_render)
2227                         RE_ReleaseResultImage(re);
2228                 return NULL;
2229         }
2230
2231         /* release is done in BKE_image_release_ibuf using lock_r */
2232         if(from_render) {
2233                 BLI_lock_thread(LOCK_VIEWER);
2234                 *lock_r= re;
2235         }
2236
2237         /* this gives active layer, composite or seqence result */
2238         rect= (unsigned int *)rres.rect32;
2239         rectf= rres.rectf;
2240         rectz= rres.rectz;
2241         dither= iuser->scene->r.dither_intensity;
2242
2243         /* combined layer gets added as first layer */
2244         if(rres.have_combined && layer==0);
2245         else if(rres.layers.first) {
2246                 RenderLayer *rl= BLI_findlink(&rres.layers, layer-(rres.have_combined?1:0));
2247                 if(rl) {
2248                         RenderPass *rpass;
2249
2250                         /* there's no combined pass, is in renderlayer itself */
2251                         if(pass==0) {
2252                                 rectf= rl->rectf;
2253                         }
2254                         else {
2255                                 rpass= BLI_findlink(&rl->passes, pass-1);
2256                                 if(rpass) {
2257                                         channels= rpass->channels;
2258                                         rectf= rpass->rect;
2259                                         dither= 0.0f; /* don't dither passes */
2260                                 }
2261                         }
2262
2263                         for(rpass= rl->passes.first; rpass; rpass= rpass->next)
2264                                 if(rpass->passtype == SCE_PASS_Z)
2265                                         rectz= rpass->rect;
2266                 }
2267         }
2268
2269         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2270
2271         /* make ibuf if needed, and initialize it */
2272         if(ibuf==NULL) {
2273                 ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2274                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2275         }
2276
2277         ibuf->x= rres.rectx;
2278         ibuf->y= rres.recty;
2279         
2280         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
2281                 imb_freerectImBuf(ibuf);
2282
2283         if(rect)
2284                 ibuf->rect= rect;
2285         
2286         if(rectf) {
2287                 ibuf->rect_float= rectf;
2288                 ibuf->flags |= IB_rectfloat;
2289                 ibuf->channels= channels;
2290         }
2291         else {
2292                 ibuf->rect_float= NULL;
2293                 ibuf->flags &= ~IB_rectfloat;
2294         }
2295
2296         if(rectz) {
2297                 ibuf->zbuf_float= rectz;
2298                 ibuf->flags |= IB_zbuffloat;
2299         }
2300         else {
2301                 ibuf->zbuf_float= NULL;
2302                 ibuf->flags &= ~IB_zbuffloat;
2303         }
2304
2305         /* since its possible to access the buffer from the image directly, set the profile [#25073] */
2306         ibuf->profile= (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) ? IB_PROFILE_LINEAR_RGB : IB_PROFILE_NONE;
2307
2308         ibuf->dither= dither;
2309
2310         ima->ok= IMA_OK_LOADED;
2311
2312         return ibuf;
2313 }
2314
2315 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2316 {
2317         ImBuf *ibuf = NULL;
2318         int frame = 0, index = 0;
2319
2320         /* see if we already have an appropriate ibuf, with image source and type */
2321         if(ima->source==IMA_SRC_MOVIE) {
2322                 frame= iuser?iuser->framenr:ima->lastframe;
2323                 ibuf= image_get_ibuf(ima, 0, frame);
2324                 /* XXX temp stuff? */
2325                 if(ima->lastframe != frame)
2326                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2327                 ima->lastframe = frame;
2328         }
2329         else if(ima->source==IMA_SRC_SEQUENCE) {
2330                 if(ima->type==IMA_TYPE_IMAGE) {
2331                         frame= iuser?iuser->framenr:ima->lastframe;
2332                         ibuf= image_get_ibuf(ima, 0, frame);
2333                         
2334                         /* XXX temp stuff? */
2335                         if(ima->lastframe != frame) {
2336                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2337                         }
2338                         ima->lastframe = frame;
2339                 }       
2340                 else if(ima->type==IMA_TYPE_MULTILAYER) {
2341                         frame= iuser?iuser->framenr:ima->lastframe;
2342                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
2343                         ibuf= image_get_ibuf(ima, index, frame);
2344                 }
2345         }
2346         else if(ima->source==IMA_SRC_FILE) {
2347                 if(ima->type==IMA_TYPE_IMAGE)
2348                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2349                 else if(ima->type==IMA_TYPE_MULTILAYER)
2350                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2351         }
2352         else if(ima->source == IMA_SRC_GENERATED) {
2353                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2354         }
2355         else if(ima->source == IMA_SRC_VIEWER) {
2356                 /* always verify entirely, not that this shouldn't happen
2357                  * as part of texture sampling in rendering anyway, so not
2358                  * a big bottleneck */
2359         }
2360
2361         *frame_r = frame;
2362         *index_r = index;
2363
2364         return ibuf;
2365 }
2366
2367 /* Checks optional ImageUser and verifies/creates ImBuf. */
2368 /* use this one if you want to get a render result in progress,
2369  * if not, use BKE_image_get_ibuf which doesn't require a release */
2370 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2371 {
2372         ImBuf *ibuf= NULL;
2373         float color[] = {0, 0, 0, 1};
2374         int frame= 0, index= 0;
2375
2376         /* This function is intended to be thread-safe. It postpones the mutex lock
2377          * until it needs to load the image, if the image is already there it
2378          * should just get the pointer and return. The reason is that a lot of mutex
2379          * locks appears to be very slow on certain multicore macs, causing a render
2380          * with image textures to actually slow down as more threads are used.
2381          *
2382          * Note that all the image loading functions should also make sure they do
2383          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2384          * That means, the last two steps must be, 1) add the ibuf to the list and
2385          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2386         
2387         if(lock_r)
2388                 *lock_r= NULL;
2389
2390         /* quick reject tests */
2391         if(ima==NULL) 
2392                 return NULL;
2393         if(iuser) {
2394                 if(iuser->ok==0)
2395                         return NULL;
2396         }
2397         else if(ima->ok==0)
2398                 return NULL;
2399         
2400         /* try to get the ibuf without locking */
2401         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2402
2403         if(ibuf == NULL) {
2404                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2405                  * load the image */
2406                 BLI_lock_thread(LOCK_IMAGE);
2407
2408                 /* need to check ok flag and loading ibuf again, because the situation
2409                  * might have changed in the meantime */
2410                 if(iuser) {
2411                         if(iuser->ok==0) {
2412                                 BLI_unlock_thread(LOCK_IMAGE);
2413                                 return NULL;
2414                         }
2415                 }
2416                 else if(ima->ok==0) {
2417                         BLI_unlock_thread(LOCK_IMAGE);
2418                         return NULL;
2419                 }
2420
2421                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2422
2423                 if(ibuf == NULL) {
2424                         /* we are sure we have to load the ibuf, using source and type */
2425                         if(ima->source==IMA_SRC_MOVIE) {
2426                                 /* source is from single file, use flipbook to store ibuf */
2427                                 ibuf= image_load_movie_file(ima, iuser, frame);
2428                         }
2429                         else if(ima->source==IMA_SRC_SEQUENCE) {
2430                                 if(ima->type==IMA_TYPE_IMAGE) {
2431                                         /* regular files, ibufs in flipbook, allows saving */
2432                                         ibuf= image_load_sequence_file(ima, iuser, frame);
2433                                 }
2434                                 /* no else; on load the ima type can change */
2435                                 if(ima->type==IMA_TYPE_MULTILAYER) {
2436                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2437                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
2438                                 }
2439                         }
2440                         else if(ima->source==IMA_SRC_FILE) {
2441                                 
2442                                 if(ima->type==IMA_TYPE_IMAGE)
2443                                         ibuf= image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */
2444                                 /* no else; on load the ima type can change */
2445                                 if(ima->type==IMA_TYPE_MULTILAYER)
2446                                         /* keeps render result, stores ibufs in listbase, allows saving */
2447                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
2448                                         
2449                         }
2450                         else if(ima->source == IMA_SRC_GENERATED) {
2451                                 /* generated is: ibuf is allocated dynamically */
2452                                 /* UV testgrid or black or solid etc */
2453                                 if(ima->gen_x==0) ima->gen_x= 1024;
2454                                 if(ima->gen_y==0) ima->gen_y= 1024;
2455                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type, color);
2456                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2457                                 ima->ok= IMA_OK_LOADED;
2458                         }
2459                         else if(ima->source == IMA_SRC_VIEWER) {
2460                                 if(ima->type==IMA_TYPE_R_RESULT) {
2461                                         /* always verify entirely, and potentially
2462                                            returns pointer to release later */
2463                                         ibuf= image_get_render_result(ima, iuser, lock_r);
2464                                 }
2465                                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2466                                         /* requires lock/unlock, otherwise don't return image */
2467                                         if(lock_r) {
2468                                                 /* unlock in BKE_image_release_ibuf */
2469                                                 BLI_lock_thread(LOCK_VIEWER);
2470                                                 *lock_r= ima;
2471
2472                                                 /* XXX anim play for viewer nodes not yet supported */
2473                                                 frame= 0; // XXX iuser?iuser->framenr:0;
2474                                                 ibuf= image_get_ibuf(ima, 0, frame);
2475
2476                                                 if(!ibuf) {
2477                                                         /* Composite Viewer, all handled in compositor */
2478                                                         /* fake ibuf, will be filled in compositor */
2479                                                         ibuf= IMB_allocImBuf(256, 256, 32, IB_rect);
2480                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2481                                                 }
2482                                         }
2483                                 }
2484                         }
2485                 }
2486
2487                 BLI_unlock_thread(LOCK_IMAGE);
2488         }
2489
2490         tag_image_time(ima);
2491
2492         return ibuf;
2493 }
2494
2495 void BKE_image_release_ibuf(Image *ima, void *lock)
2496 {
2497         /* for getting image during threaded render / compositing, need to release */
2498         if(lock == ima) {
2499                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2500         }
2501         else if(lock) {
2502                 RE_ReleaseResultImage(lock); /* render result */
2503                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2504         }
2505 }
2506
2507 /* warning, this can allocate generated images */
2508 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2509 {
2510         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2511         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2512 }
2513
2514 int BKE_image_user_get_frame(const ImageUser *iuser, int cfra, int fieldnr)
2515 {
2516         const int len= (iuser->fie_ima*iuser->frames)/2;
2517
2518         if(len==0) {
2519                 return 0;
2520         }
2521         else {
2522                 int framenr;
2523                 cfra= cfra - iuser->sfra+1;
2524
2525                 /* cyclic */
2526                 if(iuser->cycl) {
2527                         cfra= ( (cfra) % len );
2528                         if(cfra < 0) cfra+= len;
2529                         if(cfra==0) cfra= len;
2530                 }
2531
2532                 if(cfra<0) cfra= 0;
2533                 else if(cfra>len) cfra= len;
2534
2535                 /* convert current frame to current field */
2536                 cfra= 2*(cfra);
2537                 if(fieldnr) cfra++;
2538
2539                 /* transform to images space */
2540                 framenr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2541                 if(framenr>iuser->frames) framenr= iuser->frames;
2542                 framenr+= iuser->offset;
2543
2544                 if(iuser->cycl) {
2545                         framenr= ( (framenr) % len );
2546                         while(framenr < 0) framenr+= len;
2547                         if(framenr==0) framenr= len;
2548                 }
2549
2550                 return framenr;
2551         }
2552 }
2553
2554 void BKE_image_user_calc_frame(ImageUser *iuser, int cfra, int fieldnr)
2555 {
2556         const int framenr= BKE_image_user_get_frame(iuser, cfra, fieldnr);
2557
2558         /* allows image users to handle redraws */
2559         if(iuser->flag & IMA_ANIM_ALWAYS)
2560                 if(framenr!=iuser->framenr)
2561                         iuser->flag |= IMA_ANIM_REFRESHED;
2562
2563         iuser->framenr= framenr;
2564         if(iuser->ok==0) iuser->ok= 1;
2565 }
2566
2567 int BKE_image_has_alpha(struct Image *image)
2568 {
2569         ImBuf *ibuf;
2570         void *lock;
2571         int planes;
2572         
2573         ibuf= BKE_image_acquire_ibuf(image, NULL, &lock);
2574         planes = (ibuf?ibuf->planes:0);
2575         BKE_image_release_ibuf(image, lock);
2576
2577         if (planes == 32)
2578                 return 1;
2579         else
2580                 return 0;
2581 }
2582