Render display fix:
[blender.git] / source / blender / src / drawimage.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  */
32
33 #include <math.h>
34 #include <string.h>
35
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #ifdef WIN32
41 #include <io.h>
42 #else
43 #include <unistd.h>
44 #endif   
45 #include "MEM_guardedalloc.h"
46
47 #include "BLI_arithb.h"
48 #include "BLI_blenlib.h"
49
50 #include "IMB_imbuf.h"
51 #include "IMB_imbuf_types.h"
52
53 #include "DNA_brush_types.h"
54 #include "DNA_camera_types.h"
55 #include "DNA_color_types.h"
56 #include "DNA_image_types.h"
57 #include "DNA_mesh_types.h"
58 #include "DNA_meshdata_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_packedFile_types.h"
61 #include "DNA_scene_types.h"
62 #include "DNA_screen_types.h"
63 #include "DNA_space_types.h"
64 #include "DNA_texture_types.h"
65 #include "DNA_userdef_types.h"
66
67 #include "BKE_brush.h"
68 #include "BKE_colortools.h"
69 #include "BKE_utildefines.h"
70 #include "BKE_global.h"
71 #include "BKE_library.h"
72 #include "BKE_main.h"
73 #include "BKE_mesh.h"
74 #include "BKE_node.h"
75 #include "BKE_image.h"
76 #include "BKE_DerivedMesh.h"
77 #include "BKE_displist.h"
78 #include "BKE_object.h"
79
80 #include "BDR_editface.h"
81 #include "BDR_drawobject.h"
82 #include "BDR_drawmesh.h"
83 #include "BDR_imagepaint.h"
84
85 #include "BIF_cursors.h"
86 #include "BIF_gl.h"
87 #include "BIF_graphics.h"
88 #include "BIF_mywindow.h"
89 #include "BIF_drawimage.h"
90 #include "BIF_resources.h"
91 #include "BIF_interface.h"
92 #include "BIF_interface_icons.h"
93 #include "BIF_editsima.h"
94 #include "BIF_glutil.h"
95 #include "BIF_renderwin.h"
96 #include "BIF_space.h"
97 #include "BIF_screen.h"
98 #include "BIF_toolbox.h"
99 #include "BIF_transform.h"
100
101 #include "BSE_drawipo.h"
102 #include "BSE_filesel.h"
103 #include "BSE_headerbuttons.h"
104 #include "BSE_trans_types.h"
105 #include "BSE_view.h"
106
107 #include "RE_pipeline.h"
108 #include "BMF_Api.h"
109
110 /* Modules used */
111 #include "mydevice.h"
112 #include "blendef.h"
113 #include "butspace.h"  // event codes
114 #include "winlay.h"
115
116 #include "interface.h"  /* bad.... but preview code needs UI info. Will solve... (ton) */
117
118 static unsigned char *alloc_alpha_clone_image(int *width, int *height)
119 {
120         Brush *brush = G.scene->toolsettings->imapaint.brush;
121         Image *image;
122         unsigned int size, alpha;
123         unsigned char *rect, *cp;
124
125         if(!brush || !brush->clone.image)
126                 return NULL;
127         
128         image= brush->clone.image;
129         if(!image->ibuf)
130                 load_image(image, IB_rect, G.sce, G.scene->r.cfra);
131
132         if(!image->ibuf || !image->ibuf->rect)
133                 return NULL;
134
135         rect= MEM_dupallocN(image->ibuf->rect);
136         if(!rect)
137                 return NULL;
138
139         *width= image->ibuf->x;
140         *height= image->ibuf->y;
141
142         size= (*width)*(*height);
143         alpha= (unsigned char)255*brush->clone.alpha;
144         cp= rect;
145
146         while(size-- > 0) {
147                 cp[3]= alpha;
148                 cp += 4;
149         }
150
151         return rect;
152 }
153
154 static int image_preview_active(ScrArea *sa, float *xim, float *yim)
155 {
156         SpaceImage *sima= sa->spacedata.first;
157         
158         /* only when compositor shows, and image handler set */
159         if(sima->image == (Image *)find_id("IM", "Viewer Node")) {
160                 short a;
161         
162                 for(a=0; a<SPACE_MAXHANDLER; a+=2) {
163                         if(sima->blockhandler[a] == IMAGE_HANDLER_PREVIEW) {
164                                 if(xim) *xim= (G.scene->r.size*G.scene->r.xsch)/100;
165                                 if(yim) *yim= (G.scene->r.size*G.scene->r.ysch)/100;
166                                 return 1;
167                         }
168                 }
169         }
170         return 0;
171 }
172
173
174 /**
175  * Sets up the fields of the View2D member of the SpaceImage struct
176  * This routine can be called in two modes:
177  * mode == 'f': float mode (0.0 - 1.0)
178  * mode == 'p': pixel mode (0 - size)
179  *
180  * @param     sima  the image space to update
181  * @param     mode  the mode to use for the update
182  * @return    void
183  *   
184  */
185 void calc_image_view(SpaceImage *sima, char mode)
186 {
187         float xim=256, yim=256;
188         float x1, y1;
189         float zoom;
190         
191         if(image_preview_active(curarea, &xim, &yim));
192         else if(sima->image) {
193                 if(sima->image->ibuf) {
194                         xim= sima->image->ibuf->x;
195                         yim= sima->image->ibuf->y;
196                 }
197                 else if( BLI_streq(sima->image->id.name+2, "Render Result") ) {
198                         /* not very important, just nice */
199                         xim= (G.scene->r.xsch*G.scene->r.size)/100;
200                         yim= (G.scene->r.ysch*G.scene->r.size)/100;
201                 }
202         }
203                 
204         sima->v2d.tot.xmin= 0;
205         sima->v2d.tot.ymin= 0;
206         sima->v2d.tot.xmax= xim;
207         sima->v2d.tot.ymax= yim;
208         
209         sima->v2d.mask.xmin= sima->v2d.mask.ymin= 0;
210         sima->v2d.mask.xmax= curarea->winx;
211         sima->v2d.mask.ymax= curarea->winy;
212
213
214         /* Which part of the image space do we see? */
215         /* Same calculation as in lrectwrite: area left and down*/
216         x1= curarea->winrct.xmin+(curarea->winx-sima->zoom*xim)/2;
217         y1= curarea->winrct.ymin+(curarea->winy-sima->zoom*yim)/2;
218
219         x1-= sima->zoom*sima->xof;
220         y1-= sima->zoom*sima->yof;
221
222         /* float! */
223         zoom= sima->zoom;
224         
225         /* relative display right */
226         sima->v2d.cur.xmin= ((curarea->winrct.xmin - (float)x1)/zoom);
227         sima->v2d.cur.xmax= sima->v2d.cur.xmin + ((float)curarea->winx/zoom);
228         
229         /* relative display left */
230         sima->v2d.cur.ymin= ((curarea->winrct.ymin-(float)y1)/zoom);
231         sima->v2d.cur.ymax= sima->v2d.cur.ymin + ((float)curarea->winy/zoom);
232         
233         if(mode=='f') {         
234                 sima->v2d.cur.xmin/= xim;
235                 sima->v2d.cur.xmax/= xim;
236                 sima->v2d.cur.ymin/= yim;
237                 sima->v2d.cur.ymax/= yim;
238         }
239 }
240
241 /* check for facelesect, and set active image */
242 void what_image(SpaceImage *sima)
243 {
244         TFace *activetf;
245         Mesh *me;
246                 
247         if(sima->mode==SI_TEXTURE) {
248                 
249                 if(sima->image && BLI_streq(sima->image->id.name+2, "Render Result")) {
250                         if(sima->image->ibuf==NULL) {
251                                 RenderResult rres;
252                                 
253                                 /* make ibuf if needed, and initialize it */
254                                 RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
255                                 if(rres.rectf || rres.rect32) {
256                                         ImBuf *ibuf= sima->image->ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, 0, 0);
257                                         
258                                         ibuf->x= rres.rectx;
259                                         ibuf->y= rres.recty;
260                                         ibuf->rect= rres.rect32;
261                                         ibuf->rect_float= rres.rectf;
262                                         
263                                         sima->image->ok= 1;
264                                 }
265                         }
266                 }
267                 else if((G.f & G_FACESELECT)) {
268                         
269                         sima->image= NULL;
270                         me= get_mesh(OBACT);
271                         activetf = get_active_tface();
272                         
273                         if(me && me->tface && activetf && activetf->mode & TF_TEX) {
274                                 sima->image= activetf->tpage;
275                                 
276                                 if(sima->flag & SI_EDITTILE);
277                                 else sima->curtile= activetf->tile;
278                                 
279                                 if(sima->image) {
280                                         if(activetf->mode & TF_TILES)
281                                                 sima->image->tpageflag |= IMA_TILES;
282                                         else sima->image->tpageflag &= ~IMA_TILES;
283                                 }
284                         }
285                 }
286                 
287         }
288 }
289
290 /* called to assign images to UV faces */
291 void image_changed(SpaceImage *sima, int dotile)
292 {
293         TFace *tface;
294         Mesh *me;
295         int a;
296
297         if(sima->image==NULL)
298                 sima->flag &= ~SI_DRAWTOOL;
299         
300         if(sima->mode==SI_TEXTURE) {
301                 
302                 if(G.f & G_FACESELECT) {
303                         
304                         /* exception images, name rules are actually weak... */
305                         if(sima->image) {
306                                 if(BLI_streq(sima->image->id.name+2, "Render Result"))
307                                         return;
308                                 if(BLI_streq(sima->image->id.name+2, "Composite"))
309                                         return;
310                         }
311                         
312                         me= get_mesh(OBACT);
313                         if(me && me->tface) {
314                                 
315                                 tface= me->tface;
316                                 a= me->totface;
317                                 while(a--) {
318                                         if(tface->flag & TF_SELECT) {
319                                                 
320                                                 if(dotile==2) {
321                                                         tface->mode &= ~TF_TILES;
322                                                 }
323                                                 else {
324                                                         tface->tpage= sima->image;
325                                                         tface->mode |= TF_TEX;
326                                                 
327                                                         if(dotile) tface->tile= sima->curtile;
328                                                 }
329                                                 
330                                                 if(sima->image) {
331                                                         if(sima->image->tpageflag & IMA_TILES) tface->mode |= TF_TILES;
332                                                         else tface->mode &= ~TF_TILES;
333                                                 
334                                                         if(sima->image->id.us==0) sima->image->id.us= 1;
335                                                 }
336                                         }
337                                         tface++;
338                                 }
339
340                                 object_uvs_changed(OBACT);
341                                 allqueue(REDRAWBUTSEDIT, 0);
342                         }
343                 }
344         }
345 }
346
347
348 void uvco_to_areaco(float *vec, short *mval)
349 {
350         float x, y;
351
352         mval[0]= IS_CLIPPED;
353         
354         x= (vec[0] - G.v2d->cur.xmin)/(G.v2d->cur.xmax-G.v2d->cur.xmin);
355         y= (vec[1] - G.v2d->cur.ymin)/(G.v2d->cur.ymax-G.v2d->cur.ymin);
356
357         if(x>=0.0 && x<=1.0) {
358                 if(y>=0.0 && y<=1.0) {          
359                         mval[0]= G.v2d->mask.xmin + x*(G.v2d->mask.xmax-G.v2d->mask.xmin);
360                         mval[1]= G.v2d->mask.ymin + y*(G.v2d->mask.ymax-G.v2d->mask.ymin);
361                 }
362         }
363 }
364
365 void uvco_to_areaco_noclip(float *vec, int *mval)
366 {
367         float x, y;
368
369         mval[0]= IS_CLIPPED;
370         
371         x= (vec[0] - G.v2d->cur.xmin)/(G.v2d->cur.xmax-G.v2d->cur.xmin);
372         y= (vec[1] - G.v2d->cur.ymin)/(G.v2d->cur.ymax-G.v2d->cur.ymin);
373
374         x= G.v2d->mask.xmin + x*(G.v2d->mask.xmax-G.v2d->mask.xmin);
375         y= G.v2d->mask.ymin + y*(G.v2d->mask.ymax-G.v2d->mask.ymin);
376         
377         mval[0]= x;
378         mval[1]= y;
379 }
380
381 void draw_tfaces(void)
382 {
383         TFace *tface,*activetface = NULL;
384         MFace *mface,*activemface = NULL;
385         Mesh *me;
386         int a;
387         char col1[4], col2[4];
388         float pointsize= BIF_GetThemeValuef(TH_VERTEX_SIZE);
389         
390         if(G.f & G_FACESELECT) {
391                 me= get_mesh((G.scene->basact) ? (G.scene->basact->object) : 0);
392                 if(me && me->tface) {
393                         calc_image_view(G.sima, 'f');   /* float */
394                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
395                         glLoadIdentity();
396                         
397                         /* draw shadow mesh */
398                         if((G.sima->flag & SI_DRAWSHADOW) && !(G.obedit==OBACT)){
399                                 int dmNeedsFree;
400                                 DerivedMesh *dm = mesh_get_derived_final(OBACT, &dmNeedsFree);
401
402                                 glColor3ub(112, 112, 112);
403                                 if (dm->drawUVEdges) dm->drawUVEdges(dm);
404
405                                 if (dmNeedsFree) dm->release(dm);
406                         }
407                         else if(G.sima->flag & SI_DRAWSHADOW){          
408                                 tface= me->tface;
409                                 mface= me->mface;
410                                 a= me->totface;                 
411                                 while(a--) {
412                                         if(!(tface->flag & TF_HIDE)) {
413                                                 glColor3ub(112, 112, 112);
414                                                 glBegin(GL_LINE_LOOP);
415                                                 glVertex2fv(tface->uv[0]);
416                                                 glVertex2fv(tface->uv[1]);
417                                                 glVertex2fv(tface->uv[2]);
418                                                 if(mface->v4) glVertex2fv(tface->uv[3]);
419                                                 glEnd();
420                                         } 
421                                         tface++;
422                                         mface++;                                        
423                                 }
424                         }
425                         
426                         /* draw transparent faces */
427                         if(G.f & G_DRAWFACES) {
428                                 BIF_GetThemeColor4ubv(TH_FACE, col1);
429                                 BIF_GetThemeColor4ubv(TH_FACE_SELECT, col2);
430                                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
431                                 glEnable(GL_BLEND);
432                                 tface= me->tface;
433                                 mface= me->mface;
434                                 a= me->totface;                 
435                                 while(a--) {
436                                         if(tface->flag & TF_SELECT) {
437                                                 if(!(~tface->flag & (TF_SEL1|TF_SEL2|TF_SEL3)) &&
438                                                    (!mface->v4 || tface->flag & TF_SEL4))
439                                                         glColor4ubv(col2);
440                                                 else
441                                                         glColor4ubv(col1);
442                                                         
443                                                 glBegin(mface->v4?GL_QUADS:GL_TRIANGLES);
444                                                         glVertex2fv(tface->uv[0]);
445                                                         glVertex2fv(tface->uv[1]);
446                                                         glVertex2fv(tface->uv[2]);
447                                                         if(mface->v4) glVertex2fv(tface->uv[3]);
448                                                 glEnd();
449                                         }
450                                         tface++;
451                                         mface++;                                        
452                                 }
453                                 glDisable(GL_BLEND);
454                         }
455
456
457                         tface= me->tface;
458                         mface= me->mface;
459                         a= me->totface;
460                         while(a--) {
461                                 if(tface->flag & TF_SELECT) {
462                                         if(tface->flag & TF_ACTIVE){
463                                                 activetface= tface; 
464                                                 activemface= mface; 
465                                         }
466
467                                         cpack(0x0);
468                                         glBegin(GL_LINE_LOOP);
469                                                 glVertex2fv(tface->uv[0]);
470                                                 glVertex2fv(tface->uv[1]);
471                                                 glVertex2fv(tface->uv[2]);
472                                                 if(mface->v4) glVertex2fv(tface->uv[3]);
473                                         glEnd();
474                                 
475                                         setlinestyle(2);
476                                         cpack(0xFFFFFF);
477                                         glBegin(GL_LINE_STRIP);
478                                                 glVertex2fv(tface->uv[0]);
479                                                 glVertex2fv(tface->uv[1]);
480                                         glEnd();
481
482                                         glBegin(GL_LINE_STRIP);
483                                                 glVertex2fv(tface->uv[0]);
484                                                 if(mface->v4) glVertex2fv(tface->uv[3]);
485                                                 else glVertex2fv(tface->uv[2]);
486                                         glEnd();
487         
488                                         glBegin(GL_LINE_STRIP);
489                                                 glVertex2fv(tface->uv[1]);
490                                                 glVertex2fv(tface->uv[2]);
491                                                 if(mface->v4) glVertex2fv(tface->uv[3]);
492                                         glEnd();
493                                         setlinestyle(0);
494                                 }
495                                         
496                                 tface++;
497                                 mface++;
498                         }
499
500                         /* draw active face edges */
501                         if (activetface){
502                                 /* colors: R=u G=v */
503
504                                 setlinestyle(2);
505                                 tface=activetface; 
506                                 mface=activemface; 
507
508                                 cpack(0x0);
509                                 glBegin(GL_LINE_LOOP);
510                                 glVertex2fv(tface->uv[0]);
511                                         glVertex2fv(tface->uv[1]);
512                                         glVertex2fv(tface->uv[2]);
513                                         if(mface->v4) glVertex2fv(tface->uv[3]);
514                                 glEnd();
515                                         
516                                 cpack(0xFF00);
517                                 glBegin(GL_LINE_STRIP);
518                                         glVertex2fv(tface->uv[0]);
519                                         glVertex2fv(tface->uv[1]);
520                                 glEnd();
521
522                                 cpack(0xFF);
523                                 glBegin(GL_LINE_STRIP);
524                                         glVertex2fv(tface->uv[0]);
525                                         if(mface->v4) glVertex2fv(tface->uv[3]);
526                                         else glVertex2fv(tface->uv[2]);
527                                 glEnd();
528
529                                 cpack(0xFFFFFF);
530                                 glBegin(GL_LINE_STRIP);
531                                         glVertex2fv(tface->uv[1]);
532                                         glVertex2fv(tface->uv[2]);
533                                         if(mface->v4) glVertex2fv(tface->uv[3]);
534                                 glEnd();
535                                 
536                                 setlinestyle(0);
537                         }
538
539             /* unselected uv's */
540                         BIF_ThemeColor(TH_VERTEX);
541                         glPointSize(pointsize);
542
543                         bglBegin(GL_POINTS);
544                         tface= me->tface;
545                         mface= me->mface;
546                         a= me->totface;
547                         while(a--) {
548                                 if(tface->flag & TF_SELECT) {
549                                         
550                                         if(tface->flag & TF_SEL1); else bglVertex2fv(tface->uv[0]);
551                                         if(tface->flag & TF_SEL2); else bglVertex2fv(tface->uv[1]);
552                                         if(tface->flag & TF_SEL3); else bglVertex2fv(tface->uv[2]);
553                                         if(mface->v4) {
554                                                 if(tface->flag & TF_SEL4); else bglVertex2fv(tface->uv[3]);
555                                         }
556                                 }
557                                 tface++;
558                                 mface++;
559                         }
560                         bglEnd();
561
562                         /* pinned uv's */
563                         /* give odd pointsizes odd pin pointsizes */
564                 glPointSize(pointsize*2 + (((int)pointsize % 2)? (-1): 0));
565                         cpack(0xFF);
566
567                         bglBegin(GL_POINTS);
568                         tface= me->tface;
569                         mface= me->mface;
570                         a= me->totface;
571                         while(a--) {
572                                 if(tface->flag & TF_SELECT) {
573                                         
574                                         if(tface->unwrap & TF_PIN1) bglVertex2fv(tface->uv[0]);
575                                         if(tface->unwrap & TF_PIN2) bglVertex2fv(tface->uv[1]);
576                                         if(tface->unwrap & TF_PIN3) bglVertex2fv(tface->uv[2]);
577                                         if(mface->v4) {
578                                                 if(tface->unwrap & TF_PIN4) bglVertex2fv(tface->uv[3]);
579                                         }
580                                 }
581                                 tface++;
582                                 mface++;
583                         }
584                         bglEnd();
585
586                         /* selected uv's */
587                         BIF_ThemeColor(TH_VERTEX_SELECT);
588                 glPointSize(pointsize);
589
590                         bglBegin(GL_POINTS);
591                         tface= me->tface;
592                         mface= me->mface;
593                         a= me->totface;
594                         while(a--) {
595                                 if(tface->flag & TF_SELECT) {
596                                         
597                                         if(tface->flag & TF_SEL1) bglVertex2fv(tface->uv[0]);
598                                         if(tface->flag & TF_SEL2) bglVertex2fv(tface->uv[1]);
599                                         if(tface->flag & TF_SEL3) bglVertex2fv(tface->uv[2]);
600                                         if(mface->v4) {
601                                                 if(tface->flag & TF_SEL4) bglVertex2fv(tface->uv[3]);
602                                         }
603                                 }
604                                 tface++;
605                                 mface++;
606                         }
607                         bglEnd();
608                 }
609         }
610         glPointSize(1.0);
611 }
612
613 static unsigned int *get_part_from_ibuf(ImBuf *ibuf, short startx, short starty, short endx, short endy)
614 {
615         unsigned int *rt, *rp, *rectmain;
616         short y, heigth, len;
617
618         /* the right offset in rectot */
619
620         rt= ibuf->rect+ (starty*ibuf->x+ startx);
621
622         len= (endx-startx);
623         heigth= (endy-starty);
624
625         rp=rectmain= MEM_mallocN(heigth*len*sizeof(int), "rect");
626         
627         for(y=0; y<heigth; y++) {
628                 memcpy(rp, rt, len*4);
629                 rt+= ibuf->x;
630                 rp+= len;
631         }
632         return rectmain;
633 }
634
635 static void draw_image_transform(ImBuf *ibuf)
636 {
637         if(G.moving) {
638                 float aspx, aspy, center[3];
639
640         BIF_drawConstraint();
641
642                 if(ibuf==0 || ibuf->rect==0 || ibuf->x==0 || ibuf->y==0) {
643                         aspx= aspy= 1.0;
644                 }
645                 else {
646                         aspx= 256.0/ibuf->x;
647                         aspy= 256.0/ibuf->y;
648                 }
649
650                 BIF_getPropCenter(center);
651
652                 /* scale and translate the circle into place and draw it */
653                 glPushMatrix();
654                 glScalef(aspx, aspy, 1.0);
655                 glTranslatef((1/aspx)*center[0] - center[0],
656                              (1/aspy)*center[1] - center[1], 0.0);
657
658                 BIF_drawPropCircle();
659
660                 glPopMatrix();
661         }
662 }
663
664 static void draw_image_view_icon(void)
665 {
666         float xPos = 5.0;
667
668         glEnable(GL_BLEND);
669         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
670         
671         if(G.sima->flag & SI_STICKYUVS) {
672                 BIF_icon_draw_aspect(xPos, 5.0, ICON_STICKY2_UVS, 1.0f);
673                 xPos = 25.0;
674         }
675         else if(!(G.sima->flag & SI_LOCALSTICKY)) {
676                 BIF_icon_draw_aspect(xPos, 5.0, ICON_STICKY_UVS, 1.0f);
677                 xPos = 25.0;
678         }
679
680         if(G.sima->flag & SI_SELACTFACE) {
681                 BIF_icon_draw_aspect(xPos, 5.0, ICON_DRAW_UVFACES, 1.0f);
682         }
683         
684         glBlendFunc(GL_ONE,  GL_ZERO); 
685         glDisable(GL_BLEND);
686 }
687
688 static void draw_image_view_tool(void)
689 {
690         ToolSettings *settings= G.scene->toolsettings;
691         Brush *brush= settings->imapaint.brush;
692         short mval[2];
693         float radius;
694         int draw= 0;
695
696         if(brush) {
697                 if(settings->imapaint.flag & IMAGEPAINT_DRAWING) {
698                         if(settings->imapaint.flag & IMAGEPAINT_DRAW_TOOL_DRAWING)
699                                 draw= 1;
700                 }
701                 else if(settings->imapaint.flag & IMAGEPAINT_DRAW_TOOL)
702                         draw= 1;
703                 
704                 if(draw) {
705                         getmouseco_areawin(mval);
706
707                         radius= brush->size*G.sima->zoom/2;
708                         fdrawXORcirc(mval[0], mval[1], radius);
709
710                         if (brush->innerradius != 1.0) {
711                                 radius *= brush->innerradius;
712                                 fdrawXORcirc(mval[0], mval[1], radius);
713                         }
714                 }
715         }
716 }
717
718 /* ************ panel stuff ************* */
719
720 // button define is local, only events defined here possible
721 #define B_TRANS_IMAGE   1
722
723 /* is used for both read and write... */
724 static void image_editvertex_buts(uiBlock *block)
725 {
726         static float ocent[2];
727         float cent[2]= {0.0, 0.0};
728         int imx, imy;
729         int i, nactive= 0, step, digits;
730         Mesh *me;
731         
732         if( is_uv_tface_editing_allowed_silent()==0 ) return;
733         me= get_mesh(OBACT);
734         
735         if (G.sima->image && G.sima->image->ibuf) {
736                 imx= G.sima->image->ibuf->x;
737                 imy= G.sima->image->ibuf->y;
738         } else
739                 imx= imy= 256;
740         
741         for (i=0; i<me->totface; i++) {
742                 MFace *mf= &((MFace*) me->mface)[i];
743                 TFace *tf= &((TFace*) me->tface)[i];
744                 
745                 if (!(tf->flag & TF_SELECT))
746                         continue;
747                 
748                 if (tf->flag & TF_SEL1) {
749                         cent[0]+= tf->uv[0][0];
750                         cent[1]+= tf->uv[0][1];
751                         nactive++;
752                 }
753                 if (tf->flag & TF_SEL2) {
754                         cent[0]+= tf->uv[1][0];
755                         cent[1]+= tf->uv[1][1];
756                         nactive++;
757                 }
758                 if (tf->flag & TF_SEL3) {
759                         cent[0]+= tf->uv[2][0];
760                         cent[1]+= tf->uv[2][1];
761                         nactive++;
762                 }
763                 if (mf->v4 && (tf->flag & TF_SEL4)) {
764                         cent[0]+= tf->uv[3][0];
765                         cent[1]+= tf->uv[3][1];
766                         nactive++;
767                 }
768         }
769                 
770         if(block) {     // do the buttons
771                 if (nactive) {
772                         ocent[0]= cent[0]/nactive;
773                         ocent[1]= cent[1]/nactive;
774                         if (G.sima->flag & SI_COORDFLOATS) {
775                                 step= 1;
776                                 digits= 3;
777                         }
778                         else {
779                                 ocent[0] *= imx;
780                                 ocent[1] *= imy;
781                                 step= 100;
782                                 digits= 2;
783                         }
784                         
785                         uiDefBut(block, LABEL, 0, "UV Vertex:",10,55,302,19,0,0,0,0,0,"");
786                         uiBlockBeginAlign(block);
787                         if(nactive==1) {
788                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Vertex X:",       10, 35, 290, 19, &ocent[0], -10*imx, 10.0*imx, step, digits, "");
789                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Vertex Y:",       10, 15, 290, 19, &ocent[1], -10*imy, 10.0*imy, step, digits, "");
790                         }
791                         else {
792                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Median X:",       10, 35, 290, 19, &ocent[0], -10*imx, 10.0*imx, step, digits, "");
793                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Median Y:",       10, 15, 290, 19, &ocent[1], -10*imy, 10.0*imy, step, digits, "");
794                         }
795                         uiBlockEndAlign(block);
796                 }
797         }
798         else {  // apply event
799                 float delta[2];
800                 
801                 cent[0]= cent[0]/nactive;
802                 cent[1]= cent[1]/nactive;
803                         
804                 if (G.sima->flag & SI_COORDFLOATS) {
805                         delta[0]= ocent[0]-cent[0];
806                         delta[1]= ocent[1]-cent[1];
807                 }
808                 else {
809                         delta[0]= ocent[0]/imx - cent[0];
810                         delta[1]= ocent[1]/imy - cent[1];
811                 }
812
813                 for (i=0; i<me->totface; i++) {
814                         MFace *mf= &((MFace*) me->mface)[i];
815                         TFace *tf= &((TFace*) me->tface)[i];
816                 
817                         if (!(tf->flag & TF_SELECT))
818                                 continue;
819                 
820                         if (tf->flag & TF_SEL1) {
821                                 tf->uv[0][0]+= delta[0];
822                                 tf->uv[0][1]+= delta[1];
823                         }
824                         if (tf->flag & TF_SEL2) {
825                                 tf->uv[1][0]+= delta[0];
826                                 tf->uv[1][1]+= delta[1];
827                         }
828                         if (tf->flag & TF_SEL3) {
829                                 tf->uv[2][0]+= delta[0];
830                                 tf->uv[2][1]+= delta[1];
831                         }
832                         if (mf->v4 && (tf->flag & TF_SEL4)) {
833                                 tf->uv[3][0]+= delta[0];
834                                 tf->uv[3][1]+= delta[1];
835                         }
836                 }
837                         
838                 allqueue(REDRAWVIEW3D, 0);
839                 allqueue(REDRAWIMAGE, 0);
840         }
841 }
842
843
844 void do_imagebuts(unsigned short event)
845 {
846         ToolSettings *settings= G.scene->toolsettings;
847
848         switch(event) {
849         case B_TRANS_IMAGE:
850                 image_editvertex_buts(NULL);
851                 break;
852
853         case B_SIMAGEDRAW:
854                 if(G.f & G_FACESELECT) {
855                         make_repbind(G.sima->image);
856                         image_changed(G.sima, 1);
857                 }
858                 allqueue(REDRAWVIEW3D, 0);
859                 allqueue(REDRAWIMAGE, 0);
860                 break;
861
862         case B_SIMAGEDRAW1:
863                 image_changed(G.sima, 2);               /* 2: only tileflag */
864                 allqueue(REDRAWVIEW3D, 0);
865                 allqueue(REDRAWIMAGE, 0);
866                 break;
867                 
868         case B_TWINANIM:
869                 {
870                         Image *ima;
871                         int nr;
872
873                         ima = G.sima->image;
874                         if (ima) {
875                                 if(ima->flag & IMA_TWINANIM) {
876                                         nr= ima->xrep*ima->yrep;
877                                         if(ima->twsta>=nr) ima->twsta= 1;
878                                         if(ima->twend>=nr) ima->twend= nr-1;
879                                         if(ima->twsta>ima->twend) ima->twsta= 1;
880                                         allqueue(REDRAWIMAGE, 0);
881                                 }
882                         }
883                 }
884                 break;
885
886         case B_SIMACLONEBROWSE:
887                 if (settings->imapaint.brush)
888                         if (brush_clone_image_set_nr(settings->imapaint.brush, G.sima->menunr))
889                                 allqueue(REDRAWIMAGE, 0);
890                 break;
891                 
892         case B_SIMACLONEDELETE:
893                 if (settings->imapaint.brush)
894                         if (brush_clone_image_delete(settings->imapaint.brush))
895                                 allqueue(REDRAWIMAGE, 0);
896                 break;
897
898         case B_SIMABRUSHCHANGE:
899                 allqueue(REDRAWIMAGE, 0);
900                 allqueue(REDRAWBUTSEDIT, 0);
901                 break;
902                 
903         case B_SIMACURVES:
904                 curvemapping_do_image(G.sima->cumap, G.sima->image);
905                 allqueue(REDRAWIMAGE, 0);
906                 break;
907                 
908         case B_SIMARANGE:
909                 curvemapping_set_black_white(G.sima->cumap, NULL, NULL);
910                 curvemapping_do_image(G.sima->cumap, G.sima->image);
911                 allqueue(REDRAWIMAGE, 0);
912                 break;
913         
914         case B_SIMABRUSHBROWSE:
915                 if(G.sima->menunr==-2) {
916                         activate_databrowse((ID*)settings->imapaint.brush, ID_BR, 0, B_SIMABRUSHBROWSE, &G.sima->menunr, do_global_buttons);
917                         break;
918                 }
919                 else if(G.sima->menunr < 0) break;
920                         
921                 if(brush_set_nr(&settings->imapaint.brush, G.sima->menunr)) {
922                         BIF_undo_push("Browse Brush");
923                         allqueue(REDRAWBUTSEDIT, 0);
924                         allqueue(REDRAWIMAGE, 0);
925                 }
926                 break;
927         case B_SIMABRUSHDELETE:
928                 if(brush_delete(&settings->imapaint.brush)) {
929                         BIF_undo_push("Unlink Brush");
930                         allqueue(REDRAWIMAGE, 0);
931                         allqueue(REDRAWBUTSEDIT, 0);
932                 }
933                 break;
934         case B_KEEPDATA:
935                 brush_toggle_fake_user(settings->imapaint.brush);
936                 allqueue(REDRAWIMAGE, 0);
937                 allqueue(REDRAWBUTSEDIT, 0);
938                 break;
939         case B_SIMABRUSHLOCAL:
940                 if(settings->imapaint.brush && settings->imapaint.brush->id.lib) {
941                         if(okee("Make local")) {
942                                 make_local_brush(settings->imapaint.brush);
943                                 allqueue(REDRAWIMAGE, 0);
944                                 allqueue(REDRAWBUTSEDIT, 0);
945                         }
946                 }
947                 break;
948         case B_SIMABTEXBROWSE:
949                 if(settings->imapaint.brush) {
950                         Brush *brush= settings->imapaint.brush;
951
952                         if(G.sima->menunr==-2) {
953                                 MTex *mtex= brush->mtex[brush->texact];
954                                 ID *id= (ID*)((mtex)? mtex->tex: NULL);
955                                 activate_databrowse(id, ID_TE, 0, B_SIMABTEXBROWSE, &G.sima->menunr, do_global_buttons);
956                                 break;
957                         }
958                         else if(G.sima->menunr < 0) break;
959                                 
960                         if(brush_texture_set_nr(brush, G.sima->menunr)) {
961                                 BIF_undo_push("Browse Brush Texture");
962                                 allqueue(REDRAWBUTSSHADING, 0);
963                                 allqueue(REDRAWBUTSEDIT, 0);
964                                 allqueue(REDRAWIMAGE, 0);
965                         }
966                 }
967                 break;
968         case B_SIMABTEXDELETE:
969                 if(settings->imapaint.brush) {
970                         if (brush_texture_delete(settings->imapaint.brush)) {
971                                 BIF_undo_push("Unlink Brush Texture");
972                                 allqueue(REDRAWBUTSSHADING, 0);
973                                 allqueue(REDRAWBUTSEDIT, 0);
974                                 allqueue(REDRAWIMAGE, 0);
975                         }
976                 }
977                 break;
978         }
979 }
980
981 static void image_panel_properties(short cntrl) // IMAGE_HANDLER_PROPERTIES
982 {
983         uiBlock *block;
984
985         block= uiNewBlock(&curarea->uiblocks, "image_panel_properties", UI_EMBOSS, UI_HELV, curarea->win);
986         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
987         uiSetPanelHandler(IMAGE_HANDLER_PROPERTIES);  // for close and esc
988         if(uiNewPanel(curarea, block, "Properties", "Image", 10, 10, 318, 204)==0)
989                 return;
990
991         if (G.sima->image && G.sima->image->ibuf) {
992                 ImBuf *ibuf= G.sima->image->ibuf;
993                 char str[64];
994
995                 sprintf(str, "Image: size %d x %d", ibuf->x, ibuf->y);
996                 if(ibuf->rect_float) {
997                         if(ibuf->depth==32)
998                                 strcat(str, " RGBA float");
999                         else
1000                                 strcat(str, " RGB float");
1001                 }
1002                 else {
1003                         if(ibuf->depth==32)
1004                                 strcat(str, " RGBA byte");
1005                         else
1006                                 strcat(str, " RGB byte");
1007                 }
1008                 if(ibuf->zbuf || ibuf->zbuf_float)
1009                         strcat(str, " + Z");
1010                 
1011                 uiDefBut(block, LABEL, B_NOP, str,              10,180,300,19, 0, 0, 0, 0, 0, "");
1012
1013                 uiBlockBeginAlign(block);
1014                 uiDefButBitS(block, TOG, IMA_TWINANIM, B_TWINANIM, "Anim", 10,150,140,19, &G.sima->image->tpageflag, 0, 0, 0, 0, "Toggles use of animated texture");
1015                 uiDefButS(block, NUM, B_TWINANIM, "Start:",             10,130,140,19, &G.sima->image->twsta, 0.0, 128.0, 0, 0, "Displays the start frame of an animated texture");
1016                 uiDefButS(block, NUM, B_TWINANIM, "End:",               10,110,140,19, &G.sima->image->twend, 0.0, 128.0, 0, 0, "Displays the end frame of an animated texture");
1017                 uiDefButS(block, NUM, B_NOP, "Speed",                           10,90,140,19, &G.sima->image->animspeed, 1.0, 100.0, 0, 0, "Displays Speed of the animation in frames per second");
1018                 uiBlockEndAlign(block);
1019
1020                 uiBlockBeginAlign(block);
1021                 uiDefButBitS(block, TOG, IMA_TILES, B_SIMAGEDRAW1, "Tiles",     160,150,140,19, &G.sima->image->tpageflag, 0, 0, 0, 0, "Toggles use of tilemode for faces");
1022                 uiDefButS(block, NUM, B_SIMAGEDRAW, "X:",               160,130,70,19, &G.sima->image->xrep, 1.0, 16.0, 0, 0, "Sets the degree of repetition in the X direction");
1023                 uiDefButS(block, NUM, B_SIMAGEDRAW, "Y:",               230,130,70,19, &G.sima->image->yrep, 1.0, 16.0, 0, 0, "Sets the degree of repetition in the Y direction");
1024                 uiBlockBeginAlign(block);
1025         }
1026
1027         image_editvertex_buts(block);
1028 }
1029
1030 static void image_panel_paint(short cntrl)      // IMAGE_HANDLER_PROPERTIES
1031 {
1032         /* B_SIMABRUSHCHANGE only redraws and eats the mouse messages  */
1033         /* so that LEFTMOUSE does not 'punch' through the floating panel */
1034         /* B_SIMANOTHING */
1035         ToolSettings *settings= G.scene->toolsettings;
1036         Brush *brush= settings->imapaint.brush;
1037         uiBlock *block;
1038         ID *id;
1039         int yco, xco, butw;
1040
1041         block= uiNewBlock(&curarea->uiblocks, "image_panel_paint", UI_EMBOSS, UI_HELV, curarea->win);
1042         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1043         uiSetPanelHandler(IMAGE_HANDLER_PAINT);  // for close and esc
1044         if(uiNewPanel(curarea, block, "Image Paint", "Image", 10, 230, 318, 204)==0)
1045                 return;
1046
1047         yco= 160;
1048
1049         uiBlockBeginAlign(block);
1050         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Draw",                0  ,yco,80,19, &settings->imapaint.tool, 7.0, PAINT_TOOL_DRAW, 0, 0, "Draw brush");
1051         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Soften",              80 ,yco,80,19, &settings->imapaint.tool, 7.0, PAINT_TOOL_SOFTEN, 0, 0, "Soften brush");
1052         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Smear",               160,yco,80,19, &settings->imapaint.tool, 7.0, PAINT_TOOL_SMEAR, 0, 0, "Smear brush");   
1053         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Clone",               240,yco,80,19, &settings->imapaint.tool, 7.0, PAINT_TOOL_CLONE, 0, 0, "Clone brush, use RMB to drag source image");     
1054         uiBlockEndAlign(block);
1055         yco -= 30;
1056
1057         uiBlockSetCol(block, TH_BUT_SETTING2);
1058         id= (ID*)settings->imapaint.brush;
1059         xco= std_libbuttons(block, 0, yco, 0, NULL, B_SIMABRUSHBROWSE, ID_BR, 0, id, NULL, &(G.sima->menunr), 0, B_SIMABRUSHLOCAL, B_SIMABRUSHDELETE, 0, B_KEEPDATA);
1060         uiBlockSetCol(block, TH_AUTO);
1061
1062         if(brush && !brush->id.lib) {
1063                 butw= 320-(xco+10);
1064
1065                 uiDefButS(block, MENU, B_SIMANOTHING, "Mix %x0|Add %x1|Subtract %x2|Multiply %x3|Lighten %x4|Darken %x5", xco+10,yco,butw,19, &brush->blend, 0, 0, 0, 0, "Blending method for applying brushes");
1066
1067                 uiDefButBitS(block, TOG|BIT, BRUSH_TORUS, B_SIMABRUSHCHANGE, "Wrap",    xco+10,yco-25,butw,19, &brush->flag, 0, 0, 0, 0, "Enables torus wrapping");
1068
1069                 uiBlockBeginAlign(block);
1070                 uiDefButBitS(block, TOG|BIT, BRUSH_AIRBRUSH, B_SIMABRUSHCHANGE, "Airbrush",     xco+10,yco-50,butw,19, &brush->flag, 0, 0, 0, 0, "Keep applying paint effect while holding mouse (spray)");
1071                 uiDefButF(block, NUM, B_SIMANOTHING, "Rate ", xco+10,yco-70,butw,19, &brush->rate, 0.01, 1.0, 0, 0, "Number of paints per second for Airbrush");
1072                 uiBlockEndAlign(block);
1073
1074                 yco -= 25;
1075
1076                 uiBlockBeginAlign(block);
1077                 uiDefButF(block, COL, B_VPCOLSLI, "",                                   0,yco,200,19, brush->rgb, 0, 0, 0, 0, "");
1078                 uiDefButF(block, NUMSLI, B_SIMANOTHING, "Opacity ",             0,yco-20,200,19, &brush->alpha, 0.0, 1.0, 0, 0, "The amount of pressure on the brush");
1079                 uiDefButI(block, NUMSLI, B_SIMANOTHING, "Size ",                0,yco-40,200,19, &brush->size, 1, 200, 0, 0, "The size of the brush");
1080                 uiDefButF(block, NUMSLI, B_SIMANOTHING, "Falloff ",             0,yco-60,200,19, &brush->innerradius, 0.0, 1.0, 0, 0, "The fall off radius of the brush");
1081                 uiDefButF(block, NUMSLI, B_SIMANOTHING, "Spacing ",0,yco-80,200,19, &brush->spacing, 1.0, 100.0, 0, 0, "Repeating paint on %% of brush diameter");
1082                 uiBlockEndAlign(block);
1083
1084                 yco -= 110;
1085
1086                 if(settings->imapaint.tool == PAINT_TOOL_CLONE) {
1087                         id= (ID*)brush->clone.image;
1088                         uiBlockSetCol(block, TH_BUT_SETTING2);
1089                         xco= std_libbuttons(block, 0, yco, 0, NULL, B_SIMACLONEBROWSE, ID_IM, 0, id, 0, &G.sima->menunr, 0, 0, B_SIMACLONEDELETE, 0, 0);
1090                         uiBlockSetCol(block, TH_AUTO);
1091                         if(id) {
1092                                 butw= 320-(xco+5);
1093                                 uiDefButF(block, NUMSLI, B_SIMABRUSHCHANGE, "B ",xco+5,yco,butw,19, &brush->clone.alpha , 0.0, 1.0, 0, 0, "Opacity of clone image display");
1094                         }
1095                 }
1096                 else {
1097                         uiBlockSetCol(block, TH_BUT_SETTING2);
1098                         id= (brush->mtex[0])? (ID*)brush->mtex[0]->tex: NULL;
1099                         xco= std_libbuttons(block, 0, yco, 0, NULL, B_SIMABTEXBROWSE, ID_TE, 0, id, NULL, &(G.sima->menunr), 0, 0, B_SIMABTEXDELETE, 0, 0);
1100                         /*uiDefButBitS(block, TOG|BIT, BRUSH_FIXED_TEX, B_SIMABRUSHCHANGE, "Fixed",     xco+5,yco,butw,19, &brush->flag, 0, 0, 0, 0, "Keep texture origin in fixed position");*/
1101                         uiBlockSetCol(block, TH_AUTO);
1102                 }
1103         }
1104
1105 #if 0
1106                 uiDefButBitS(block, TOG|BIT, IMAGEPAINT_DRAW_TOOL_DRAWING, B_SIMABRUSHCHANGE, "TD", 0,1,50,19, &settings->imapaint.flag.flag, 0, 0, 0, 0, "Enables brush shape while drawing");
1107                 uiDefButBitS(block, TOG|BIT, IMAGEPAINT_DRAW_TOOL, B_SIMABRUSHCHANGE, "TP", 50,1,50,19, &settings->imapaint.flag.flag, 0, 0, 0, 0, "Enables brush shape while not drawing");
1108 #endif
1109 }
1110
1111 static void image_panel_curves_reset(void *cumap_v, void *unused)
1112 {
1113         CurveMapping *cumap = cumap_v;
1114         int a;
1115         
1116         for(a=0; a<CM_TOT; a++)
1117                 curvemap_reset(cumap->cm+a, &cumap->clipr);
1118         
1119         cumap->black[0]=cumap->black[1]=cumap->black[2]= 0.0f;
1120         cumap->white[0]=cumap->white[1]=cumap->white[2]= 1.0f;
1121         curvemapping_set_black_white(cumap, NULL, NULL);
1122         
1123         curvemapping_changed(cumap, 0);
1124         curvemapping_do_image(cumap, G.sima->image);
1125         
1126         allqueue(REDRAWIMAGE, 0);
1127 }
1128
1129
1130 static void image_panel_curves(short cntrl)     // IMAGE_HANDLER_PROPERTIES
1131 {
1132         uiBlock *block;
1133         uiBut *bt;
1134         
1135         block= uiNewBlock(&curarea->uiblocks, "image_panel_curves", UI_EMBOSS, UI_HELV, curarea->win);
1136         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1137         uiSetPanelHandler(IMAGE_HANDLER_CURVES);  // for close and esc
1138         if(uiNewPanel(curarea, block, "Curves", "Image", 10, 450, 318, 204)==0)
1139                 return;
1140         
1141         if (G.sima->image && G.sima->image->ibuf) {
1142                 rctf rect;
1143                 
1144                 if(G.sima->cumap==NULL)
1145                         G.sima->cumap= curvemapping_add(4, 0.0f, 0.0f, 1.0f, 1.0f);
1146                 
1147                 rect.xmin= 110; rect.xmax= 310;
1148                 rect.ymin= 10; rect.ymax= 200;
1149                 curvemap_buttons(block, G.sima->cumap, 'c', B_SIMACURVES, B_SIMAGEDRAW, &rect);
1150                 
1151                 bt=uiDefBut(block, BUT, B_SIMARANGE, "Reset",   10, 160, 90, 19, NULL, 0.0f, 0.0f, 0, 0, "Reset Black/White point and curves");
1152                 uiButSetFunc(bt, image_panel_curves_reset, G.sima->cumap, NULL);
1153                 
1154                 uiBlockBeginAlign(block);
1155                 uiDefButF(block, NUM, B_SIMARANGE, "Min R:",    10, 120, 90, 19, G.sima->cumap->black, -1000.0f, 1000.0f, 10, 2, "Black level");
1156                 uiDefButF(block, NUM, B_SIMARANGE, "Min G:",    10, 100, 90, 19, G.sima->cumap->black+1, -1000.0f, 1000.0f, 10, 2, "Black level");
1157                 uiDefButF(block, NUM, B_SIMARANGE, "Min B:",    10, 80, 90, 19, G.sima->cumap->black+2, -1000.0f, 1000.0f, 10, 2, "Black level");
1158                 
1159                 uiBlockBeginAlign(block);
1160                 uiDefButF(block, NUM, B_SIMARANGE, "Max R:",    10, 50, 90, 19, G.sima->cumap->white, -1000.0f, 1000.0f, 10, 2, "White level");
1161                 uiDefButF(block, NUM, B_SIMARANGE, "Max G:",    10, 30, 90, 19, G.sima->cumap->white+1, -1000.0f, 1000.0f, 10, 2, "White level");
1162                 uiDefButF(block, NUM, B_SIMARANGE, "Max B:",    10, 10, 90, 19, G.sima->cumap->white+2, -1000.0f, 1000.0f, 10, 2, "White level");
1163                 
1164         }
1165 }
1166
1167 /* are there curves? curves visible? and curves do something? */
1168 static int image_curves_active(ScrArea *sa)
1169 {
1170         SpaceImage *sima= sa->spacedata.first;
1171
1172         if(sima->cumap) {
1173                 if(curvemapping_RGBA_does_something(sima->cumap)) {
1174                         short a;
1175                         for(a=0; a<SPACE_MAXHANDLER; a+=2) {
1176                                 if(sima->blockhandler[a] == IMAGE_HANDLER_CURVES)
1177                                         return 1;
1178                         }
1179                 }
1180         }
1181         return 0;
1182 }
1183
1184 void image_preview_event(int event)
1185 {
1186         int exec= 0;
1187         
1188
1189         if(event==0) {
1190                 G.scene->r.scemode &= ~R_COMP_CROP;
1191                 exec= 1;
1192         }
1193         else if(event==2 || (G.scene->r.scemode & R_COMP_CROP)==0) {
1194                 if(image_preview_active(curarea, NULL, NULL)) {
1195                         G.scene->r.scemode |= R_COMP_CROP;
1196                         exec= 1;
1197                 }
1198         }
1199         
1200         if(exec) {
1201                 ScrArea *sa;
1202                 
1203                 ntreeCompositTagGenerators(G.scene->nodetree);
1204         
1205                 for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
1206                         if(sa->spacetype==SPACE_NODE) {
1207                                 addqueue(sa->win, UI_BUT_EVENT, B_NODE_TREE_EXEC);
1208                                 break;
1209                         }
1210                 }
1211         }       
1212 }
1213
1214
1215 /* nothing drawn here, we use it to store values */
1216 static void preview_cb(struct ScrArea *sa, struct uiBlock *block)
1217 {
1218         rctf dispf;
1219         rcti *disprect= &G.scene->r.disprect;
1220         int winx= (G.scene->r.size*G.scene->r.xsch)/100;
1221         int winy= (G.scene->r.size*G.scene->r.ysch)/100;
1222         short mval[2];
1223         
1224         if(G.scene->r.mode & R_BORDER) {
1225                 winx*= (G.scene->r.border.xmax - G.scene->r.border.xmin);
1226                 winy*= (G.scene->r.border.ymax - G.scene->r.border.ymin);
1227         }
1228         
1229         /* while dragging we don't update the rects */
1230         if(block->panel->flag & PNL_SELECT)
1231                 return;
1232         if(get_mbut() & M_MOUSE)
1233                 return;
1234
1235         BLI_init_rctf(&dispf, 15.0f, (block->maxx - block->minx)-15.0f, 15.0f, (block->maxy - block->miny)-15.0f);
1236         ui_graphics_to_window_rct(sa->win, &dispf, disprect);
1237         
1238         /* correction for gla draw */
1239         BLI_translate_rcti(disprect, -curarea->winrct.xmin, -curarea->winrct.ymin);
1240         
1241         calc_image_view(G.sima, 'p');
1242 //      printf("winrct %d %d %d %d\n", disprect->xmin, disprect->ymin,disprect->xmax, disprect->ymax);
1243         /* map to image space coordinates */
1244         mval[0]= disprect->xmin; mval[1]= disprect->ymin;
1245         areamouseco_to_ipoco(G.v2d, mval, &dispf.xmin, &dispf.ymin);
1246         mval[0]= disprect->xmax; mval[1]= disprect->ymax;
1247         areamouseco_to_ipoco(G.v2d, mval, &dispf.xmax, &dispf.ymax);
1248         
1249         /* map to render coordinates */
1250         disprect->xmin= dispf.xmin;
1251         disprect->xmax= dispf.xmax;
1252         disprect->ymin= dispf.ymin;
1253         disprect->ymax= dispf.ymax;
1254         
1255         CLAMP(disprect->xmin, 0, winx);
1256         CLAMP(disprect->xmax, 0, winx);
1257         CLAMP(disprect->ymin, 0, winy);
1258         CLAMP(disprect->ymax, 0, winy);
1259 //      printf("drawrct %d %d %d %d\n", disprect->xmin, disprect->ymin,disprect->xmax, disprect->ymax);
1260         
1261         image_preview_event(1);
1262 }
1263
1264 static int is_preview_allowed(ScrArea *cur)
1265 {
1266         ScrArea *sa;
1267
1268         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
1269                 if(sa!=cur && sa->spacetype==SPACE_IMAGE) {
1270                         if(image_preview_active(sa, NULL, NULL))
1271                            return 0;
1272                 }
1273         }
1274         return 1;
1275 }
1276
1277 static void image_panel_preview(ScrArea *sa, short cntrl)       // IMAGE_HANDLER_PREVIEW
1278 {
1279         uiBlock *block;
1280         SpaceImage *sima= sa->spacedata.first;
1281         int ofsx, ofsy;
1282         
1283         if(is_preview_allowed(sa)==0) {
1284                 rem_blockhandler(sa, IMAGE_HANDLER_PREVIEW);
1285                 return;
1286         }
1287         
1288         block= uiNewBlock(&sa->uiblocks, "image_panel_preview", UI_EMBOSS, UI_HELV, sa->win);
1289         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | UI_PNL_SCALE | cntrl);
1290         uiSetPanelHandler(IMAGE_HANDLER_PREVIEW);  // for close and esc
1291         
1292         ofsx= -150+(sa->winx/2)/sima->blockscale;
1293         ofsy= -100+(sa->winy/2)/sima->blockscale;
1294         if(uiNewPanel(sa, block, "Preview", "Image", ofsx, ofsy, 300, 200)==0) return;
1295         
1296         uiBlockSetDrawExtraFunc(block, preview_cb);
1297         
1298 }
1299
1300 static void image_blockhandlers(ScrArea *sa)
1301 {
1302         SpaceImage *sima= sa->spacedata.first;
1303         short a;
1304
1305         /* warning; blocks need to be freed each time, handlers dont remove  */
1306         uiFreeBlocksWin(&sa->uiblocks, sa->win);
1307         
1308         for(a=0; a<SPACE_MAXHANDLER; a+=2) {
1309                 switch(sima->blockhandler[a]) {
1310
1311                 case IMAGE_HANDLER_PROPERTIES:
1312                         image_panel_properties(sima->blockhandler[a+1]);
1313                         break;
1314                 case IMAGE_HANDLER_PAINT:
1315                         image_panel_paint(sima->blockhandler[a+1]);
1316                         break;          
1317                 case IMAGE_HANDLER_CURVES:
1318                         image_panel_curves(sima->blockhandler[a+1]);
1319                         break;          
1320                 case IMAGE_HANDLER_PREVIEW:
1321                         image_panel_preview(sa, sima->blockhandler[a+1]);
1322                         break;          
1323                 }
1324                 /* clear action value for event */
1325                 sima->blockhandler[a+1]= 0;
1326         }
1327         uiDrawBlocksPanels(sa, 0);
1328 }
1329
1330 static void imagespace_grid(SpaceImage *sima)
1331 {
1332         float gridsize, gridstep= 1.0f/32.0f;
1333         float fac, blendfac;
1334         
1335         gridsize= sima->zoom;
1336         
1337         calc_image_view(sima, 'f');
1338         myortho2(sima->v2d.cur.xmin, sima->v2d.cur.xmax, sima->v2d.cur.ymin, sima->v2d.cur.ymax);
1339         
1340         BIF_ThemeColorShade(TH_BACK, 20);
1341         glRectf(0.0, 0.0, 1.0, 1.0);
1342         
1343         if(gridsize<=0.0f) return;
1344         
1345         if(gridsize<1.0f) {
1346                 while(gridsize<1.0f) {
1347                         gridsize*= 4.0;
1348                         gridstep*= 4.0;
1349                 }
1350         }
1351         else {
1352                 while(gridsize>=4.0f) {
1353                         gridsize/= 4.0;
1354                         gridstep/= 4.0;
1355                 }
1356         }
1357         
1358         /* the fine resolution level */
1359         blendfac= 0.25*gridsize - floor(0.25*gridsize);
1360         CLAMP(blendfac, 0.0, 1.0);
1361         BIF_ThemeColorShade(TH_BACK, (int)(20.0*(1.0-blendfac)));
1362         
1363         fac= 0.0f;
1364         glBegin(GL_LINES);
1365         while(fac<1.0) {
1366                 glVertex2f(0.0f, fac);
1367                 glVertex2f(1.0f, fac);
1368                 glVertex2f(fac, 0.0f);
1369                 glVertex2f(fac, 1.0f);
1370                 fac+= gridstep;
1371         }
1372         
1373         /* the large resolution level */
1374         BIF_ThemeColor(TH_BACK);
1375         
1376         fac= 0.0f;
1377         while(fac<1.0) {
1378                 glVertex2f(0.0f, fac);
1379                 glVertex2f(1.0f, fac);
1380                 glVertex2f(fac, 0.0f);
1381                 glVertex2f(fac, 1.0f);
1382                 fac+= 4.0*gridstep;
1383         }
1384         glEnd();
1385         
1386 }
1387
1388 static void sima_draw_alpha_backdrop(SpaceImage *sima, float x1, float y1, float xsize, float ysize)
1389 {
1390         float tile= sima->zoom*15.0f;
1391         float x, y, maxx, maxy;
1392         
1393         glColor3ub(100, 100, 100);
1394         glRectf(x1, y1, x1 + sima->zoom*xsize, y1 + sima->zoom*ysize);
1395         glColor3ub(160, 160, 160);
1396         
1397         maxx= x1+sima->zoom*xsize;
1398         maxy= y1+sima->zoom*ysize;
1399         
1400         for(x=0; x<xsize; x+=30) {
1401                 for(y=0; y<ysize; y+=30) {
1402                         float fx= x1 + sima->zoom*x;
1403                         float fy= y1 + sima->zoom*y;
1404                         float tilex= tile, tiley= tile;
1405                         
1406                         if(fx+tile > maxx)
1407                                 tilex= maxx-fx;
1408                         if(fy+tile > maxy)
1409                                 tiley= maxy-fy;
1410                         
1411                         glRectf(fx, fy, fx + tilex, fy + tiley);
1412                 }
1413         }
1414         for(x=15; x<xsize; x+=30) {
1415                 for(y=15; y<ysize; y+=30) {
1416                         float fx= x1 + sima->zoom*x;
1417                         float fy= y1 + sima->zoom*y;
1418                         float tilex= tile, tiley= tile;
1419                         
1420                         if(fx+tile > maxx)
1421                                 tilex= maxx-fx;
1422                         if(fy+tile > maxy)
1423                                 tiley= maxy-fy;
1424                         
1425                         glRectf(fx, fy, fx + tilex, fy + tiley);
1426                 }
1427         }
1428 }
1429
1430 static void sima_draw_alpha_pixels(float x1, float y1, int rectx, int recty, unsigned int *recti)
1431 {
1432         
1433         /* swap bytes, so alpha is most significant one, then just draw it as luminance int */
1434         if(G.order==B_ENDIAN)
1435                 glPixelStorei(GL_UNPACK_SWAP_BYTES, 1);
1436         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_UNSIGNED_INT, recti);
1437         glPixelStorei(GL_UNPACK_SWAP_BYTES, 0);
1438 }
1439
1440 static void sima_draw_alpha_pixelsf(float x1, float y1, int rectx, int recty, float *rectf)
1441 {
1442         float *trectf= MEM_mallocN(rectx*recty*4, "temp");
1443         int a, b;
1444         
1445         for(a= rectx*recty -1, b= 4*a+3; a>=0; a--, b-=4)
1446                 trectf[a]= rectf[b];
1447         
1448         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_FLOAT, trectf);
1449         MEM_freeN(trectf);
1450         /* ogl trick below is slower... (on ATI 9600) */
1451 //      glColorMask(1, 0, 0, 0);
1452 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+3);
1453 //      glColorMask(0, 1, 0, 0);
1454 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+2);
1455 //      glColorMask(0, 0, 1, 0);
1456 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+1);
1457 //      glColorMask(1, 1, 1, 1);
1458 }
1459
1460 static void sima_draw_zbuf_pixels(float x1, float y1, int rectx, int recty, int *recti)
1461 {
1462         if(recti==NULL)
1463                 return;
1464         
1465         /* zbuffer values are signed, so we need to shift color range */
1466         glPixelTransferf(GL_RED_SCALE, 0.5f);
1467         glPixelTransferf(GL_GREEN_SCALE, 0.5f);
1468         glPixelTransferf(GL_BLUE_SCALE, 0.5f);
1469         glPixelTransferf(GL_RED_BIAS, 0.5f);
1470         glPixelTransferf(GL_GREEN_BIAS, 0.5f);
1471         glPixelTransferf(GL_BLUE_BIAS, 0.5f);
1472         
1473         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_INT, recti);
1474         
1475         glPixelTransferf(GL_RED_SCALE, 1.0f);
1476         glPixelTransferf(GL_GREEN_SCALE, 1.0f);
1477         glPixelTransferf(GL_BLUE_SCALE, 1.0f);
1478         glPixelTransferf(GL_RED_BIAS, 0.0f);
1479         glPixelTransferf(GL_GREEN_BIAS, 0.0f);
1480         glPixelTransferf(GL_BLUE_BIAS, 0.0f);
1481 }
1482
1483 static void sima_draw_zbuffloat_pixels(float x1, float y1, int rectx, int recty, float *rect_float)
1484 {
1485         float bias, scale, *rectf, clipend;
1486         int a;
1487         
1488         if(rect_float==NULL)
1489                 return;
1490         
1491         if(G.scene->camera && G.scene->camera->type==OB_CAMERA) {
1492                 bias= ((Camera *)G.scene->camera->data)->clipsta;
1493                 clipend= ((Camera *)G.scene->camera->data)->clipend;
1494                 scale= 1.0f/(clipend-bias);
1495         }
1496         else {
1497                 bias= 0.1f;
1498                 scale= 0.01f;
1499                 clipend= 100.0f;
1500         }
1501         
1502         rectf= MEM_mallocN(rectx*recty*4, "temp");
1503         for(a= rectx*recty -1; a>=0; a--) {
1504                 if(rect_float[a]>clipend)
1505                         rectf[a]= 0.0f;
1506                 else if(rect_float[a]<bias)
1507                         rectf[a]= 1.0f;
1508                 else {
1509                         rectf[a]= 1.0f - (rect_float[a]-bias)*scale;
1510                         rectf[a]*= rectf[a];
1511                 }
1512         }
1513         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_FLOAT, rectf);
1514         
1515         MEM_freeN(rectf);
1516 }
1517
1518 static void imagewindow_draw_renderinfo(ScrArea *sa)
1519 {
1520         SpaceImage *sima= sa->spacedata.first;
1521         rcti rect;
1522         float colf[3];
1523         
1524         if(sima->info_str==NULL)
1525                 return;
1526         
1527         rect= sa->winrct;
1528         rect.ymin= rect.ymax-RW_HEADERY;
1529         
1530         glaDefine2DArea(&rect);
1531         
1532         /* clear header rect */
1533         BIF_GetThemeColor3fv(TH_BACK, colf);
1534         glClearColor(colf[0]+0.1f, colf[1]+0.1f, colf[2]+0.1f, 1.0); 
1535         glClear(GL_COLOR_BUFFER_BIT);
1536         
1537         BIF_ThemeColor(TH_TEXT_HI);
1538         glRasterPos2i(12, 5);
1539         BMF_DrawString(G.fonts, sima->info_str);
1540 }
1541
1542 void drawimagespace(ScrArea *sa, void *spacedata)
1543 {
1544         SpaceImage *sima= spacedata;
1545         ImBuf *ibuf= NULL;
1546         Brush *brush;
1547         float col[3];
1548         unsigned int *rect;
1549         float x1, y1;
1550         short sx, sy, dx, dy, show_render= 0;
1551         
1552                 /* If derived data is used then make sure that object
1553                  * is up-to-date... might not be the case because updates
1554                  * are normally done in drawview and could get here before
1555                  * drawing a View3D.
1556                  */
1557         if (!G.obedit && OBACT && (sima->flag & SI_DRAWSHADOW)) {
1558                 object_handle_update(OBACT);
1559         }
1560
1561         BIF_GetThemeColor3fv(TH_BACK, col);
1562         glClearColor(col[0], col[1], col[2], 0.0);
1563         glClear(GL_COLOR_BUFFER_BIT);
1564
1565         bwin_clear_viewmat(sa->win);    /* clear buttons view */
1566         glLoadIdentity();
1567         
1568         if(sima->image && BLI_streq(sima->image->id.name+2, "Render Result") )
1569                 show_render= 1;
1570         
1571         what_image(sima);
1572         
1573         if(sima->image) {
1574                 if(sima->image->ibuf==NULL && show_render==0) {
1575                         load_image(sima->image, IB_rect, G.sce, G.scene->r.cfra);
1576                         scrarea_queue_headredraw(sa);   /* update header for image options */
1577                 }
1578                 
1579                 tag_image_time(sima->image);
1580                 ibuf= sima->image->ibuf;
1581         }
1582         
1583         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL)) {
1584                 imagespace_grid(sima);
1585                 if(show_render==0)
1586                         draw_tfaces();
1587         }
1588         else {
1589                 float xim, yim, xoffs=0.0f, yoffs= 0.0f;
1590                 
1591                 if(image_preview_active(sa, &xim, &yim)) {
1592                         xoffs= G.scene->r.disprect.xmin;
1593                         yoffs= G.scene->r.disprect.ymin;
1594                         glColor3ub(0,0,0);
1595                         calc_image_view(sima, 'f');     
1596                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
1597                         glRectf(0.0f, 0.0f, 1.0f, 1.0f);
1598                         glLoadIdentity();
1599                 }
1600                 else {
1601                         xim= ibuf->x; yim= ibuf->y;
1602                 }
1603                 
1604                 /* calc location */
1605                 x1= sima->zoom*xoffs + ((float)sa->winx - sima->zoom*(float)xim)/2.0f;
1606                 y1= sima->zoom*yoffs + ((float)sa->winy - sima->zoom*(float)yim)/2.0f;
1607         
1608                 x1-= sima->zoom*sima->xof;
1609                 y1-= sima->zoom*sima->yof;
1610                 
1611                 /* needed for gla draw */
1612                 if(show_render) { 
1613                         rcti rct= sa->winrct; 
1614                         
1615                         imagewindow_draw_renderinfo(sa);        /* calls glaDefine2DArea too */
1616                         
1617                         rct.ymax-=RW_HEADERY; 
1618                         glaDefine2DArea(&rct);
1619                 }
1620                 else glaDefine2DArea(&sa->winrct);
1621                 
1622                 glPixelZoom((float)sima->zoom, (float)sima->zoom);
1623                                 
1624                 if(sima->flag & SI_EDITTILE) {
1625                         glaDrawPixelsSafe(x1, y1, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1626                         
1627                         glPixelZoom(1.0, 1.0);
1628                         
1629                         dx= ibuf->x/sima->image->xrep;
1630                         dy= ibuf->y/sima->image->yrep;
1631                         sy= (sima->curtile / sima->image->xrep);
1632                         sx= sima->curtile - sy*sima->image->xrep;
1633         
1634                         sx*= dx;
1635                         sy*= dy;
1636                         
1637                         calc_image_view(sima, 'p');     /* pixel */
1638                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
1639                         
1640                         cpack(0x0);
1641                         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRects(sx,  sy,  sx+dx-1,  sy+dy-1); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1642                         cpack(0xFFFFFF);
1643                         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRects(sx+1,  sy+1,  sx+dx,  sy+dy); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1644                 }
1645                 else if(sima->mode==SI_TEXTURE) {
1646                         
1647                         if(sima->image->tpageflag & IMA_TILES) {
1648                                 
1649                                 /* just leave this a while */
1650                                 if(sima->image->xrep<1) return;
1651                                 if(sima->image->yrep<1) return;
1652                                 
1653                                 if(sima->curtile >= sima->image->xrep*sima->image->yrep) 
1654                                         sima->curtile = sima->image->xrep*sima->image->yrep - 1; 
1655                                 
1656                                 dx= ibuf->x/sima->image->xrep;
1657                                 dy= ibuf->y/sima->image->yrep;
1658                                 
1659                                 sy= (sima->curtile / sima->image->xrep);
1660                                 sx= sima->curtile - sy*sima->image->xrep;
1661                 
1662                                 sx*= dx;
1663                                 sy*= dy;
1664                                 
1665                                 rect= get_part_from_ibuf(ibuf, sx, sy, sx+dx, sy+dy);
1666                                 
1667                                 /* rect= ibuf->rect; */
1668                                 for(sy= 0; sy+dy<=ibuf->y; sy+= dy) {
1669                                         for(sx= 0; sx+dx<=ibuf->x; sx+= dx) {
1670                                                 glaDrawPixelsSafe(x1+sx*sima->zoom, y1+sy*sima->zoom, dx, dy, dx, GL_RGBA, GL_UNSIGNED_BYTE, rect);
1671                                         }
1672                                 }
1673                                 
1674                                 MEM_freeN(rect);
1675                         }
1676                         else {
1677                                 /* this part is generic image display */
1678                                 if(sima->flag & SI_SHOW_ALPHA) {
1679                                         if(ibuf->rect)
1680                                                 sima_draw_alpha_pixels(x1, y1, ibuf->x, ibuf->y, ibuf->rect);
1681                                         else if(ibuf->rect_float)
1682                                                 sima_draw_alpha_pixelsf(x1, y1, ibuf->x, ibuf->y, ibuf->rect_float);
1683                                 }
1684                                 else if(sima->flag & SI_SHOW_ZBUF) {
1685                                         if(ibuf->zbuf)
1686                                                 sima_draw_zbuf_pixels(x1, y1, ibuf->x, ibuf->y, ibuf->zbuf);
1687                                         else
1688                                                 sima_draw_zbuffloat_pixels(x1, y1, ibuf->x, ibuf->y, ibuf->zbuf_float);
1689                                 }
1690                                 else {
1691                                         if(sima->flag & SI_USE_ALPHA) {
1692                                                 sima_draw_alpha_backdrop(sima, x1, y1, (float)ibuf->x, (float)ibuf->y);
1693                                                 glEnable(GL_BLEND);
1694                                                 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
1695                                         }
1696                                         
1697                                         /* detect if we need to redo the curve map. 
1698                                            ibuf->rect is zero for compositor and render results after change 
1699                                            convert to 32 bits always... drawing float rects isnt supported well (atis)
1700                                         */
1701                                         if(ibuf->rect_float) {
1702                                                 if(ibuf->rect==NULL) {
1703                                                         if(image_curves_active(sa))
1704                                                                 curvemapping_do_image(G.sima->cumap, G.sima->image);
1705                                                         else 
1706                                                                 IMB_rect_from_float(ibuf);
1707                                                 }
1708                                         }
1709
1710                                         if(ibuf->rect)
1711                                                 glaDrawPixelsSafe(x1, y1, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1712 //                                      else
1713 //                                              glaDrawPixelsSafe(x1, y1, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_FLOAT, ibuf->rect_float);
1714                                         
1715                                         if(sima->flag & SI_USE_ALPHA)
1716                                                 glDisable(GL_BLEND);
1717                                 }
1718                         }
1719                         
1720                         brush= G.scene->toolsettings->imapaint.brush;
1721                         if(brush && (G.scene->toolsettings->imapaint.tool == PAINT_TOOL_CLONE)) {
1722                                 int w, h;
1723                                 unsigned char *clonerect;
1724
1725                                 /* this is not very efficient, but glDrawPixels doesn't allow
1726                                    drawing with alpha */
1727                                 clonerect= alloc_alpha_clone_image(&w, &h);
1728
1729                                 if(clonerect) {
1730                                         int offx, offy;
1731                                         offx = sima->zoom*ibuf->x * + brush->clone.offset[0];
1732                                         offy = sima->zoom*ibuf->y * + brush->clone.offset[1];
1733
1734                                         glEnable(GL_BLEND);
1735                                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1736                                         glaDrawPixelsSafe(x1 + offx, y1 + offy, w, h, w, GL_RGBA, GL_UNSIGNED_BYTE, clonerect);
1737                                         glDisable(GL_BLEND);
1738
1739                                         MEM_freeN(clonerect);
1740                                 }
1741                         }
1742                         
1743                         glPixelZoom(1.0, 1.0);
1744                         
1745                         if(show_render==0) 
1746                                 draw_tfaces();
1747                 }
1748
1749                 glPixelZoom(1.0, 1.0);
1750
1751                 calc_image_view(sima, 'f');     /* float */
1752         }
1753
1754         draw_image_transform(ibuf);
1755
1756         mywinset(sa->win);      /* restore scissor after gla call... */
1757         myortho2(-0.375, sa->winx-0.375, -0.375, sa->winy-0.375);
1758
1759         if(G.rendering==0) {
1760                 draw_image_view_tool();
1761                 draw_image_view_icon();
1762         }
1763         draw_area_emboss(sa);
1764
1765         /* it is important to end a view in a transform compatible with buttons */
1766         bwin_scalematrix(sa->win, sima->blockscale, sima->blockscale, sima->blockscale);
1767         if(!(G.rendering && show_render))
1768                 image_blockhandlers(sa);
1769
1770         sa->win_swap= WIN_BACK_OK;
1771 }
1772
1773 static void image_zoom_power_of_two(void)
1774 {
1775         /* Make zoom a power of 2 */
1776
1777         G.sima->zoom = 1 / G.sima->zoom;
1778         G.sima->zoom = log(G.sima->zoom) / log(2);
1779         G.sima->zoom = ceil(G.sima->zoom);
1780         G.sima->zoom = pow(2, G.sima->zoom);
1781         G.sima->zoom = 1 / G.sima->zoom;
1782 }
1783
1784 static void image_zoom_set_factor(float zoomfac)
1785 {
1786         SpaceImage *sima= curarea->spacedata.first;
1787         int width, height;
1788
1789         if (zoomfac <= 0.0f)
1790                 return;
1791
1792         sima->zoom *= zoomfac;
1793
1794         if (sima->zoom > 0.1f && sima->zoom < 4.0f)
1795                 return;
1796
1797         /* check zoom limits */
1798
1799         calc_image_view(G.sima, 'p');
1800         width= 256;
1801         height= 256;
1802         if (sima->image) {
1803                 if (sima->image->ibuf) {
1804                         float xim, yim;
1805                         /* I know a bit weak... but preview uses not actual image size */
1806                         if(image_preview_active(curarea, &xim, &yim)) {
1807                                 width= (int) xim;
1808                                 height= (int) yim;
1809                         }
1810                         else {
1811                                 width= sima->image->ibuf->x;
1812                                 height= sima->image->ibuf->y;
1813                         }
1814                 }
1815         }
1816         width *= sima->zoom;
1817         height *= sima->zoom;
1818
1819         if ((width < 4) && (height < 4))
1820                 sima->zoom /= zoomfac;
1821         else if((curarea->winrct.xmax - curarea->winrct.xmin) <= sima->zoom)
1822                 sima->zoom /= zoomfac;
1823         else if((curarea->winrct.ymax - curarea->winrct.ymin) <= sima->zoom)
1824                 sima->zoom /= zoomfac;
1825 }
1826
1827 void image_viewmove(int mode)
1828 {
1829         short mval[2], mvalo[2], zoom0;
1830         int oldcursor;
1831         Window *win;
1832         
1833         getmouseco_sc(mvalo);
1834         zoom0= G.sima->zoom;
1835         
1836         oldcursor=get_cursor();
1837         win=winlay_get_active_window();
1838         
1839         SetBlenderCursor(BC_NSEW_SCROLLCURSOR);
1840         
1841         while(get_mbut()&(L_MOUSE|M_MOUSE)) {
1842
1843                 getmouseco_sc(mval);
1844
1845                 if(mvalo[0]!=mval[0] || mvalo[1]!=mval[1]) {
1846                 
1847                         if(mode==0) {
1848                                 G.sima->xof += (mvalo[0]-mval[0])/G.sima->zoom;
1849                                 G.sima->yof += (mvalo[1]-mval[1])/G.sima->zoom;
1850                         }
1851                         else if (mode==1) {
1852                                 float factor;
1853
1854                                 factor= 1.0+(float)(mvalo[0]-mval[0]+mvalo[1]-mval[1])/300.0;
1855                                 image_zoom_set_factor(factor);
1856                         }
1857
1858                         mvalo[0]= mval[0];
1859                         mvalo[1]= mval[1];
1860                         
1861                         scrarea_do_windraw(curarea);
1862                         screen_swapbuffers();
1863                 }
1864                 else BIF_wait_for_statechange();
1865         }
1866         window_set_cursor(win, oldcursor);
1867         
1868         if(image_preview_active(curarea, NULL, NULL)) {
1869                 /* recalculates new preview rect */
1870                 scrarea_do_windraw(curarea);
1871                 image_preview_event(2);
1872         }
1873 }
1874
1875 void image_viewzoom(unsigned short event, int invert)
1876 {
1877         SpaceImage *sima= curarea->spacedata.first;
1878
1879         if(event==WHEELDOWNMOUSE || event==PADMINUS)
1880                 image_zoom_set_factor((U.uiflag & USER_WHEELZOOMDIR)? 1.25: 0.8);
1881         else if(event==WHEELUPMOUSE || event==PADPLUSKEY)
1882                 image_zoom_set_factor((U.uiflag & USER_WHEELZOOMDIR)? 0.8: 1.25);
1883         else if(event==PAD1)
1884                 sima->zoom= 1.0;
1885         else if(event==PAD2)
1886                 sima->zoom= (invert)? 2.0: 0.5;
1887         else if(event==PAD4)
1888                 sima->zoom= (invert)? 4.0: 0.25;
1889         else if(event==PAD8)
1890                 sima->zoom= (invert)? 8.0: 0.125;
1891         
1892         /* ensure pixel exact locations for draw */
1893         sima->xof= (int)sima->xof;
1894         sima->yof= (int)sima->yof;
1895         
1896         if(image_preview_active(curarea, NULL, NULL)) {
1897                 /* recalculates new preview rect */
1898                 scrarea_do_windraw(curarea);
1899                 image_preview_event(2);
1900         }
1901 }
1902
1903 /**
1904  * Updates the fields of the View2D member of the SpaceImage struct.
1905  * Default behavior is to reset the position of the image and set the zoom to 1
1906  * If the image will not fit within the window rectangle, the zoom is adjusted
1907  *
1908  * @return    void
1909  *   
1910  */
1911 void image_home(void)
1912 {
1913         int width, height, imgwidth, imgheight;
1914         float zoomX, zoomY;
1915
1916         if (curarea->spacetype != SPACE_IMAGE) return;
1917
1918         if ((G.sima->image == NULL) || (G.sima->image->ibuf == NULL)) {
1919                 imgwidth = 256;
1920                 imgheight = 256;
1921         }
1922         else {
1923                 imgwidth = G.sima->image->ibuf->x;
1924                 imgheight = G.sima->image->ibuf->y;
1925         }
1926
1927         /* Check if the image will fit in the image with zoom==1 */
1928         width = curarea->winx;
1929         height = curarea->winy;
1930         if (((imgwidth >= width) || (imgheight >= height)) && 
1931                 ((width > 0) && (height > 0))) {
1932                 /* Find the zoom value that will fit the image in the image space */
1933                 zoomX = ((float)width) / ((float)imgwidth);
1934                 zoomY = ((float)height) / ((float)imgheight);
1935                 G.sima->zoom= MIN2(zoomX, zoomY);
1936
1937                 image_zoom_power_of_two();
1938         }
1939         else {
1940                 G.sima->zoom= 1.0f;
1941         }
1942
1943         G.sima->xof= G.sima->yof= 0.0f;
1944         
1945         calc_image_view(G.sima, 'p');
1946         
1947         scrarea_queue_winredraw(curarea);
1948 }
1949
1950 void image_viewcentre(void)
1951 {
1952         float size, min[2], max[2], d[2], xim=256.0f, yim=256.0f;
1953
1954         if( is_uv_tface_editing_allowed()==0 ) return;
1955
1956         if (!minmax_tface_uv(min, max)) return;
1957
1958         if(G.sima->image && G.sima->image->ibuf) {
1959                 xim= G.sima->image->ibuf->x;
1960                 yim= G.sima->image->ibuf->y;
1961         }
1962
1963         G.sima->xof= (int) (((min[0] + max[0])*0.5f - 0.5f)*xim);
1964         G.sima->yof= (int) (((min[1] + max[1])*0.5f - 0.5f)*yim);
1965
1966         d[0] = max[0] - min[0];
1967         d[1] = max[1] - min[1];
1968         size= 0.5*MAX2(d[0], d[1])*MAX2(xim, yim)/256.0f;
1969         
1970         if(size<=0.01) size= 0.01;
1971
1972         G.sima->zoom= 0.7/size;
1973
1974         calc_image_view(G.sima, 'p');
1975
1976         scrarea_queue_winredraw(curarea);
1977 }
1978
1979
1980 /* *********************** render callbacks ***************** */
1981
1982 /* set on initialize render, only one render output to imagewindow can exist, so the global isnt dangerous yet :) */
1983 static ScrArea *image_area= NULL;
1984
1985 /* can get as well the full picture, as the parts while rendering */
1986 static void imagewindow_progress(ScrArea *sa, RenderResult *rr, volatile rcti *renrect)
1987 {
1988         SpaceImage *sima= sa->spacedata.first;
1989         float x1, y1, *rectf= NULL;
1990         unsigned int *rect32= NULL;
1991         int ymin, ymax, xmin, xmax;
1992         
1993         /* if renrect argument, we only display scanlines */
1994         if(renrect) {
1995                 /* if ymax==recty, rendering of layer is ready, we should not draw, other things happen... */
1996                 if(rr->renlay==NULL || renrect->ymax>=rr->recty)
1997                         return;
1998                 
1999                 /* xmin here is first subrect x coord, xmax defines subrect width */
2000                 xmin = renrect->xmin;
2001                 xmax = renrect->xmax - xmin;
2002                 if (xmax<2) return;
2003                 
2004                 ymin= renrect->ymin;
2005                 ymax= renrect->ymax - ymin;
2006                 if(ymax<2)
2007                         return;
2008                 renrect->ymin= renrect->ymax;
2009         }
2010         else {
2011                 xmin = ymin = 0;
2012                 xmax = rr->rectx - 2*rr->crop;
2013                 ymax = rr->recty - 2*rr->crop;
2014         }
2015         
2016         /* image window cruft */
2017         
2018         /* find current float rect for display, first case is after composit... still weak */
2019         if(rr->rectf)
2020                 rectf= rr->rectf;
2021         else {
2022                 if(rr->rect32)
2023                         rect32= rr->rect32;
2024                 else {
2025                         if(rr->renlay==NULL || rr->renlay->rectf==NULL) return;
2026                         rectf= rr->renlay->rectf;
2027                 }
2028         }
2029         if(rectf) {
2030                 /* if scanline updates... */
2031                 rectf+= 4*(rr->rectx*ymin + xmin);
2032                 
2033                 /* when rendering more pixels than needed, we crop away cruft */
2034                 if(rr->crop)
2035                         rectf+= 4*(rr->crop*rr->rectx + rr->crop);
2036         }
2037         
2038         /* tilerect defines drawing offset from (0,0) */
2039         /* however, tilerect (xmin, ymin) is first pixel */
2040         x1 = sima->centx + (rr->tilerect.xmin + rr->crop + xmin)*sima->zoom;
2041         y1 = sima->centy + (rr->tilerect.ymin + rr->crop + ymin)*sima->zoom;
2042         
2043         /* needed for gla draw */
2044         { rcti rct= sa->winrct; rct.ymax-= RW_HEADERY; glaDefine2DArea(&rct);}
2045
2046         glPixelZoom((float)sima->zoom, (float)sima->zoom);
2047         
2048         if(rect32)
2049                 glaDrawPixelsSafe(x1, y1, xmax, ymax, rr->rectx, GL_RGBA, GL_UNSIGNED_BYTE, rect32);
2050         else
2051                 glaDrawPixelsSafe_to32(x1, y1, xmax, ymax, rr->rectx, rectf);
2052         
2053         glPixelZoom(1.0, 1.0);
2054         
2055 }
2056
2057
2058 /* in render window; display a couple of scanlines of rendered image */
2059 /* NOTE: called while render, so no malloc allowed! */
2060 static void imagewindow_progress_display_cb(RenderResult *rr, volatile rcti *rect)
2061 {
2062         
2063         if (image_area) {
2064                 
2065                 if(rect==NULL) {
2066                         SpaceImage *sima= image_area->spacedata.first;
2067                         
2068                         /* this enforces reading correct buffer in what_image(), renderlayers/scenes/compo/sequences... */
2069                         IMB_freeImBuf(sima->image->ibuf);
2070                         sima->image->ibuf= NULL;
2071                 }               
2072                 
2073                 imagewindow_progress(image_area, rr, rect);
2074
2075                 /* no screen_swapbuffers, prevent any other window to draw */
2076                 myswapbuffers();
2077         }
2078 }
2079
2080 /* unused, init_display_cb is called on each render */
2081 static void imagewindow_clear_display_cb(RenderResult *rr)
2082 {
2083         if (image_area) {
2084         }
2085 }
2086
2087 static ScrArea *biggest_non_image_area(void)
2088 {
2089         ScrArea *sa, *big= NULL;
2090         int size, maxsize= 0;
2091         
2092         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
2093                 if(sa->spacetype!=SPACE_IMAGE) {
2094                         size= sa->winx*sa->winy;
2095                         if(sa->winx > 10 && sa->winy > 10 && size > maxsize) {
2096                                 maxsize= size;
2097                                 big= sa;
2098                         }
2099                 }
2100         }
2101         return big;
2102 }
2103
2104 static ScrArea *biggest_area(void)
2105 {
2106         ScrArea *sa, *big= NULL;
2107         int size, maxsize= 0;
2108         
2109         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
2110                 size= sa->winx*sa->winy;
2111                 if(size > maxsize) {
2112                         maxsize= size;
2113                         big= sa;
2114                 }
2115         }
2116         return big;
2117 }
2118
2119
2120 /* if R_DISPLAYIMAGE
2121       use Image Window showing Render Result
2122           else: turn largest non-image area into Image Window (not to frustrate texture or composite usage)
2123           else: then we use Image Window anyway...
2124    if R_DISPSCREEN
2125       make a new temp fullscreen area with Image Window
2126 */
2127
2128 static ScrArea *imagewindow_set_render_display(void)
2129 {
2130         ScrArea *sa;
2131         SpaceImage *sima;
2132         
2133         /* find an imagewindow showing render result */
2134         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
2135                 if(sa->spacetype==SPACE_IMAGE) {
2136                         sima= sa->spacedata.first;
2137                         
2138                         if(sima->image && BLI_streq(sima->image->id.name+2, "Render Result") )
2139                                 break;
2140                 }
2141         }
2142         if(sa==NULL) {
2143                 /* find largest open non-image area */
2144                 sa= biggest_non_image_area();
2145                 if(sa) {
2146                         newspace(sa, SPACE_IMAGE);
2147                         sima= sa->spacedata.first;
2148                         
2149                         /* makes ESC go back to prev space */
2150                         sima->flag |= SI_PREVSPACE;
2151                 }
2152                 else {
2153                         /* use any area of decent size */
2154                         sa= biggest_area();
2155                         if(sa->spacetype!=SPACE_IMAGE) {
2156                                 newspace(sa, SPACE_IMAGE);
2157                                 sima= sa->spacedata.first;
2158                                 
2159                                 /* makes ESC go back to prev space */
2160                                 sima->flag |= SI_PREVSPACE;
2161                         }
2162                 }
2163         }
2164         
2165         sima= sa->spacedata.first;
2166         
2167         /* get the correct image, and scale it */
2168         sima->image = (Image *)find_id("IM", "Render Result");
2169         
2170         if(sima->image==NULL) {
2171                 Image *ima= alloc_libblock(&G.main->image, ID_IM, "Render Result");
2172                 strcpy(ima->name, "Render Result");
2173                 ima->ok= 1;
2174                 ima->xrep= ima->yrep= 1;
2175                 sima->image= ima;
2176         }
2177         else if(sima->image->id.us==0)  /* well... happens on reload, dunno yet what todo, imagewindow cannot be user when hidden*/
2178                 sima->image->id.us= 1;
2179         
2180         /* this enforces reading empty buffer in what_image(), so display is cleared */
2181         IMB_freeImBuf(sima->image->ibuf);
2182         sima->image->ibuf= NULL;
2183         
2184         if(G.displaymode==R_DISPLAYSCREEN) {
2185                 if(sa->full==0) {
2186                         sima->flag |= SI_FULLWINDOW;
2187                         /* fullscreen works with lousy curarea */
2188                         curarea= sa;
2189                         area_fullscreen();
2190                         sa= curarea;
2191                 }
2192         }
2193         
2194         return sa;
2195 }
2196
2197 static void imagewindow_init_display_cb(RenderResult *rr)
2198 {
2199         
2200         image_area= imagewindow_set_render_display();
2201         
2202         if(image_area) {
2203                 SpaceImage *sima= image_area->spacedata.first;
2204                 
2205                 areawinset(image_area->win);
2206                 
2207                 if(sima->info_str==NULL)
2208                         sima->info_str= MEM_callocN(RW_MAXTEXT, "info str imagewin");
2209                 
2210                 /* calc location using original size (tiles don't tell) */
2211                 sima->centx= (image_area->winx - sima->zoom*(float)rr->rectx)/2.0f;
2212                 sima->centy= (image_area->winy - sima->zoom*(float)rr->recty)/2.0f;
2213                 
2214                 sima->centx-= sima->zoom*sima->xof;
2215                 sima->centy-= sima->zoom*sima->yof;
2216                 
2217                 drawimagespace(image_area, sima);
2218                 if(image_area->headertype) scrarea_do_headdraw(image_area);
2219                 screen_swapbuffers();
2220                 
2221                 allqueue(REDRAWIMAGE, 0);       /* redraw in end */
2222         }
2223 }
2224
2225 /* coming from BIF_toggle_render_display() */
2226 void imagewindow_toggle_render(void)
2227 {
2228         ScrArea *sa;
2229         
2230         /* check if any imagewindow is showing temporal render output */
2231         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
2232                 if(sa->spacetype==SPACE_IMAGE) {
2233                         SpaceImage *sima= sa->spacedata.first;
2234                         
2235                         if(sima->image && BLI_streq(sima->image->id.name+2, "Render Result") )
2236                                 if(sima->flag & (SI_PREVSPACE|SI_FULLWINDOW))
2237                                         break;
2238                 }
2239         }
2240         if(sa) {
2241                 addqueue(sa->win, ESCKEY, 1);   /* also returns from fullscreen */
2242         }
2243         else {
2244                 sa= imagewindow_set_render_display();
2245                 scrarea_queue_headredraw(sa);
2246                 scrarea_queue_winredraw(sa);
2247         }
2248 }
2249
2250 /* NOTE: called while render, so no malloc allowed! */
2251 static void imagewindow_renderinfo_cb(RenderStats *rs)
2252 {
2253         
2254         if(image_area) {
2255                 SpaceImage *sima= image_area->spacedata.first;
2256                 
2257                 if(rs)
2258                         make_renderinfo_string(rs, sima->info_str);
2259
2260                 imagewindow_draw_renderinfo(image_area);
2261                 
2262                 /* no screen_swapbuffers, prevent any other window to draw */
2263                 myswapbuffers();
2264         }
2265 }
2266
2267
2268 void imagewindow_render_callbacks(Render *re)
2269 {
2270         RE_display_init_cb(re, imagewindow_init_display_cb);
2271         RE_display_draw_cb(re, imagewindow_progress_display_cb);
2272         RE_display_clear_cb(re, imagewindow_clear_display_cb);
2273         RE_stats_draw_cb(re, imagewindow_renderinfo_cb);        
2274 }
2275