svn merge -r 15392:15551 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[blender.git] / source / blender / src / drawimage.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL 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.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): Blender Foundation, 2002-2006
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <math.h>
31 #include <string.h>
32
33 #ifdef HAVE_CONFIG_H
34 #include <config.h>
35 #endif
36
37 #ifdef WIN32
38 #include <io.h>
39 #else
40 #include <unistd.h>
41 #endif   
42 #include "MEM_guardedalloc.h"
43
44 #include "BLI_arithb.h"
45 #include "BLI_blenlib.h"
46 #include "BLI_editVert.h"
47
48 #include "IMB_imbuf.h"
49 #include "IMB_imbuf_types.h"
50
51 #include "DNA_brush_types.h"
52 #include "DNA_camera_types.h"
53 #include "DNA_color_types.h"
54 #include "DNA_image_types.h"
55 #include "DNA_mesh_types.h"
56 #include "DNA_meshdata_types.h"
57 #include "DNA_node_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_packedFile_types.h"
60 #include "DNA_scene_types.h"
61 #include "DNA_screen_types.h"
62 #include "DNA_space_types.h"
63 #include "DNA_texture_types.h"
64 #include "DNA_userdef_types.h"
65
66 #include "BKE_brush.h"
67 #include "BKE_colortools.h"
68 #include "BKE_utildefines.h"
69 #include "BKE_global.h"
70 #include "BKE_library.h"
71 #include "BKE_main.h"
72 #include "BKE_mesh.h"
73 #include "BKE_node.h"
74 #include "BKE_image.h"
75 #include "BKE_DerivedMesh.h"
76 #include "BKE_displist.h"
77 #include "BKE_object.h"
78
79 #include "BDR_editface.h"
80 #include "BDR_drawobject.h"
81 #include "BDR_drawmesh.h"
82 #include "BDR_imagepaint.h"
83
84 #include "BIF_cursors.h"
85 #include "BIF_gl.h"
86 #include "BIF_graphics.h"
87 #include "BIF_mywindow.h"
88 #include "BIF_drawimage.h"
89 #include "BIF_resources.h"
90 #include "BIF_interface.h"
91 #include "BIF_interface_icons.h"
92 #include "BIF_editsima.h"
93 #include "BIF_glutil.h"
94 #include "BIF_renderwin.h"
95 #include "BIF_space.h"
96 #include "BIF_screen.h"
97 #include "BIF_toolbox.h"
98 #include "BIF_transform.h"
99 #include "BIF_editmesh.h"
100
101 #include "BSE_drawipo.h"
102 #include "BSE_drawview.h"
103 #include "BSE_filesel.h"
104 #include "BSE_headerbuttons.h"
105 #include "BSE_node.h"
106 #include "BSE_trans_types.h"
107 #include "BSE_view.h"
108
109 #include "RE_pipeline.h"
110 #include "BMF_Api.h"
111
112 #include "PIL_time.h"
113
114 /* Modules used */
115 #include "mydevice.h"
116 #include "blendef.h"
117 #include "butspace.h"  // event codes
118 #include "winlay.h"
119
120 #include "interface.h"  /* bad.... but preview code needs UI info. Will solve... (ton) */
121
122 static unsigned char *alloc_alpha_clone_image(int *width, int *height)
123 {
124         Brush *brush = G.scene->toolsettings->imapaint.brush;
125         ImBuf *ibuf;
126         unsigned int size, alpha;
127         unsigned char *rect, *cp;
128
129         if(!brush || !brush->clone.image)
130                 return NULL;
131         
132         ibuf= BKE_image_get_ibuf(brush->clone.image, NULL);
133
134         if(!ibuf || !ibuf->rect)
135                 return NULL;
136
137         rect= MEM_dupallocN(ibuf->rect);
138         if(!rect)
139                 return NULL;
140
141         *width= ibuf->x;
142         *height= ibuf->y;
143
144         size= (*width)*(*height);
145         alpha= (unsigned char)255*brush->clone.alpha;
146         cp= rect;
147
148         while(size-- > 0) {
149                 cp[3]= alpha;
150                 cp += 4;
151         }
152
153         return rect;
154 }
155
156 static int image_preview_active(ScrArea *sa, float *xim, float *yim)
157 {
158         SpaceImage *sima= sa->spacedata.first;
159         
160         /* only when compositor shows, and image handler set */
161         if(sima->image && sima->image->type==IMA_TYPE_COMPOSITE) {
162                 short a;
163         
164                 for(a=0; a<SPACE_MAXHANDLER; a+=2) {
165                         if(sima->blockhandler[a] == IMAGE_HANDLER_PREVIEW) {
166                                 if(xim) *xim= (G.scene->r.size*G.scene->r.xsch)/100;
167                                 if(yim) *yim= (G.scene->r.size*G.scene->r.ysch)/100;
168                                 return 1;
169                         }
170                 }
171         }
172         return 0;
173 }
174
175
176 /**
177  * Sets up the fields of the View2D member of the SpaceImage struct
178  * This routine can be called in two modes:
179  * mode == 'f': float mode (0.0 - 1.0)
180  * mode == 'p': pixel mode (0 - size)
181  *
182  * @param     sima  the image space to update
183  * @param     mode  the mode to use for the update
184  * @return    void
185  *   
186  */
187 void calc_image_view(SpaceImage *sima, char mode)
188 {
189         float xim=256, yim=256;
190         float x1, y1;
191         
192         if(image_preview_active(curarea, &xim, &yim));
193         else if(sima->image) {
194                 ImBuf *ibuf= imagewindow_get_ibuf(sima);
195                 float xuser_asp, yuser_asp;
196                 
197                 image_pixel_aspect(sima->image, &xuser_asp, &yuser_asp);
198                 if(ibuf) {
199                         xim= ibuf->x * xuser_asp;
200                         yim= ibuf->y * yuser_asp;
201                 }
202                 else if( sima->image->type==IMA_TYPE_R_RESULT ) {
203                         /* not very important, just nice */
204                         xim= (G.scene->r.xsch*G.scene->r.size)/100;
205                         yim= (G.scene->r.ysch*G.scene->r.size)/100;
206                 }
207         }
208                 
209         sima->v2d.tot.xmin= 0;
210         sima->v2d.tot.ymin= 0;
211         sima->v2d.tot.xmax= xim;
212         sima->v2d.tot.ymax= yim;
213         
214         sima->v2d.mask.xmin= sima->v2d.mask.ymin= 0;
215         sima->v2d.mask.xmax= curarea->winx;
216         sima->v2d.mask.ymax= curarea->winy;
217
218
219         /* Which part of the image space do we see? */
220         /* Same calculation as in lrectwrite: area left and down*/
221         x1= curarea->winrct.xmin+(curarea->winx-sima->zoom*xim)/2;
222         y1= curarea->winrct.ymin+(curarea->winy-sima->zoom*yim)/2;
223
224         x1-= sima->zoom*sima->xof;
225         y1-= sima->zoom*sima->yof;
226         
227         /* relative display right */
228         sima->v2d.cur.xmin= ((curarea->winrct.xmin - (float)x1)/sima->zoom);
229         sima->v2d.cur.xmax= sima->v2d.cur.xmin + ((float)curarea->winx/sima->zoom);
230         
231         /* relative display left */
232         sima->v2d.cur.ymin= ((curarea->winrct.ymin-(float)y1)/sima->zoom);
233         sima->v2d.cur.ymax= sima->v2d.cur.ymin + ((float)curarea->winy/sima->zoom);
234         
235         if(mode=='f') {         
236                 sima->v2d.cur.xmin/= xim;
237                 sima->v2d.cur.xmax/= xim;
238                 sima->v2d.cur.ymin/= yim;
239                 sima->v2d.cur.ymax/= yim;
240         }
241 }
242
243 /* check for facelesect, and set active image */
244 void what_image(SpaceImage *sima)
245 {
246         if(             (sima->mode!=SI_TEXTURE) ||
247                         (sima->image && sima->image->source==IMA_SRC_VIEWER) ||
248                         (G.obedit != OBACT) ||
249                         (G.editMesh==NULL) ||
250                         (sima->pin)
251         ) {
252                 return;
253         }
254         
255         /* viewer overrides uv editmode */
256         if (EM_texFaceCheck()) {
257                 MTFace *activetf;
258                 
259                 sima->image= NULL;
260                 
261                 activetf = get_active_mtface(NULL, NULL, 1); /* partially selected face is ok */
262                 
263                 if(activetf && activetf->mode & TF_TEX) {
264                         /* done need to check for pin here, see above */
265                         /*if (!sima->pin)*/
266                         sima->image= activetf->tpage;
267                         
268                         if(sima->flag & SI_EDITTILE);
269                         else sima->curtile= activetf->tile;
270                         
271                         if(sima->image) {
272                                 if(activetf->mode & TF_TILES)
273                                         sima->image->tpageflag |= IMA_TILES;
274                                 else sima->image->tpageflag &= ~IMA_TILES;
275                         }
276                 }
277         }
278 }
279
280 /* after a what_image(), this call will give ibufs, includes the spare image */
281 ImBuf *imagewindow_get_ibuf(SpaceImage *sima)
282 {
283         if(G.sima->image) {
284                 /* check for spare */
285                 if(sima->image->type==IMA_TYPE_R_RESULT && BIF_show_render_spare())
286                         return BIF_render_spare_imbuf();
287                 else
288                         return BKE_image_get_ibuf(sima->image, &sima->iuser);
289         }
290         return NULL;
291 }
292
293 /*
294  * dotile -     1, set the tile flag (from the space image)
295  *                      2, set the tile index for the faces. 
296  * */
297 void image_set_tile(SpaceImage *sima, int dotile)
298 {
299         MTFace *tface;
300         EditMesh *em = G.editMesh;
301         EditFace *efa;
302         
303         if(!sima->image || sima->mode!=SI_TEXTURE || !EM_texFaceCheck())
304                 return;
305         
306         /* skip assigning these procedural images... */
307         if(sima->image && (sima->image->type==IMA_TYPE_R_RESULT || sima->image->type==IMA_TYPE_COMPOSITE))
308                 return;
309         
310         for (efa= em->faces.first; efa; efa= efa->next) {
311                 tface = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
312                 if (efa->h==0 && efa->f & SELECT) {
313                         if (dotile==1) {
314                                 /* set tile flag */
315                                 if (sima->image->tpageflag & IMA_TILES) {
316                                         tface->mode |= TF_TILES;
317                                 } else {
318                                         tface->mode &= ~TF_TILES;
319                                 }
320                         } else if (dotile==2) {
321                                 /* set tile index */
322                                 tface->tile= sima->curtile;
323                         }
324                 }
325         }
326         object_uvs_changed(OBACT);
327         allqueue(REDRAWBUTSEDIT, 0);
328 }
329
330
331
332 void uvco_to_areaco(float *vec, short *mval)
333 {
334         float x, y;
335
336         mval[0]= IS_CLIPPED;
337         
338         x= (vec[0] - G.v2d->cur.xmin)/(G.v2d->cur.xmax-G.v2d->cur.xmin);
339         y= (vec[1] - G.v2d->cur.ymin)/(G.v2d->cur.ymax-G.v2d->cur.ymin);
340
341         if(x>=0.0 && x<=1.0) {
342                 if(y>=0.0 && y<=1.0) {          
343                         mval[0]= G.v2d->mask.xmin + x*(G.v2d->mask.xmax-G.v2d->mask.xmin);
344                         mval[1]= G.v2d->mask.ymin + y*(G.v2d->mask.ymax-G.v2d->mask.ymin);
345                 }
346         }
347 }
348
349 void uvco_to_areaco_noclip(float *vec, int *mval)
350 {
351         float x, y;
352
353         mval[0]= IS_CLIPPED;
354         
355         x= (vec[0] - G.v2d->cur.xmin)/(G.v2d->cur.xmax-G.v2d->cur.xmin);
356         y= (vec[1] - G.v2d->cur.ymin)/(G.v2d->cur.ymax-G.v2d->cur.ymin);
357
358         x= G.v2d->mask.xmin + x*(G.v2d->mask.xmax-G.v2d->mask.xmin);
359         y= G.v2d->mask.ymin + y*(G.v2d->mask.ymax-G.v2d->mask.ymin);
360         
361         mval[0]= x;
362         mval[1]= y;
363 }
364
365 static void drawcursor_sima(float xuser_asp, float yuser_asp)
366 {
367         int wi, hi;
368         float w, h;
369         
370         if (    !G.obedit ||    /* only draw cursor in editmode */
371                         !CustomData_has_layer(&G.editMesh->fdata, CD_MTFACE) || /* must have UV's */
372                         (G.sima->image && G.sima->flag & SI_DRAWTOOL) /* cant be painting */
373                 )       return;
374         
375         transform_width_height_tface_uv(&wi, &hi);
376         w = (((float)wi)/256.0f)*G.sima->zoom * xuser_asp;
377         h = (((float)hi)/256.0f)*G.sima->zoom * yuser_asp;
378         
379         cpack(0xFFFFFF);
380         glTranslatef(G.v2d->cursor[0], G.v2d->cursor[1], 0.0f);  
381         fdrawline(-0.05/w, 0, 0, 0.05/h);
382         fdrawline(0, 0.05/h, 0.05/w, 0);
383         fdrawline(0.05/w, 0, 0, -0.05/h);
384         fdrawline(0, -0.05/h, -0.05/w, 0);
385         
386         setlinestyle(4);
387         cpack(0xFF);
388         fdrawline(-0.05/w, 0, 0, 0.05/h);
389         fdrawline(0, 0.05/h, 0.05/w, 0);
390         fdrawline(0.05/w, 0, 0, -0.05/h);
391         fdrawline(0, -0.05/h, -0.05/w, 0);
392         
393         
394         setlinestyle(0);
395         cpack(0x0);
396         fdrawline(-0.020/w, 0, -0.1/w, 0);
397         fdrawline(0.1/w, 0, .020/w, 0);
398         fdrawline(0, -0.020/h, 0, -0.1/h);
399         fdrawline(0, 0.1/h, 0, 0.020/h);
400         
401         setlinestyle(1);
402         cpack(0xFFFFFF);
403         fdrawline(-0.020/w, 0, -0.1/w, 0);
404         fdrawline(0.1/w, 0, .020/w, 0);
405         fdrawline(0, -0.020/h, 0, -0.1/h);
406         fdrawline(0, 0.1/h, 0, 0.020/h);
407         
408         glTranslatef(-G.v2d->cursor[0], -G.v2d->cursor[1], 0.0f);
409         setlinestyle(0);
410 }
411
412 // checks if we are selecting only faces
413 int draw_uvs_face_check(void)
414 {
415         if (G.sima==NULL) {
416                 return 0;
417         }
418         if (G.sima->flag & SI_SYNC_UVSEL) {
419                 if (G.scene->selectmode == SCE_SELECT_FACE) {
420                         return 2;
421                 } else if (G.scene->selectmode & SCE_SELECT_FACE) {
422                         return 1;
423                 } 
424         } else {
425                 if (G.sima->selectmode == SI_SELECT_FACE) {
426                         return 1;
427                 }
428         }
429         return 0;
430 }
431
432 void uv_center(float uv[][2], float cent[2], void * isquad)
433 {
434
435         if (isquad) {
436                 cent[0] = (uv[0][0] + uv[1][0] + uv[2][0] + uv[3][0]) / 4.0;
437                 cent[1] = (uv[0][1] + uv[1][1] + uv[2][1] + uv[3][1]) / 4.0;            
438         } else {
439                 cent[0] = (uv[0][0] + uv[1][0] + uv[2][0]) / 3.0;
440                 cent[1] = (uv[0][1] + uv[1][1] + uv[2][1]) / 3.0;               
441         }
442 }
443
444 static float uv_area(float uv[][2], int quad)
445 {
446         if (quad) {
447                 return AreaF2Dfl(uv[0], uv[1], uv[2]) + AreaF2Dfl(uv[0], uv[2], uv[3]); 
448         } else { 
449                 return AreaF2Dfl(uv[0], uv[1], uv[2]); 
450         }
451 }
452
453 void uv_copy_aspect(float uv_orig[][2], float uv[][2], float aspx, float aspy)
454 {
455         uv[0][0] = uv_orig[0][0]*aspx;
456         uv[0][1] = uv_orig[0][1]*aspy;
457         
458         uv[1][0] = uv_orig[1][0]*aspx;
459         uv[1][1] = uv_orig[1][1]*aspy;
460         
461         uv[2][0] = uv_orig[2][0]*aspx;
462         uv[2][1] = uv_orig[2][1]*aspy;
463         
464         uv[3][0] = uv_orig[3][0]*aspx;
465         uv[3][1] = uv_orig[3][1]*aspy;
466 }
467
468 /* draws uv's in the image space */
469 void draw_uvs_sima(void)
470 {
471         MTFace *tface,*activetface = NULL;
472         EditMesh *em = G.editMesh;
473         EditFace *efa, *efa_act;
474         
475         char col1[4], col2[4];
476         float pointsize;
477         int drawface;
478         int lastsel, sel;
479         
480         if (!G.obedit || !CustomData_has_layer(&em->fdata, CD_MTFACE))
481                 return;
482         
483         drawface = draw_uvs_face_check();
484         
485         calc_image_view(G.sima, 'f');   /* float */
486         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
487         glLoadIdentity();
488         
489         
490         if(G.sima->flag & SI_DRAWTOOL) {
491                 /* draws the grey mesh when painting */
492                 glColor3ub(112, 112, 112);
493                 for (efa= em->faces.first; efa; efa= efa->next) {
494                         tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
495                         glBegin(GL_LINE_LOOP);
496                         glVertex2fv(tface->uv[0]);
497                         glVertex2fv(tface->uv[1]);
498                         glVertex2fv(tface->uv[2]);
499                         if(efa->v4) glVertex2fv(tface->uv[3]);
500                         glEnd();
501                 }
502                 return; /* only draw shadow mesh */
503         } else if (G.sima->flag & SI_DRAWSHADOW) {
504                 /* draw shadow mesh - this is the mesh with the modifier applied */
505                 glColor3ub(112, 112, 112);
506                 if (    em->derivedFinal &&
507                                 em->derivedFinal->drawUVEdges &&
508                                 CustomData_has_layer(&em->derivedFinal->faceData, CD_MTFACE)
509                 ) {
510                         /* we can use the existing final mesh */
511                         glColor3ub(112, 112, 112);
512                         em->derivedFinal->drawUVEdges(em->derivedFinal);
513                 } else {
514                         DerivedMesh *finalDM, *cageDM;
515                         
516                         /* draw final mesh with modifiers applied */
517                         cageDM = editmesh_get_derived_cage_and_final(&finalDM, CD_MASK_BAREMESH | CD_MASK_MTFACE);
518                         
519                         if              (finalDM->drawUVEdges &&
520                                         DM_get_face_data_layer(finalDM, CD_MTFACE) &&
521                                         /* When sync selection is enabled, all faces are drawn (except for hidden)
522                                          * so if cage is the same as the final, theres no point in drawing the shadowmesh. */
523                                         !((G.sima->flag & SI_SYNC_UVSEL && cageDM==finalDM))
524                         ) {
525                                 glColor3ub(112, 112, 112);
526                                 finalDM->drawUVEdges(finalDM);
527                         }
528                         
529                         if (cageDM != finalDM)
530                                 cageDM->release(cageDM);
531                         finalDM->release(finalDM);
532                 }
533         }
534         
535         activetface = get_active_mtface(&efa_act, NULL, 0); /* will be set to NULL if hidden */
536                 
537         
538         if (G.sima->flag & SI_DRAW_STRETCH) {
539                 float col[4];
540                 float aspx, aspy;
541                 float tface_uv[4][2];
542                 
543                 transform_aspect_ratio_tface_uv(&aspx, &aspy);
544                 
545                 switch (G.sima->dt_uvstretch) {
546                         case SI_UVDT_STRETCH_AREA:
547                         {
548                                 float totarea=0.0f, totuvarea=0.0f, areadiff, uvarea, area;
549                                 
550                                 for (efa= em->faces.first; efa; efa= efa->next) {
551                                         tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
552                                         uv_copy_aspect(tface->uv, tface_uv, aspx, aspy);
553
554                                         totarea += EM_face_area(efa);
555                                         //totuvarea += tface_area(tface, efa->v4!=0);
556                                         totuvarea += uv_area(tface_uv, efa->v4!=0);
557                                         
558                                         if (simaFaceDraw_Check(efa, tface)) {
559                                                 efa->tmp.p = tface;
560                                         } else {
561                                                 if (tface == activetface)
562                                                         activetface= NULL;
563                                                 efa->tmp.p = NULL;
564                                         }
565                                 }
566                                 
567                                 if (totarea < FLT_EPSILON || totuvarea < FLT_EPSILON) {
568                                         col[0] = 1.0;
569                                         col[1] = col[2] = 0.0;
570                                         glColor3fv(col);
571                                         for (efa= em->faces.first; efa; efa= efa->next) {
572                                                 if ((tface=(MTFace *)efa->tmp.p)) {
573                                                         glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
574                                                                 glVertex2fv(tface->uv[0]);
575                                                                 glVertex2fv(tface->uv[1]);
576                                                                 glVertex2fv(tface->uv[2]);
577                                                                 if(efa->v4) glVertex2fv(tface->uv[3]);
578                                                         glEnd();
579                                                 }
580                                         }
581                                 } else {
582                                         for (efa= em->faces.first; efa; efa= efa->next) {
583                                                 if ((tface=(MTFace *)efa->tmp.p)) {
584                                                         area = EM_face_area(efa) / totarea;
585                                                         uv_copy_aspect(tface->uv, tface_uv, aspx, aspy);
586                                                         //uvarea = tface_area(tface, efa->v4!=0) / totuvarea;
587                                                         uvarea = uv_area(tface_uv, efa->v4!=0) / totuvarea;
588                                                         
589                                                         if (area < FLT_EPSILON || uvarea < FLT_EPSILON) {
590                                                                 areadiff = 1.0;
591                                                         } else if (area>uvarea) {
592                                                                 areadiff = 1.0-(uvarea/area);
593                                                         } else {
594                                                                 areadiff = 1.0-(area/uvarea);
595                                                         }
596                                                         
597                                                         weight_to_rgb(areadiff, col, col+1, col+2);
598                                                         glColor3fv(col);
599                                                         
600                                                         glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
601                                                                 glVertex2fv(tface->uv[0]);
602                                                                 glVertex2fv(tface->uv[1]);
603                                                                 glVertex2fv(tface->uv[2]);
604                                                                 if(efa->v4) glVertex2fv(tface->uv[3]);
605                                                         glEnd();
606                                                 }
607                                         }
608                                 }
609                                 break;
610                         }
611                         case SI_UVDT_STRETCH_ANGLE:
612                         {
613                                 float uvang1,uvang2,uvang3,uvang4;
614                                 float ang1,ang2,ang3,ang4;
615                                 float av1[3], av2[3], av3[3], av4[3]; /* use for 2d and 3d  angle vectors */
616                                 float a;
617                                 
618                                 col[3] = 0.5; /* hard coded alpha, not that nice */
619                                 
620                                 glShadeModel(GL_SMOOTH);
621                                 
622                                 for (efa= em->faces.first; efa; efa= efa->next) {
623                                         tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
624                                         
625                                         if (simaFaceDraw_Check(efa, tface)) {
626                                                 efa->tmp.p = tface;
627                                                 uv_copy_aspect(tface->uv, tface_uv, aspx, aspy);
628                                                 if (efa->v4) {
629                                                         
630 #if 0                                           /* Simple but slow, better reuse normalized vectors */
631                                                         uvang1 = VecAngle3_2D(tface_uv[3], tface_uv[0], tface_uv[1]);
632                                                         ang1 = VecAngle3(efa->v4->co, efa->v1->co, efa->v2->co);
633                                                         
634                                                         uvang2 = VecAngle3_2D(tface_uv[0], tface_uv[1], tface_uv[2]);
635                                                         ang2 = VecAngle3(efa->v1->co, efa->v2->co, efa->v3->co);
636                                                         
637                                                         uvang3 = VecAngle3_2D(tface_uv[1], tface_uv[2], tface_uv[3]);
638                                                         ang3 = VecAngle3(efa->v2->co, efa->v3->co, efa->v4->co);
639                                                         
640                                                         uvang4 = VecAngle3_2D(tface_uv[2], tface_uv[3], tface_uv[0]);
641                                                         ang4 = VecAngle3(efa->v3->co, efa->v4->co, efa->v1->co);
642 #endif
643                                                         
644                                                         /* uv angles */
645                                                         VECSUB2D(av1, tface_uv[3], tface_uv[0]); Normalize2(av1);
646                                                         VECSUB2D(av2, tface_uv[0], tface_uv[1]); Normalize2(av2);
647                                                         VECSUB2D(av3, tface_uv[1], tface_uv[2]); Normalize2(av3);
648                                                         VECSUB2D(av4, tface_uv[2], tface_uv[3]); Normalize2(av4);
649                                                         
650                                                         /* This is the correct angle however we are only comparing angles
651                                                          * uvang1 = 90-((NormalizedVecAngle2_2D(av1, av2) * 180.0/M_PI)-90);*/
652                                                         uvang1 = NormalizedVecAngle2_2D(av1, av2)*180.0/M_PI;
653                                                         uvang2 = NormalizedVecAngle2_2D(av2, av3)*180.0/M_PI;
654                                                         uvang3 = NormalizedVecAngle2_2D(av3, av4)*180.0/M_PI;
655                                                         uvang4 = NormalizedVecAngle2_2D(av4, av1)*180.0/M_PI;
656                                                         
657                                                         /* 3d angles */
658                                                         VECSUB(av1, efa->v4->co, efa->v1->co); Normalize(av1);
659                                                         VECSUB(av2, efa->v1->co, efa->v2->co); Normalize(av2);
660                                                         VECSUB(av3, efa->v2->co, efa->v3->co); Normalize(av3);
661                                                         VECSUB(av4, efa->v3->co, efa->v4->co); Normalize(av4);
662                                                         
663                                                         /* This is the correct angle however we are only comparing angles
664                                                          * ang1 = 90-((NormalizedVecAngle2(av1, av2) * 180.0/M_PI)-90);*/
665                                                         ang1 = NormalizedVecAngle2(av1, av2)*180.0/M_PI;
666                                                         ang2 = NormalizedVecAngle2(av2, av3)*180.0/M_PI;
667                                                         ang3 = NormalizedVecAngle2(av3, av4)*180.0/M_PI;
668                                                         ang4 = NormalizedVecAngle2(av4, av1)*180.0/M_PI;
669                                                         
670                                                         glBegin(GL_QUADS);
671                                                         
672                                                         /* This simple makes the angles display worse then they really are ;)
673                                                          * 1.0-pow((1.0-a), 2) */
674                                                         
675                                                         a = fabs(uvang1-ang1)/180.0;
676                                                         weight_to_rgb(1.0-pow((1.0-a), 2), col, col+1, col+2);
677                                                         glColor3fv(col);
678                                                         glVertex2fv(tface->uv[0]);
679                                                         a = fabs(uvang2-ang2)/180.0;
680                                                         weight_to_rgb(1.0-pow((1.0-a), 2), col, col+1, col+2);
681                                                         glColor3fv(col);
682                                                         glVertex2fv(tface->uv[1]);
683                                                         a = fabs(uvang3-ang3)/180.0;
684                                                         weight_to_rgb(1.0-pow((1.0-a), 2), col, col+1, col+2);
685                                                         glColor3fv(col);
686                                                         glVertex2fv(tface->uv[2]);
687                                                         a = fabs(uvang4-ang4)/180.0;
688                                                         weight_to_rgb(1.0-pow((1.0-a), 2), col, col+1, col+2);
689                                                         glColor3fv(col);
690                                                         glVertex2fv(tface->uv[3]);
691                                                         
692                                                 } else {
693 #if 0                                           /* Simple but slow, better reuse normalized vectors */
694                                                         uvang1 = VecAngle3_2D(tface_uv[2], tface_uv[0], tface_uv[1]);
695                                                         ang1 = VecAngle3(efa->v3->co, efa->v1->co, efa->v2->co);
696                                                         
697                                                         uvang2 = VecAngle3_2D(tface_uv[0], tface_uv[1], tface_uv[2]);
698                                                         ang2 = VecAngle3(efa->v1->co, efa->v2->co, efa->v3->co);
699                                                         
700                                                         uvang3 = 180-(uvang1+uvang2);
701                                                         ang3 = 180-(ang1+ang2);
702 #endif                                          
703                                                         
704                                                         /* uv angles */
705                                                         VECSUB2D(av1, tface_uv[2], tface_uv[0]); Normalize2(av1);
706                                                         VECSUB2D(av2, tface_uv[0], tface_uv[1]); Normalize2(av2);
707                                                         VECSUB2D(av3, tface_uv[1], tface_uv[2]); Normalize2(av3);
708                                                         
709                                                         /* This is the correct angle however we are only comparing angles
710                                                          * uvang1 = 90-((NormalizedVecAngle2_2D(av1, av2) * 180.0/M_PI)-90); */
711                                                         uvang1 = NormalizedVecAngle2_2D(av1, av2)*180.0/M_PI;
712                                                         uvang2 = NormalizedVecAngle2_2D(av2, av3)*180.0/M_PI;
713                                                         uvang3 = NormalizedVecAngle2_2D(av3, av1)*180.0/M_PI;
714                                                         
715                                                         /* 3d angles */
716                                                         VECSUB(av1, efa->v3->co, efa->v1->co); Normalize(av1);
717                                                         VECSUB(av2, efa->v1->co, efa->v2->co); Normalize(av2);
718                                                         VECSUB(av3, efa->v2->co, efa->v3->co); Normalize(av3);
719                                                         /* This is the correct angle however we are only comparing angles
720                                                          * ang1 = 90-((NormalizedVecAngle2(av1, av2) * 180.0/M_PI)-90); */
721                                                         ang1 = NormalizedVecAngle2(av1, av2)*180.0/M_PI;
722                                                         ang2 = NormalizedVecAngle2(av2, av3)*180.0/M_PI;
723                                                         ang3 = NormalizedVecAngle2(av3, av1)*180.0/M_PI;
724                                                         
725                                                         /* This simple makes the angles display worse then they really are ;)
726                                                          * 1.0-pow((1.0-a), 2) */
727                                                         
728                                                         glBegin(GL_TRIANGLES);
729                                                         a = fabs(uvang1-ang1)/180.0;
730                                                         weight_to_rgb(1.0-pow((1.0-a), 2), col, col+1, col+2);
731                                                         glColor3fv(col);
732                                                         glVertex2fv(tface->uv[0]);
733                                                         a = fabs(uvang2-ang2)/180.0;
734                                                         weight_to_rgb(1.0-pow((1.0-a), 2), col, col+1, col+2);
735                                                         glColor3fv(col);
736                                                         glVertex2fv(tface->uv[1]);
737                                                         a = fabs(uvang3-ang3)/180.0;
738                                                         weight_to_rgb(1.0-pow((1.0-a), 2), col, col+1, col+2);
739                                                         glColor3fv(col);
740                                                         glVertex2fv(tface->uv[2]);
741                                                 }
742                                                 glEnd();
743                                         } else {
744                                                 if (tface == activetface)
745                                                         activetface= NULL;
746                                                 efa->tmp.p = NULL;
747                                         }
748                                 }
749                                 glShadeModel(GL_FLAT);
750                                 break;
751                         }
752                 }
753         } else if(G.f & G_DRAWFACES) {
754                 /* draw transparent faces */
755                 BIF_GetThemeColor4ubv(TH_FACE, col1);
756                 BIF_GetThemeColor4ubv(TH_FACE_SELECT, col2);
757                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
758                 glEnable(GL_BLEND);
759                 
760                 for (efa= em->faces.first; efa; efa= efa->next) {
761                         tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
762                         
763                         if (simaFaceDraw_Check(efa, tface)) {
764                                 efa->tmp.p = tface;
765                                 if (tface==activetface) continue; /* important the temp pointer is set above */
766                                 if( simaFaceSel_Check(efa, tface)) {
767                                         glColor4ubv((GLubyte *)col2);
768                                 } else {
769                                         glColor4ubv((GLubyte *)col1);
770                                 }
771                                         
772                                 glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
773                                         glVertex2fv(tface->uv[0]);
774                                         glVertex2fv(tface->uv[1]);
775                                         glVertex2fv(tface->uv[2]);
776                                         if(efa->v4) glVertex2fv(tface->uv[3]);
777                                 glEnd();
778                                 
779                         } else {
780                                 if (tface == activetface)
781                                         activetface= NULL;
782                                 efa->tmp.p = NULL;
783                         }
784                 }
785                 glDisable(GL_BLEND);
786         } else {
787                 /* would be nice to do this within a draw loop but most below are optional, so it would involve too many checks */
788                 for (efa= em->faces.first; efa; efa= efa->next) {
789                         tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
790                         if (simaFaceDraw_Check(efa, tface)) {           
791                                 efa->tmp.p = tface;
792                         } else {
793                                 if (tface == activetface)
794                                         activetface= NULL;
795                                 efa->tmp.p = NULL;
796                         }
797                 }
798                 
799         }
800         
801         if (activetface) {
802                 glEnable(GL_BLEND);
803                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
804                 BIF_ThemeColor4(TH_EDITMESH_ACTIVE);
805                 glEnable(GL_POLYGON_STIPPLE);
806                 glPolygonStipple(stipple_quarttone);
807                 glBegin(efa_act->v4?GL_QUADS:GL_TRIANGLES);
808                         glVertex2fv(activetface->uv[0]);
809                         glVertex2fv(activetface->uv[1]);
810                         glVertex2fv(activetface->uv[2]);
811                         if(efa_act->v4) glVertex2fv(activetface->uv[3]);
812                 glEnd();
813                 glDisable(GL_POLYGON_STIPPLE);
814                 glDisable(GL_BLEND);
815         }
816         
817         if (G.sima->flag & SI_SMOOTH_UV) {
818                 glEnable( GL_LINE_SMOOTH );
819                 glEnable(GL_BLEND);
820                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
821         }
822         
823         switch (G.sima->dt_uv) {
824         case SI_UVDT_DASH:
825                 for (efa= em->faces.first; efa; efa= efa->next) {
826 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
827 //                      if (simaFaceDraw_Check(efa, tface)) {
828                         
829                         /*this is a shortcut to do the same as above but a faster for drawing */
830                         if ((tface=(MTFace *)efa->tmp.p)) {
831                         
832                                 cpack(0x111111);
833                                 glBegin(GL_LINE_LOOP);
834                                         glVertex2fv(tface->uv[0]);
835                                         glVertex2fv(tface->uv[1]);
836                                         glVertex2fv(tface->uv[2]);
837                                         if(efa->v4) glVertex2fv(tface->uv[3]);
838                                 glEnd();
839                         
840                                 setlinestyle(2);
841                                 cpack(0x909090);
842                                 glBegin(GL_LINE_STRIP);
843                                         glVertex2fv(tface->uv[0]);
844                                         glVertex2fv(tface->uv[1]);
845                                 glEnd();
846         
847                                 glBegin(GL_LINE_STRIP);
848                                         glVertex2fv(tface->uv[0]);
849                                         if(efa->v4) glVertex2fv(tface->uv[3]);
850                                         else glVertex2fv(tface->uv[2]);
851                                 glEnd();
852         
853                                 glBegin(GL_LINE_STRIP);
854                                         glVertex2fv(tface->uv[1]);
855                                         glVertex2fv(tface->uv[2]);
856                                         if(efa->v4) glVertex2fv(tface->uv[3]);
857                                 glEnd();
858                                 setlinestyle(0);
859                         }
860                 }
861                 break;
862         case SI_UVDT_BLACK: /* black/white */
863         case SI_UVDT_WHITE: 
864                 cpack((G.sima->dt_uv==SI_UVDT_WHITE) ? 0xFFFFFF : 0x0);
865                 for (efa= em->faces.first; efa; efa= efa->next) {
866 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
867 //                      if (simaFaceDraw_Check(efa, tface)) {
868                         
869                         /*this is a shortcut to do the same as above but a faster for drawing */
870                         if ((tface=(MTFace *)efa->tmp.p)) {
871                         
872                                 glBegin(GL_LINE_LOOP);
873                                         glVertex2fv(tface->uv[0]);
874                                         glVertex2fv(tface->uv[1]);
875                                         glVertex2fv(tface->uv[2]);
876                                         if(efa->v4) glVertex2fv(tface->uv[3]);
877                                 glEnd();
878                         }
879                 }
880                 break;
881         case SI_UVDT_OUTLINE:
882                 glLineWidth(3);
883                 cpack(0x0);
884                 
885                 for (efa= em->faces.first; efa; efa= efa->next) {
886 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
887 //                      if (simaFaceDraw_Check(efa, tface)) {
888                         
889                         /*this is a shortcut to do the same as above but a faster for drawing */
890                         if ((tface=(MTFace *)efa->tmp.p)) {
891                                 
892                                 glBegin(GL_LINE_LOOP);
893                                         glVertex2fv(tface->uv[0]);
894                                         glVertex2fv(tface->uv[1]);
895                                         glVertex2fv(tface->uv[2]);
896                                         if(efa->v4) glVertex2fv(tface->uv[3]);
897                                 glEnd();
898                         }
899                 }
900                 
901                 glLineWidth(1);
902                 col2[0] = col2[1] = col2[2] = 128; col2[3] = 255;
903                 glColor4ubv((unsigned char *)col2); 
904                 
905                 if (G.f & G_DRAWEDGES) {
906                         glShadeModel(GL_SMOOTH);
907                         BIF_GetThemeColor4ubv(TH_VERTEX_SELECT, col1);
908                         lastsel = sel = 0;
909
910                         for (efa= em->faces.first; efa; efa= efa->next) {
911         //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
912         //                      if (simaFaceDraw_Check(efa, tface)) {
913                                 
914                                 /*this is a shortcut to do the same as above but a faster for drawing */
915                                 if ((tface=(MTFace *)efa->tmp.p)) {
916                                         
917                                         glBegin(GL_LINE_LOOP);
918                                         sel = (simaUVSel_Check(efa, tface, 0) ? 1 : 0);
919                                         if (sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
920                                         glVertex2fv(tface->uv[0]);
921                                         
922                                         sel = simaUVSel_Check(efa, tface, 1) ? 1 : 0;
923                                         if (sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
924                                         glVertex2fv(tface->uv[1]);
925                                         
926                                         sel = simaUVSel_Check(efa, tface, 2) ? 1 : 0;
927                                         if (sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
928                                         glVertex2fv(tface->uv[2]);
929                                         
930                                         if(efa->v4) {
931                                                 sel = simaUVSel_Check(efa, tface, 3) ? 1 : 0;
932                                                 if (sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
933                                                 glVertex2fv(tface->uv[3]);
934                                         }
935                                         
936                                         glEnd();
937                                 }
938                         }
939                         glShadeModel(GL_FLAT);
940                 } else { /* No nice edges */
941                         
942                         for (efa= em->faces.first; efa; efa= efa->next) {
943         //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
944         //                      if (simaFaceDraw_Check(efa, tface)) {
945                                 
946                                 /*this is a shortcut to do the same as above but a faster for drawing */
947                                 if ((tface=(MTFace *)efa->tmp.p)) {
948                                         
949                                         glBegin(GL_LINE_LOOP);
950                                         glVertex2fv(tface->uv[0]);
951                                         glVertex2fv(tface->uv[1]);
952                                         glVertex2fv(tface->uv[2]);
953                                         if(efa->v4)
954                                                 glVertex2fv(tface->uv[3]);
955                                         glEnd();
956                                 }
957                         }
958                 }
959                 
960                 break;
961         }
962
963         if (G.sima->flag & SI_SMOOTH_UV) {
964                 glDisable( GL_LINE_SMOOTH);
965                 glDisable(GL_BLEND);
966         }
967
968         if (drawface) {
969                 // draw UV face points
970                 float cent[2];
971                 
972                 
973             /* unselected faces's */
974                 pointsize = BIF_GetThemeValuef(TH_FACEDOT_SIZE);
975                 // TODO - drawobject.c changes this value after - Investiagate!
976                 glPointSize(pointsize);
977                 
978                 BIF_ThemeColor(TH_WIRE);
979                 bglBegin(GL_POINTS);
980                 for (efa= em->faces.first; efa; efa= efa->next) {
981                         
982 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
983 //                      if (simaFaceDraw_Check(efa, tface)) {
984                         
985                         /*this is a shortcut to do the same as above but a faster for drawing */
986                         if ((tface=(MTFace *)efa->tmp.p)) {
987                                 if( ! simaFaceSel_Check(efa, tface) ) {
988                                         uv_center(tface->uv, cent, (void *)efa->v4);
989                                         bglVertex2fv(cent);
990                                 }
991                         }
992                 }
993                 bglEnd();
994                 /* selected faces's */
995                 BIF_ThemeColor(TH_FACE_DOT);
996                 bglBegin(GL_POINTS);
997                 for (efa= em->faces.first; efa; efa= efa->next) {
998                         
999 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1000 //                      if (simaFaceDraw_Check(efa, tface)) {
1001                         
1002                         /*this is a shortcut to do the same as above but a faster for drawing */
1003                         if ((tface=(MTFace *)efa->tmp.p)) {
1004                                 if( simaFaceSel_Check(efa, tface) ) {
1005                                         uv_center(tface->uv, cent, (void *)efa->v4);
1006                                         bglVertex2fv(cent);
1007                                 }
1008                         }
1009                 }
1010                 bglEnd();
1011         }
1012         
1013         if (drawface != 2) { /* 2 means Mesh Face Mode */
1014             /* unselected uv's */
1015                 BIF_ThemeColor(TH_VERTEX);
1016                 pointsize = BIF_GetThemeValuef(TH_VERTEX_SIZE);
1017                 glPointSize(pointsize);
1018         
1019                 bglBegin(GL_POINTS);
1020                 for (efa= em->faces.first; efa; efa= efa->next) {
1021                         
1022 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1023 //                      if (simaFaceDraw_Check(efa, tface)) {
1024                         
1025                         /*this is a shortcut to do the same as above but a faster for drawing */
1026                         if ((tface=(MTFace *)efa->tmp.p)) {
1027                         
1028                                 if(simaUVSel_Check(efa, tface, 0)); else bglVertex2fv(tface->uv[0]);
1029                                 if(simaUVSel_Check(efa, tface, 1)); else bglVertex2fv(tface->uv[1]);
1030                                 if(simaUVSel_Check(efa, tface, 2)); else bglVertex2fv(tface->uv[2]);
1031                                 if(efa->v4) {
1032                                         if(simaUVSel_Check(efa, tface, 3)); else bglVertex2fv(tface->uv[3]);
1033                                 }
1034                         }
1035                 }
1036                 bglEnd();
1037         
1038                 /* pinned uv's */
1039                 /* give odd pointsizes odd pin pointsizes */
1040             glPointSize(pointsize*2 + (((int)pointsize % 2)? (-1): 0));
1041                 cpack(0xFF);
1042         
1043                 bglBegin(GL_POINTS);
1044                 for (efa= em->faces.first; efa; efa= efa->next) {
1045 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1046 //                      if (simaFaceDraw_Check(efa, tface)) {
1047                         
1048                         /*this is a shortcut to do the same as above but a faster for drawing */
1049                         if ((tface=(MTFace *)efa->tmp.p)) {
1050                                 
1051                                 if(tface->unwrap & TF_PIN1) bglVertex2fv(tface->uv[0]);
1052                                 if(tface->unwrap & TF_PIN2) bglVertex2fv(tface->uv[1]);
1053                                 if(tface->unwrap & TF_PIN3) bglVertex2fv(tface->uv[2]);
1054                                 if(efa->v4) {
1055                                         if(tface->unwrap & TF_PIN4) bglVertex2fv(tface->uv[3]);
1056                                 }
1057                         }
1058                 }
1059                 bglEnd();
1060         
1061                 /* selected uv's */
1062                 BIF_ThemeColor(TH_VERTEX_SELECT);
1063             glPointSize(pointsize);
1064         
1065                 bglBegin(GL_POINTS);
1066                 for (efa= em->faces.first; efa; efa= efa->next) {
1067 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1068 //                      if (simaFaceDraw_Check(efa, tface)) {
1069                         
1070                         /*this is a shortcut to do the same as above but a faster for drawing */
1071                         if ((tface=(MTFace *)efa->tmp.p)) {
1072                         
1073                                 if(!simaUVSel_Check(efa, tface, 0)); else bglVertex2fv(tface->uv[0]);
1074                                 if(!simaUVSel_Check(efa, tface, 1)); else bglVertex2fv(tface->uv[1]);
1075                                 if(!simaUVSel_Check(efa, tface, 2)); else bglVertex2fv(tface->uv[2]);
1076                                 if(efa->v4) {
1077                                         if(!simaUVSel_Check(efa, tface, 3)); else bglVertex2fv(tface->uv[3]);
1078                                 }
1079                         }
1080                 }
1081                 bglEnd();       
1082         }
1083         glPointSize(1.0);
1084 }
1085
1086 static unsigned int *get_part_from_ibuf(ImBuf *ibuf, short startx, short starty, short endx, short endy)
1087 {
1088         unsigned int *rt, *rp, *rectmain;
1089         short y, heigth, len;
1090
1091         /* the right offset in rectot */
1092
1093         rt= ibuf->rect+ (starty*ibuf->x+ startx);
1094
1095         len= (endx-startx);
1096         heigth= (endy-starty);
1097
1098         rp=rectmain= MEM_mallocN(heigth*len*sizeof(int), "rect");
1099         
1100         for(y=0; y<heigth; y++) {
1101                 memcpy(rp, rt, len*4);
1102                 rt+= ibuf->x;
1103                 rp+= len;
1104         }
1105         return rectmain;
1106 }
1107
1108 static void draw_image_transform(ImBuf *ibuf, float xuser_asp, float yuser_asp)
1109 {
1110         if(G.moving) {
1111                 float aspx, aspy, center[3];
1112
1113         BIF_drawConstraint();
1114
1115                 if(ibuf==0 || ibuf->rect==0 || ibuf->x==0 || ibuf->y==0) {
1116                         aspx= aspy= 1.0;
1117                 }
1118                 else {
1119                         aspx= (256.0/ibuf->x) * xuser_asp;
1120                         aspy= (256.0/ibuf->y) * yuser_asp;
1121                 }
1122                 BIF_getPropCenter(center);
1123
1124                 /* scale and translate the circle into place and draw it */
1125                 glPushMatrix();
1126                 glScalef(aspx, aspy, 1.0);
1127                 glTranslatef((1/aspx)*center[0] - center[0],
1128                              (1/aspy)*center[1] - center[1], 0.0);
1129
1130                 BIF_drawPropCircle();
1131
1132                 glPopMatrix();
1133         }
1134 }
1135
1136 static void draw_image_view_tool(void)
1137 {
1138         ToolSettings *settings= G.scene->toolsettings;
1139         Brush *brush= settings->imapaint.brush;
1140         short mval[2];
1141         float radius;
1142         int draw= 0;
1143
1144         if(brush) {
1145                 if(settings->imapaint.flag & IMAGEPAINT_DRAWING) {
1146                         if(settings->imapaint.flag & IMAGEPAINT_DRAW_TOOL_DRAWING)
1147                                 draw= 1;
1148                 }
1149                 else if(settings->imapaint.flag & IMAGEPAINT_DRAW_TOOL)
1150                         draw= 1;
1151                 
1152                 if(draw) {
1153                         getmouseco_areawin(mval);
1154
1155                         radius= brush->size*G.sima->zoom/2;
1156                         fdrawXORcirc(mval[0], mval[1], radius);
1157
1158                         if (brush->innerradius != 1.0) {
1159                                 radius *= brush->innerradius;
1160                                 fdrawXORcirc(mval[0], mval[1], radius);
1161                         }
1162                 }
1163         }
1164 }
1165
1166 /* ************ panel stuff ************* */
1167
1168 /* this function gets the values for cursor and vertex number buttons */
1169 static void image_transform_but_attr(int *imx, int *imy, int *step, int *digits) /*, float *xcoord, float *ycoord)*/
1170 {
1171         ImBuf *ibuf= imagewindow_get_ibuf(G.sima);
1172         if(ibuf) {
1173                 *imx= ibuf->x;
1174                 *imy= ibuf->y;
1175         }
1176         
1177         if (G.sima->flag & SI_COORDFLOATS) {
1178                 *step= 1;
1179                 *digits= 3;
1180         }
1181         else {
1182                 *step= 100;
1183                 *digits= 2;
1184         }
1185 }
1186
1187
1188 /* is used for both read and write... */
1189 void image_editvertex_buts(uiBlock *block)
1190 {
1191         static float ocent[2];
1192         float cent[2]= {0.0, 0.0};
1193         int imx= 256, imy= 256;
1194         int nactive= 0, step, digits;
1195         EditMesh *em = G.editMesh;
1196         EditFace *efa;
1197         MTFace *tf;
1198         
1199         if( is_uv_tface_editing_allowed_silent()==0 ) return;
1200         
1201         image_transform_but_attr(&imx, &imy, &step, &digits);
1202         
1203         for (efa= em->faces.first; efa; efa= efa->next) {
1204                 tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1205                 if (simaFaceDraw_Check(efa, tf)) {
1206                         
1207                         if (simaUVSel_Check(efa, tf, 0)) {
1208                                 cent[0]+= tf->uv[0][0];
1209                                 cent[1]+= tf->uv[0][1];
1210                                 nactive++;
1211                         }
1212                         if (simaUVSel_Check(efa, tf, 1)) {
1213                                 cent[0]+= tf->uv[1][0];
1214                                 cent[1]+= tf->uv[1][1];
1215                                 nactive++;
1216                         }
1217                         if (simaUVSel_Check(efa, tf, 2)) {
1218                                 cent[0]+= tf->uv[2][0];
1219                                 cent[1]+= tf->uv[2][1];
1220                                 nactive++;
1221                         }
1222                         if (efa->v4 && simaUVSel_Check(efa, tf, 3)) {
1223                                 cent[0]+= tf->uv[3][0];
1224                                 cent[1]+= tf->uv[3][1];
1225                                 nactive++;
1226                         }
1227                 }
1228         }
1229                 
1230         if(block) {     // do the buttons
1231                 if (nactive) {
1232                         ocent[0]= cent[0]/nactive;
1233                         ocent[1]= cent[1]/nactive;
1234                         if (G.sima->flag & SI_COORDFLOATS) {
1235                         } else {
1236                                 ocent[0] *= imx;
1237                                 ocent[1] *= imy;
1238                         }
1239                         
1240                         //uiBlockBeginAlign(block);
1241                         if(nactive==1) {
1242                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Vertex X:",       10, 10, 145, 19, &ocent[0], -10*imx, 10.0*imx, step, digits, "");
1243                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Vertex Y:",       165, 10, 145, 19, &ocent[1], -10*imy, 10.0*imy, step, digits, "");
1244                         }
1245                         else {
1246                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Median X:",       10, 10, 145, 19, &ocent[0], -10*imx, 10.0*imx, step, digits, "");
1247                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Median Y:",       165, 10, 145, 19, &ocent[1], -10*imy, 10.0*imy, step, digits, "");
1248                         }
1249                         //uiBlockEndAlign(block);
1250                 }
1251         }
1252         else {  // apply event
1253                 float delta[2];
1254                 
1255                 cent[0]= cent[0]/nactive;
1256                 cent[1]= cent[1]/nactive;
1257                         
1258                 if (G.sima->flag & SI_COORDFLOATS) {
1259                         delta[0]= ocent[0]-cent[0];
1260                         delta[1]= ocent[1]-cent[1];
1261                 }
1262                 else {
1263                         delta[0]= ocent[0]/imx - cent[0];
1264                         delta[1]= ocent[1]/imy - cent[1];
1265                 }
1266
1267                 for (efa= em->faces.first; efa; efa= efa->next) {
1268                         tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1269                         if (simaFaceDraw_Check(efa, tf)) {
1270                                 if (simaUVSel_Check(efa, tf, 0)) {
1271                                         tf->uv[0][0]+= delta[0];
1272                                         tf->uv[0][1]+= delta[1];
1273                                 }
1274                                 if (simaUVSel_Check(efa, tf, 1)) {
1275                                         tf->uv[1][0]+= delta[0];
1276                                         tf->uv[1][1]+= delta[1];
1277                                 }
1278                                 if (simaUVSel_Check(efa, tf, 2)) {
1279                                         tf->uv[2][0]+= delta[0];
1280                                         tf->uv[2][1]+= delta[1];
1281                                 }
1282                                 if (efa->v4 && simaUVSel_Check(efa, tf, 3)) {
1283                                         tf->uv[3][0]+= delta[0];
1284                                         tf->uv[3][1]+= delta[1];
1285                                 }
1286                         }
1287                 }
1288                         
1289                 allqueue(REDRAWVIEW3D, 0);
1290                 allqueue(REDRAWIMAGE, 0);
1291         }
1292 }
1293
1294
1295 /* is used for both read and write... */
1296 void image_editcursor_buts(uiBlock *block)
1297 {
1298         static float ocent[2];
1299         int imx= 256, imy= 256;
1300         int step, digits;
1301         
1302         if( is_uv_tface_editing_allowed_silent()==0 ) return;
1303         
1304         image_transform_but_attr(&imx, &imy, &step, &digits);
1305                 
1306         if(block) {     // do the buttons
1307                 ocent[0]= G.v2d->cursor[0];
1308                 ocent[1]= G.v2d->cursor[1];
1309                 if (G.sima->flag & SI_COORDFLOATS) {
1310                 } else {
1311                         ocent[0] *= imx;
1312                         ocent[1] *= imy;
1313                 }
1314                 
1315                 uiBlockBeginAlign(block);
1316                 uiDefButF(block, NUM, B_CURSOR_IMAGE, "Cursor X:",      165, 120, 145, 19, &ocent[0], -10*imx, 10.0*imx, step, digits, "");
1317                 uiDefButF(block, NUM, B_CURSOR_IMAGE, "Cursor Y:",      165, 100, 145, 19, &ocent[1], -10*imy, 10.0*imy, step, digits, "");
1318                 uiBlockEndAlign(block);
1319         }
1320         else {  // apply event
1321                 if (G.sima->flag & SI_COORDFLOATS) {
1322                         G.v2d->cursor[0]= ocent[0];
1323                         G.v2d->cursor[1]= ocent[1];
1324                 }
1325                 else {
1326                         G.v2d->cursor[0]= ocent[0]/imx;
1327                         G.v2d->cursor[1]= ocent[1]/imy;
1328                 }
1329                 allqueue(REDRAWIMAGE, 0);
1330         }
1331 }
1332
1333
1334 void image_info(Image *ima, ImBuf *ibuf, char *str)
1335 {
1336         int ofs= 0;
1337         
1338         str[0]= 0;
1339         
1340         if(ima==NULL) return;
1341         if(ibuf==NULL) {
1342                 sprintf(str, "Can not get an image");
1343                 return;
1344         }
1345         
1346         if(ima->source==IMA_SRC_MOVIE) {
1347                 ofs= sprintf(str, "Movie ");
1348                 if(ima->anim) 
1349                         ofs+= sprintf(str+ofs, "%d frs", IMB_anim_get_duration(ima->anim));
1350         }
1351         else
1352                 ofs= sprintf(str, "Image ");
1353
1354         ofs+= sprintf(str+ofs, ": size %d x %d,", ibuf->x, ibuf->y);
1355         
1356         if(ibuf->rect_float) {
1357                 if(ibuf->channels!=4) {
1358                         sprintf(str+ofs, "%d float channel(s)", ibuf->channels);
1359                 }
1360                 else if(ibuf->depth==32)
1361                         strcat(str, " RGBA float");
1362                 else
1363                         strcat(str, " RGB float");
1364         }
1365         else {
1366                 if(ibuf->depth==32)
1367                         strcat(str, " RGBA byte");
1368                 else
1369                         strcat(str, " RGB byte");
1370         }
1371         if(ibuf->zbuf || ibuf->zbuf_float)
1372                 strcat(str, " + Z");
1373         
1374 }
1375
1376 static void image_panel_properties(short cntrl) // IMAGE_HANDLER_PROPERTIES
1377 {
1378         uiBlock *block;
1379         
1380         block= uiNewBlock(&curarea->uiblocks, "image_panel_properties", UI_EMBOSS, UI_HELV, curarea->win);
1381         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1382         uiSetPanelHandler(IMAGE_HANDLER_PROPERTIES);  // for close and esc
1383         if(uiNewPanel(curarea, block, "Image Properties", "Image", 10, 10, 318, 204)==0)
1384                 return;
1385         
1386         /* note, it draws no bottom half in facemode, for vertex buttons */
1387         uiblock_image_panel(block, &G.sima->image, &G.sima->iuser, B_REDR, B_REDR);
1388         image_editvertex_buts(block);
1389 }       
1390
1391 static void image_panel_game_properties(short cntrl)    // IMAGE_HANDLER_GAME_PROPERTIES
1392 {
1393         ImBuf *ibuf= BKE_image_get_ibuf(G.sima->image, &G.sima->iuser);
1394         uiBlock *block;
1395
1396         block= uiNewBlock(&curarea->uiblocks, "image_panel_game_properties", UI_EMBOSS, UI_HELV, curarea->win);
1397         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1398         uiSetPanelHandler(IMAGE_HANDLER_GAME_PROPERTIES);  // for close and esc
1399         if(uiNewPanel(curarea, block, "Real-time Properties", "Image", 10, 10, 318, 204)==0)
1400                 return;
1401
1402         if (ibuf) {
1403                 char str[128];
1404                 
1405                 image_info(G.sima->image, ibuf, str);
1406                 uiDefBut(block, LABEL, B_NOP, str,              10,180,300,19, 0, 0, 0, 0, 0, "");
1407
1408                 uiBlockBeginAlign(block);
1409                 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");
1410                 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");
1411                 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");
1412                 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");
1413                 uiBlockEndAlign(block);
1414
1415                 uiBlockBeginAlign(block);
1416                 uiDefButBitS(block, TOG, IMA_TILES, B_SIMAGETILE, "Tiles",      160,150,140,19, &G.sima->image->tpageflag, 0, 0, 0, 0, "Toggles use of tilemode for faces (Shift LMB to pick the tile for selected faces)");
1417                 uiDefButS(block, NUM, B_SIMA_REDR_IMA_3D, "X:",         160,130,70,19, &G.sima->image->xrep, 1.0, 16.0, 0, 0, "Sets the degree of repetition in the X direction");
1418                 uiDefButS(block, NUM, B_SIMA_REDR_IMA_3D, "Y:",         230,130,70,19, &G.sima->image->yrep, 1.0, 16.0, 0, 0, "Sets the degree of repetition in the Y direction");
1419                 uiBlockBeginAlign(block);
1420
1421                 uiBlockBeginAlign(block);
1422                 uiDefButBitS(block, TOG, IMA_CLAMP_U, B_SIMA3DVIEWDRAW, "ClampX",       160,100,70,19, &G.sima->image->tpageflag, 0, 0, 0, 0, "Disable texture repeating horizontaly");
1423                 uiDefButBitS(block, TOG, IMA_CLAMP_V, B_SIMA3DVIEWDRAW, "ClampY",       230,100,70,19, &G.sima->image->tpageflag, 0, 0, 0, 0, "Disable texture repeating vertically");
1424                 uiBlockEndAlign(block);
1425         }
1426 }
1427
1428 static void image_panel_view_properties(short cntrl)    // IMAGE_HANDLER_VIEW_PROPERTIES
1429 {
1430         uiBlock *block;
1431
1432         block= uiNewBlock(&curarea->uiblocks, "image_view_properties", UI_EMBOSS, UI_HELV, curarea->win);
1433         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1434         uiSetPanelHandler(IMAGE_HANDLER_VIEW_PROPERTIES);  // for close and esc
1435         if(uiNewPanel(curarea, block, "View Properties", "Image", 10, 10, 318, 204)==0)
1436                 return;
1437         
1438         
1439         uiDefButBitI(block, TOG, SI_DRAW_TILE, B_REDR, "Repeat Image",  10,160,140,19, &G.sima->flag, 0, 0, 0, 0, "Repeat/Tile the image display");
1440         uiDefButBitI(block, TOG, SI_COORDFLOATS, B_REDR, "Normalized Coords",   165,160,145,19, &G.sima->flag, 0, 0, 0, 0, "Display coords from 0.0 to 1.0 rather then in pixels");
1441         
1442         
1443         if (G.sima->image) {
1444                 uiDefBut(block, LABEL, B_NOP, "Image Display:",         10,140,140,19, 0, 0, 0, 0, 0, "");
1445                 uiBlockBeginAlign(block);
1446                 uiDefButF(block, NUM, B_REDR, "AspX:", 10,120,140,19, &G.sima->image->aspx, 0.1, 5000.0, 100, 0, "X Display Aspect for this image, does not affect renderingm 0 disables.");
1447                 uiDefButF(block, NUM, B_REDR, "AspY:", 10,100,140,19, &G.sima->image->aspy, 0.1, 5000.0, 100, 0, "X Display Aspect for this image, does not affect rendering 0 disables.");
1448                 uiBlockEndAlign(block);
1449         }
1450         
1451         
1452         if (EM_texFaceCheck()) {
1453                 uiDefBut(block, LABEL, B_NOP, "Draw Type:",             10, 80,120,19, 0, 0, 0, 0, 0, "");
1454                 uiBlockBeginAlign(block);
1455                 uiDefButC(block,  ROW, B_REDR, "Outline",               10,60,58,19, &G.sima->dt_uv, 0.0, SI_UVDT_OUTLINE, 0, 0, "Outline Wire UV drawtype");
1456                 uiDefButC(block,  ROW, B_REDR, "Dash",                  68, 60,58,19, &G.sima->dt_uv, 0.0, SI_UVDT_DASH, 0, 0, "Dashed Wire UV drawtype");
1457                 uiDefButC(block,  ROW, B_REDR, "Black",                 126, 60,58,19, &G.sima->dt_uv, 0.0, SI_UVDT_BLACK, 0, 0, "Black Wire UV drawtype");
1458                 uiDefButC(block,  ROW, B_REDR, "White",                 184,60,58,19, &G.sima->dt_uv, 0.0, SI_UVDT_WHITE, 0, 0, "White Wire UV drawtype");
1459                 
1460                 uiBlockEndAlign(block);
1461                 uiDefButBitI(block, TOG, SI_SMOOTH_UV, B_REDR, "Smooth",        250,60,60,19,  &G.sima->flag, 0, 0, 0, 0, "Display smooth lines in the UV view");
1462                 
1463                 
1464                 uiDefButBitI(block, TOG, G_DRAWFACES, B_REDR, "Faces",          10,30,60,19,  &G.f, 0, 0, 0, 0, "Displays all faces as shades in the 3d view and UV editor");
1465                 uiDefButBitI(block, TOG, G_DRAWEDGES, B_REDR, "Edges", 70, 30,60,19, &G.f, 0, 0, 0, 0, "Displays selected edges using hilights and UV editor");
1466                 
1467                 uiDefButBitI(block, TOG, SI_DRAWSHADOW, B_REDR, "Final Shadow", 130, 30,110,19, &G.sima->flag, 0, 0, 0, 0, "Draw the final result from the objects modifiers");
1468                 
1469                 uiDefButBitI(block, TOG, SI_DRAW_STRETCH, B_REDR, "UV Stretch", 10,0,100,19,  &G.sima->flag, 0, 0, 0, 0, "Difference between UV's and the 3D coords (blue for low distortion, red is high)");
1470                 if (G.sima->flag & SI_DRAW_STRETCH) {
1471                         uiBlockBeginAlign(block);
1472                         uiDefButC(block,  ROW, B_REDR, "Area",                  120,0,60,19, &G.sima->dt_uvstretch, 0.0, SI_UVDT_STRETCH_AREA, 0, 0, "Area distortion between UV's and 3D coords");
1473                         uiDefButC(block,  ROW, B_REDR, "Angle",         180,0,60,19, &G.sima->dt_uvstretch, 0.0, SI_UVDT_STRETCH_ANGLE, 0, 0, "Angle distortion between UV's and 3D coords");
1474                         uiBlockEndAlign(block);
1475                 }
1476                 
1477         }
1478         image_editcursor_buts(block);
1479 }
1480
1481 static void image_panel_paint(short cntrl)      // IMAGE_HANDLER_PAINT
1482 {
1483         /* B_SIMABRUSHCHANGE only redraws and eats the mouse messages  */
1484         /* so that LEFTMOUSE does not 'punch' through the floating panel */
1485         /* B_SIMANOTHING */
1486         ToolSettings *settings= G.scene->toolsettings;
1487         Brush *brush= settings->imapaint.brush;
1488         uiBlock *block;
1489         ID *id;
1490         int yco, xco, butw;
1491         
1492         if ((G.sima->image && (G.sima->flag & SI_DRAWTOOL))==0) {
1493                 return;
1494         }
1495         
1496         block= uiNewBlock(&curarea->uiblocks, "image_panel_paint", UI_EMBOSS, UI_HELV, curarea->win);
1497         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1498         uiSetPanelHandler(IMAGE_HANDLER_PAINT);  // for close and esc
1499         if(uiNewPanel(curarea, block, "Image Paint", "Image", 10, 230, 318, 204)==0)
1500                 return;
1501
1502         yco= 160;
1503
1504         uiBlockBeginAlign(block);
1505         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Draw",                0  ,yco,80,19, &settings->imapaint.tool, 7.0, PAINT_TOOL_DRAW, 0, 0, "Draw brush");
1506         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Soften",              80 ,yco,80,19, &settings->imapaint.tool, 7.0, PAINT_TOOL_SOFTEN, 0, 0, "Soften brush");
1507         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Smear",               160,yco,80,19, &settings->imapaint.tool, 7.0, PAINT_TOOL_SMEAR, 0, 0, "Smear brush");   
1508         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");     
1509         uiBlockEndAlign(block);
1510         yco -= 30;
1511
1512         uiBlockSetCol(block, TH_BUT_SETTING2);
1513         id= (ID*)settings->imapaint.brush;
1514         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);
1515         uiBlockSetCol(block, TH_AUTO);
1516
1517         if(brush && !brush->id.lib) {
1518                 butw= 320-(xco+10);
1519
1520                 uiDefButS(block, MENU, B_SIMANOTHING, "Mix %x0|Add %x1|Subtract %x2|Multiply %x3|Lighten %x4|Darken %x5|Erase Alpha %x6|Add Alpha %x7", xco+10,yco,butw,19, &brush->blend, 0, 0, 0, 0, "Blending method for applying brushes");
1521
1522                 uiDefButBitS(block, TOG|BIT, BRUSH_TORUS, B_SIMABRUSHCHANGE, "Wrap",    xco+10,yco-25,butw,19, &brush->flag, 0, 0, 0, 0, "Enables torus wrapping");
1523
1524                 uiBlockBeginAlign(block);
1525                 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)");
1526                 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");
1527                 uiBlockEndAlign(block);
1528
1529                 yco -= 25;
1530
1531                 uiBlockBeginAlign(block);
1532                 uiDefButF(block, COL, B_VPCOLSLI, "",                                   0,yco,200,19, brush->rgb, 0, 0, 0, 0, "");
1533                 uiDefButF(block, NUMSLI, B_SIMANOTHING, "Opacity ",             0,yco-20,180,19, &brush->alpha, 0.0, 1.0, 0, 0, "The amount of pressure on the brush");
1534                 uiDefButBitS(block, TOG|BIT, BRUSH_ALPHA_PRESSURE, B_SIMANOTHING, "P",  180,yco-20,20,19, &brush->flag, 0, 0, 0, 0, "Enables pressure sensitivity for tablets");
1535                 uiDefButI(block, NUMSLI, B_SIMANOTHING, "Size ",                0,yco-40,180,19, &brush->size, 1, 200, 0, 0, "The size of the brush");
1536                 uiDefButBitS(block, TOG|BIT, BRUSH_SIZE_PRESSURE, B_SIMANOTHING, "P",   180,yco-40,20,19, &brush->flag, 0, 0, 0, 0, "Enables pressure sensitivity for tablets");
1537                 uiDefButF(block, NUMSLI, B_SIMANOTHING, "Falloff ",             0,yco-60,180,19, &brush->innerradius, 0.0, 1.0, 0, 0, "The fall off radius of the brush");
1538                 uiDefButBitS(block, TOG|BIT, BRUSH_RAD_PRESSURE, B_SIMANOTHING, "P",    180,yco-60,20,19, &brush->flag, 0, 0, 0, 0, "Enables pressure sensitivity for tablets");
1539                 uiDefButF(block, NUMSLI, B_SIMANOTHING, "Spacing ",0,yco-80,180,19, &brush->spacing, 1.0, 100.0, 0, 0, "Repeating paint on %% of brush diameter");
1540                 uiDefButBitS(block, TOG|BIT, BRUSH_SPACING_PRESSURE, B_SIMANOTHING, "P",        180,yco-80,20,19, &brush->flag, 0, 0, 0, 0, "Enables pressure sensitivity for tablets");
1541                 uiBlockEndAlign(block);
1542
1543                 yco -= 110;
1544
1545                 if(settings->imapaint.tool == PAINT_TOOL_CLONE) {
1546                         id= (ID*)brush->clone.image;
1547                         uiBlockSetCol(block, TH_BUT_SETTING2);
1548                         xco= std_libbuttons(block, 0, yco, 0, NULL, B_SIMACLONEBROWSE, ID_IM, 0, id, 0, &G.sima->menunr, 0, 0, B_SIMACLONEDELETE, 0, 0);
1549                         uiBlockSetCol(block, TH_AUTO);
1550                         if(id) {
1551                                 butw= 320-(xco+5);
1552                                 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");
1553                         }
1554                 }
1555                 else {
1556                         MTex *mtex= brush->mtex[brush->texact];
1557
1558                         uiBlockSetCol(block, TH_BUT_SETTING2);
1559                         id= (mtex)? (ID*)mtex->tex: NULL;
1560                         xco= std_libbuttons(block, 0, yco, 0, NULL, B_SIMABTEXBROWSE, ID_TE, 0, id, NULL, &(G.sima->menunr), 0, 0, B_SIMABTEXDELETE, 0, 0);
1561                         /*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");*/
1562                         uiBlockSetCol(block, TH_AUTO);
1563                 }
1564         }
1565
1566 #if 0
1567                 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");
1568                 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");
1569 #endif
1570 }
1571
1572 static void image_panel_curves_reset(void *cumap_v, void *ibuf_v)
1573 {
1574         CurveMapping *cumap = cumap_v;
1575         int a;
1576         
1577         for(a=0; a<CM_TOT; a++)
1578                 curvemap_reset(cumap->cm+a, &cumap->clipr);
1579         
1580         cumap->black[0]=cumap->black[1]=cumap->black[2]= 0.0f;
1581         cumap->white[0]=cumap->white[1]=cumap->white[2]= 1.0f;
1582         curvemapping_set_black_white(cumap, NULL, NULL);
1583         
1584         curvemapping_changed(cumap, 0);
1585         curvemapping_do_ibuf(cumap, ibuf_v);
1586         
1587         allqueue(REDRAWIMAGE, 0);
1588 }
1589
1590
1591 static void image_panel_curves(short cntrl)     // IMAGE_HANDLER_CURVES
1592 {
1593         ImBuf *ibuf;
1594         uiBlock *block;
1595         uiBut *bt;
1596         
1597         /* and we check for spare */
1598         ibuf= imagewindow_get_ibuf(G.sima);
1599         
1600         block= uiNewBlock(&curarea->uiblocks, "image_panel_curves", UI_EMBOSS, UI_HELV, curarea->win);
1601         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1602         uiSetPanelHandler(IMAGE_HANDLER_CURVES);  // for close and esc
1603         if(uiNewPanel(curarea, block, "Curves", "Image", 10, 450, 318, 204)==0)
1604                 return;
1605         
1606         if (ibuf) {
1607                 rctf rect;
1608                 
1609                 if(G.sima->cumap==NULL)
1610                         G.sima->cumap= curvemapping_add(4, 0.0f, 0.0f, 1.0f, 1.0f);
1611                 
1612                 rect.xmin= 110; rect.xmax= 310;
1613                 rect.ymin= 10; rect.ymax= 200;
1614                 curvemap_buttons(block, G.sima->cumap, 'c', B_SIMACURVES, B_REDR, &rect);
1615                 
1616                 bt=uiDefBut(block, BUT, B_SIMARANGE, "Reset",   10, 160, 90, 19, NULL, 0.0f, 0.0f, 0, 0, "Reset Black/White point and curves");
1617                 uiButSetFunc(bt, image_panel_curves_reset, G.sima->cumap, ibuf);
1618                 
1619                 uiBlockBeginAlign(block);
1620                 uiDefButF(block, NUM, B_SIMARANGE, "Min R:",    10, 120, 90, 19, G.sima->cumap->black, -1000.0f, 1000.0f, 10, 2, "Black level");
1621                 uiDefButF(block, NUM, B_SIMARANGE, "Min G:",    10, 100, 90, 19, G.sima->cumap->black+1, -1000.0f, 1000.0f, 10, 2, "Black level");
1622                 uiDefButF(block, NUM, B_SIMARANGE, "Min B:",    10, 80, 90, 19, G.sima->cumap->black+2, -1000.0f, 1000.0f, 10, 2, "Black level");
1623                 
1624                 uiBlockBeginAlign(block);
1625                 uiDefButF(block, NUM, B_SIMARANGE, "Max R:",    10, 50, 90, 19, G.sima->cumap->white, -1000.0f, 1000.0f, 10, 2, "White level");
1626                 uiDefButF(block, NUM, B_SIMARANGE, "Max G:",    10, 30, 90, 19, G.sima->cumap->white+1, -1000.0f, 1000.0f, 10, 2, "White level");
1627                 uiDefButF(block, NUM, B_SIMARANGE, "Max B:",    10, 10, 90, 19, G.sima->cumap->white+2, -1000.0f, 1000.0f, 10, 2, "White level");
1628                 
1629         }
1630 }
1631
1632 /* are there curves? curves visible? and curves do something? */
1633 static int image_curves_active(ScrArea *sa)
1634 {
1635         SpaceImage *sima= sa->spacedata.first;
1636
1637         if(sima->cumap) {
1638                 if(curvemapping_RGBA_does_something(sima->cumap)) {
1639                         short a;
1640                         for(a=0; a<SPACE_MAXHANDLER; a+=2) {
1641                                 if(sima->blockhandler[a] == IMAGE_HANDLER_CURVES)
1642                                         return 1;
1643                         }
1644                 }
1645         }
1646         return 0;
1647 }
1648
1649 /* 0: disable preview 
1650    otherwise refresh preview
1651 */
1652 void image_preview_event(int event)
1653 {
1654         int exec= 0;
1655         
1656
1657         if(event==0) {
1658                 G.scene->r.scemode &= ~R_COMP_CROP;
1659                 exec= 1;
1660         }
1661         else {
1662                 if(image_preview_active(curarea, NULL, NULL)) {
1663                         G.scene->r.scemode |= R_COMP_CROP;
1664                         exec= 1;
1665                 }
1666                 else
1667                         G.scene->r.scemode &= ~R_COMP_CROP;
1668         }
1669         
1670         if(exec && G.scene->nodetree) {
1671                 /* should work when no node editor in screen..., so we execute right away */
1672                 
1673                 ntreeCompositTagGenerators(G.scene->nodetree);
1674
1675                 G.afbreek= 0;
1676                 G.scene->nodetree->timecursor= set_timecursor;
1677                 G.scene->nodetree->test_break= blender_test_break;
1678                 
1679                 BIF_store_spare();
1680                 
1681                 ntreeCompositExecTree(G.scene->nodetree, &G.scene->r, 1);       /* 1 is do_previews */
1682                 
1683                 G.scene->nodetree->timecursor= NULL;
1684                 G.scene->nodetree->test_break= NULL;
1685                 
1686                 scrarea_do_windraw(curarea);
1687                 waitcursor(0);
1688                 
1689                 allqueue(REDRAWNODE, 1);
1690         }       
1691 }
1692
1693
1694 /* nothing drawn here, we use it to store values */
1695 static void preview_cb(struct ScrArea *sa, struct uiBlock *block)
1696 {
1697         rctf dispf;
1698         rcti *disprect= &G.scene->r.disprect;
1699         int winx= (G.scene->r.size*G.scene->r.xsch)/100;
1700         int winy= (G.scene->r.size*G.scene->r.ysch)/100;
1701         short mval[2];
1702         
1703         if(G.scene->r.mode & R_BORDER) {
1704                 winx*= (G.scene->r.border.xmax - G.scene->r.border.xmin);
1705                 winy*= (G.scene->r.border.ymax - G.scene->r.border.ymin);
1706         }
1707         
1708         /* while dragging we need to update the rects, otherwise it doesn't end with correct one */
1709
1710         BLI_init_rctf(&dispf, 15.0f, (block->maxx - block->minx)-15.0f, 15.0f, (block->maxy - block->miny)-15.0f);
1711         ui_graphics_to_window_rct(sa->win, &dispf, disprect);
1712         
1713         /* correction for gla draw */
1714         BLI_translate_rcti(disprect, -curarea->winrct.xmin, -curarea->winrct.ymin);
1715         
1716         calc_image_view(G.sima, 'p');
1717 //      printf("winrct %d %d %d %d\n", disprect->xmin, disprect->ymin,disprect->xmax, disprect->ymax);
1718         /* map to image space coordinates */
1719         mval[0]= disprect->xmin; mval[1]= disprect->ymin;
1720         areamouseco_to_ipoco(G.v2d, mval, &dispf.xmin, &dispf.ymin);
1721         mval[0]= disprect->xmax; mval[1]= disprect->ymax;
1722         areamouseco_to_ipoco(G.v2d, mval, &dispf.xmax, &dispf.ymax);
1723         
1724         /* map to render coordinates */
1725         disprect->xmin= dispf.xmin;
1726         disprect->xmax= dispf.xmax;
1727         disprect->ymin= dispf.ymin;
1728         disprect->ymax= dispf.ymax;
1729         
1730         CLAMP(disprect->xmin, 0, winx);
1731         CLAMP(disprect->xmax, 0, winx);
1732         CLAMP(disprect->ymin, 0, winy);
1733         CLAMP(disprect->ymax, 0, winy);
1734 //      printf("drawrct %d %d %d %d\n", disprect->xmin, disprect->ymin,disprect->xmax, disprect->ymax);
1735
1736 }
1737
1738 static int is_preview_allowed(ScrArea *cur)
1739 {
1740         SpaceImage *sima= cur->spacedata.first;
1741         ScrArea *sa;
1742
1743         /* check if another areawindow has preview set */
1744         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
1745                 if(sa!=cur && sa->spacetype==SPACE_IMAGE) {
1746                         if(image_preview_active(sa, NULL, NULL))
1747                            return 0;
1748                 }
1749         }
1750         /* check image type */
1751         if(sima->image==NULL || sima->image->type!=IMA_TYPE_COMPOSITE)
1752                 return 0;
1753         
1754         return 1;
1755 }
1756
1757 static void image_panel_preview(ScrArea *sa, short cntrl)       // IMAGE_HANDLER_PREVIEW
1758 {
1759         uiBlock *block;
1760         SpaceImage *sima= sa->spacedata.first;
1761         int ofsx, ofsy;
1762         
1763         if(is_preview_allowed(sa)==0) {
1764                 rem_blockhandler(sa, IMAGE_HANDLER_PREVIEW);
1765                 G.scene->r.scemode &= ~R_COMP_CROP;     /* quite weak */
1766                 return;
1767         }
1768         
1769         block= uiNewBlock(&sa->uiblocks, "image_panel_preview", UI_EMBOSS, UI_HELV, sa->win);
1770         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | UI_PNL_SCALE | cntrl);
1771         uiSetPanelHandler(IMAGE_HANDLER_PREVIEW);  // for close and esc
1772         
1773         ofsx= -150+(sa->winx/2)/sima->blockscale;
1774         ofsy= -100+(sa->winy/2)/sima->blockscale;
1775         if(uiNewPanel(sa, block, "Preview", "Image", ofsx, ofsy, 300, 200)==0) return;
1776         
1777         uiBlockSetDrawExtraFunc(block, preview_cb);
1778         
1779 }
1780
1781 static void image_blockhandlers(ScrArea *sa)
1782 {
1783         SpaceImage *sima= sa->spacedata.first;
1784         short a;
1785
1786         /* warning; blocks need to be freed each time, handlers dont remove  */
1787         uiFreeBlocksWin(&sa->uiblocks, sa->win);
1788         
1789         for(a=0; a<SPACE_MAXHANDLER; a+=2) {
1790                 switch(sima->blockhandler[a]) {
1791
1792                 case IMAGE_HANDLER_PROPERTIES:
1793                         image_panel_properties(sima->blockhandler[a+1]);
1794                         break;
1795                 case IMAGE_HANDLER_GAME_PROPERTIES:
1796                         image_panel_game_properties(sima->blockhandler[a+1]);
1797                         break;
1798                 case IMAGE_HANDLER_VIEW_PROPERTIES:
1799                         image_panel_view_properties(sima->blockhandler[a+1]);
1800                         break;
1801                 case IMAGE_HANDLER_PAINT:
1802                         image_panel_paint(sima->blockhandler[a+1]);
1803                         break;          
1804                 case IMAGE_HANDLER_CURVES:
1805                         image_panel_curves(sima->blockhandler[a+1]);
1806                         break;          
1807                 case IMAGE_HANDLER_PREVIEW:
1808                         image_panel_preview(sa, sima->blockhandler[a+1]);
1809                         break;          
1810                 }
1811                 /* clear action value for event */
1812                 sima->blockhandler[a+1]= 0;
1813         }
1814         uiDrawBlocksPanels(sa, 0);
1815 }
1816
1817 void imagespace_composite_flipbook(ScrArea *sa)
1818 {
1819         SpaceImage *sima= sa->spacedata.first;
1820         ImBuf *ibuf;
1821         int cfrao= G.scene->r.cfra;
1822         int sfra, efra;
1823         
1824         if(sa->spacetype!=SPACE_IMAGE)
1825                 return;
1826         if(sima->iuser.frames<2)
1827                 return;
1828         if(G.scene->nodetree==NULL)
1829                 return;
1830         
1831         sfra= sima->iuser.sfra;
1832         efra= sima->iuser.sfra + sima->iuser.frames-1;
1833         G.scene->nodetree->test_break= blender_test_break;
1834         
1835         for(G.scene->r.cfra=sfra; G.scene->r.cfra<=efra; G.scene->r.cfra++) {
1836                 
1837                 set_timecursor(CFRA);
1838                 
1839                 BKE_image_all_free_anim_ibufs(CFRA);
1840                 ntreeCompositTagAnimated(G.scene->nodetree);
1841                 ntreeCompositExecTree(G.scene->nodetree, &G.scene->r, G.scene->r.cfra!=cfrao);  /* 1 is no previews */
1842                 
1843                 force_draw(0);
1844                 
1845                 ibuf= BKE_image_get_ibuf(sima->image, &sima->iuser);
1846                 /* save memory in flipbooks */
1847                 if(ibuf)
1848                         imb_freerectfloatImBuf(ibuf);
1849                 
1850                 if(blender_test_break())
1851                         break;
1852         }
1853         G.scene->nodetree->test_break= NULL;
1854         waitcursor(0);
1855         
1856         play_anim(0);
1857         
1858         allqueue(REDRAWNODE, 1);
1859         allqueue(REDRAWIMAGE, 1);
1860         
1861         G.scene->r.cfra= cfrao;
1862 }
1863
1864 static void imagespace_grid(SpaceImage *sima)
1865 {
1866         float gridsize, gridstep= 1.0f/32.0f;
1867         float fac, blendfac;
1868         
1869         gridsize= sima->zoom;
1870         
1871         calc_image_view(sima, 'f');
1872         myortho2(sima->v2d.cur.xmin, sima->v2d.cur.xmax, sima->v2d.cur.ymin, sima->v2d.cur.ymax);
1873         
1874         BIF_ThemeColorShade(TH_BACK, 20);
1875         glRectf(0.0, 0.0, 1.0, 1.0);
1876         
1877         if(gridsize<=0.0f) return;
1878         
1879         if(gridsize<1.0f) {
1880                 while(gridsize<1.0f) {
1881                         gridsize*= 4.0;
1882                         gridstep*= 4.0;
1883                 }
1884         }
1885         else {
1886                 while(gridsize>=4.0f) {
1887                         gridsize/= 4.0;
1888                         gridstep/= 4.0;
1889                 }
1890         }
1891         
1892         /* the fine resolution level */
1893         blendfac= 0.25*gridsize - floor(0.25*gridsize);
1894         CLAMP(blendfac, 0.0, 1.0);
1895         BIF_ThemeColorShade(TH_BACK, (int)(20.0*(1.0-blendfac)));
1896         
1897         fac= 0.0f;
1898         glBegin(GL_LINES);
1899         while(fac<1.0) {
1900                 glVertex2f(0.0f, fac);
1901                 glVertex2f(1.0f, fac);
1902                 glVertex2f(fac, 0.0f);
1903                 glVertex2f(fac, 1.0f);
1904                 fac+= gridstep;
1905         }
1906         
1907         /* the large resolution level */
1908         BIF_ThemeColor(TH_BACK);
1909         
1910         fac= 0.0f;
1911         while(fac<1.0) {
1912                 glVertex2f(0.0f, fac);
1913                 glVertex2f(1.0f, fac);
1914                 glVertex2f(fac, 0.0f);
1915                 glVertex2f(fac, 1.0f);
1916                 fac+= 4.0*gridstep;
1917         }
1918         glEnd();
1919         
1920 }
1921
1922 static void sima_draw_alpha_backdrop(SpaceImage *sima, float x1, float y1, float xsize, float ysize)
1923 {
1924         GLubyte checker_stipple[32*32/8] =
1925         {
1926                 255,255,0,0,255,255,0,0,255,255,0,0,255,255,0,0, \
1927                 255,255,0,0,255,255,0,0,255,255,0,0,255,255,0,0, \
1928                 255,255,0,0,255,255,0,0,255,255,0,0,255,255,0,0, \
1929                 255,255,0,0,255,255,0,0,255,255,0,0,255,255,0,0, \
1930                 0,0,255,255,0,0,255,255,0,0,255,255,0,0,255,255, \
1931                 0,0,255,255,0,0,255,255,0,0,255,255,0,0,255,255, \
1932                 0,0,255,255,0,0,255,255,0,0,255,255,0,0,255,255, \
1933                 0,0,255,255,0,0,255,255,0,0,255,255,0,0,255,255, \
1934         };
1935         
1936         glColor3ub(100, 100, 100);
1937         glRectf(x1, y1, x1 + sima->zoom*xsize, y1 + sima->zoom*ysize);
1938         glColor3ub(160, 160, 160);
1939
1940         glEnable(GL_POLYGON_STIPPLE);
1941         glPolygonStipple(checker_stipple);
1942         glRectf(x1, y1, x1 + sima->zoom*xsize, y1 + sima->zoom*ysize);
1943         glDisable(GL_POLYGON_STIPPLE);
1944 }
1945
1946 static void sima_draw_alpha_pixels(float x1, float y1, int rectx, int recty, unsigned int *recti)
1947 {
1948         
1949         /* swap bytes, so alpha is most significant one, then just draw it as luminance int */
1950         if(G.order==B_ENDIAN)
1951                 glPixelStorei(GL_UNPACK_SWAP_BYTES, 1);
1952         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_UNSIGNED_INT, recti);
1953         glPixelStorei(GL_UNPACK_SWAP_BYTES, 0);
1954 }
1955
1956 static void sima_draw_alpha_pixelsf(float x1, float y1, int rectx, int recty, float *rectf)
1957 {
1958         float *trectf= MEM_mallocN(rectx*recty*4, "temp");
1959         int a, b;
1960         
1961         for(a= rectx*recty -1, b= 4*a+3; a>=0; a--, b-=4)
1962                 trectf[a]= rectf[b];
1963         
1964         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_FLOAT, trectf);
1965         MEM_freeN(trectf);
1966         /* ogl trick below is slower... (on ATI 9600) */
1967 //      glColorMask(1, 0, 0, 0);
1968 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+3);
1969 //      glColorMask(0, 1, 0, 0);
1970 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+2);
1971 //      glColorMask(0, 0, 1, 0);
1972 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+1);
1973 //      glColorMask(1, 1, 1, 1);
1974 }
1975
1976 static void sima_draw_zbuf_pixels(float x1, float y1, int rectx, int recty, int *recti)
1977 {
1978         if(recti==NULL)
1979                 return;
1980         
1981         /* zbuffer values are signed, so we need to shift color range */
1982         glPixelTransferf(GL_RED_SCALE, 0.5f);
1983         glPixelTransferf(GL_GREEN_SCALE, 0.5f);
1984         glPixelTransferf(GL_BLUE_SCALE, 0.5f);
1985         glPixelTransferf(GL_RED_BIAS, 0.5f);
1986         glPixelTransferf(GL_GREEN_BIAS, 0.5f);
1987         glPixelTransferf(GL_BLUE_BIAS, 0.5f);
1988         
1989         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_INT, recti);
1990         
1991         glPixelTransferf(GL_RED_SCALE, 1.0f);
1992         glPixelTransferf(GL_GREEN_SCALE, 1.0f);
1993         glPixelTransferf(GL_BLUE_SCALE, 1.0f);
1994         glPixelTransferf(GL_RED_BIAS, 0.0f);
1995         glPixelTransferf(GL_GREEN_BIAS, 0.0f);
1996         glPixelTransferf(GL_BLUE_BIAS, 0.0f);
1997 }
1998
1999 static void sima_draw_zbuffloat_pixels(float x1, float y1, int rectx, int recty, float *rect_float)
2000 {
2001         float bias, scale, *rectf, clipend;
2002         int a;
2003         
2004         if(rect_float==NULL)
2005                 return;
2006         
2007         if(G.scene->camera && G.scene->camera->type==OB_CAMERA) {
2008                 bias= ((Camera *)G.scene->camera->data)->clipsta;
2009                 clipend= ((Camera *)G.scene->camera->data)->clipend;
2010                 scale= 1.0f/(clipend-bias);
2011         }
2012         else {
2013                 bias= 0.1f;
2014                 scale= 0.01f;
2015                 clipend= 100.0f;
2016         }
2017         
2018         rectf= MEM_mallocN(rectx*recty*4, "temp");
2019         for(a= rectx*recty -1; a>=0; a--) {
2020                 if(rect_float[a]>clipend)
2021                         rectf[a]= 0.0f;
2022                 else if(rect_float[a]<bias)
2023                         rectf[a]= 1.0f;
2024                 else {
2025                         rectf[a]= 1.0f - (rect_float[a]-bias)*scale;
2026                         rectf[a]*= rectf[a];
2027                 }
2028         }
2029         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_FLOAT, rectf);
2030         
2031         MEM_freeN(rectf);
2032 }
2033
2034 static void imagewindow_draw_renderinfo(ScrArea *sa)
2035 {
2036         rcti rect;
2037         float colf[3];
2038         int showspare= BIF_show_render_spare();
2039         char *str= BIF_render_text();
2040         
2041         if(str==NULL)
2042                 return;
2043         
2044         rect= sa->winrct;
2045         rect.ymin= rect.ymax-RW_HEADERY;
2046         
2047         glaDefine2DArea(&rect);
2048         
2049         /* clear header rect */
2050         BIF_GetThemeColor3fv(TH_BACK, colf);
2051         glClearColor(colf[0]+0.1f, colf[1]+0.1f, colf[2]+0.1f, 1.0); 
2052         glClear(GL_COLOR_BUFFER_BIT);
2053         
2054         BIF_ThemeColor(TH_TEXT_HI);
2055         glRasterPos2i(12, 5);
2056         if(showspare) {
2057                 BMF_DrawString(G.fonts, "(Previous)");
2058                 glRasterPos2i(72, 5);
2059         }               
2060         BMF_DrawString(G.fonts, str);
2061 }
2062
2063 void drawimagespace(ScrArea *sa, void *spacedata)
2064 {
2065         SpaceImage *sima= spacedata;
2066         ImBuf *ibuf= NULL;
2067         Brush *brush;
2068         float col[3];
2069         unsigned int *rect;
2070         float x1, y1;
2071         short sx, sy, dx, dy, show_render= 0, show_viewer= 0;
2072         float xuser_asp=1, yuser_asp=1;
2073                 /* If derived data is used then make sure that object
2074                  * is up-to-date... might not be the case because updates
2075                  * are normally done in drawview and could get here before
2076                  * drawing a View3D.
2077                  */
2078         if (G.obedit && OBACT && (sima->flag & SI_DRAWSHADOW)) {
2079                 object_handle_update(OBACT);
2080         }
2081         
2082         BIF_GetThemeColor3fv(TH_BACK, col);
2083         glClearColor(col[0], col[1], col[2], 0.0);
2084         glClear(GL_COLOR_BUFFER_BIT);
2085
2086         bwin_clear_viewmat(sa->win);    /* clear buttons view */
2087         glLoadIdentity();
2088         
2089         if(sima->image && sima->image->source==IMA_SRC_VIEWER) {
2090                 show_viewer= 1;
2091                 if(sima->image->type==IMA_TYPE_R_RESULT)
2092                         show_render= 1;
2093         }
2094         
2095         what_image(sima);
2096         
2097         if(sima->image) {
2098                 image_pixel_aspect(sima->image, &xuser_asp, &yuser_asp);
2099                 
2100                 /* UGLY hack? until now iusers worked fine... but for flipbook viewer we need this */
2101                 if(sima->image->type==IMA_TYPE_COMPOSITE) {
2102                         ImageUser *iuser= ntree_get_active_iuser(G.scene->nodetree);
2103                         if(iuser) {
2104                                 BKE_image_user_calc_imanr(iuser, G.scene->r.cfra, 0);
2105                                 G.sima->iuser= *iuser;
2106                         }
2107                 }
2108                 /* and we check for spare */
2109                 ibuf= imagewindow_get_ibuf(sima);
2110         }
2111         
2112         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL)) {
2113                 imagespace_grid(sima);
2114                 if(show_viewer==0) {
2115                         draw_uvs_sima();
2116                         drawcursor_sima(xuser_asp, yuser_asp);
2117                 }
2118         }
2119         else {
2120                 float xim, yim, xoffs=0.0f, yoffs= 0.0f;
2121                 
2122                 if(image_preview_active(sa, &xim, &yim)) {
2123                         xoffs= G.scene->r.disprect.xmin;
2124                         yoffs= G.scene->r.disprect.ymin;
2125                         glColor3ub(0,0,0);
2126                         calc_image_view(sima, 'f');     
2127                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
2128                         glRectf(0.0f, 0.0f, 1.0f, 1.0f);
2129                         glLoadIdentity();
2130                 }
2131                 else {
2132                         xim= ibuf->x * xuser_asp; yim= ibuf->y * yuser_asp;
2133                 }
2134                 
2135                 /* calc location */
2136                 x1= sima->zoom*xoffs + ((float)sa->winx - sima->zoom*(float)xim)/2.0f;
2137                 y1= sima->zoom*yoffs + ((float)sa->winy - sima->zoom*(float)yim)/2.0f;
2138         
2139                 x1-= sima->zoom*sima->xof;
2140                 y1-= sima->zoom*sima->yof;
2141                 
2142                 /* needed for gla draw */
2143                 if(show_render) { 
2144                         rcti rct= sa->winrct; 
2145                         
2146                         imagewindow_draw_renderinfo(sa);        /* calls glaDefine2DArea too */
2147                         
2148                         rct.ymax-=RW_HEADERY; 
2149                         glaDefine2DArea(&rct);
2150                 }
2151                 else glaDefine2DArea(&sa->winrct);
2152                 
2153                 glPixelZoom(sima->zoom * xuser_asp, sima->zoom * yuser_asp);
2154                                 
2155                 if(sima->flag & SI_EDITTILE) {
2156                         /* create char buffer from float if needed */
2157                         if(ibuf->rect_float && ibuf->rect==NULL)
2158                                 IMB_rect_from_float(ibuf);
2159
2160                         glaDrawPixelsSafe(x1, y1, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
2161                         
2162                         glPixelZoom(1.0, 1.0);
2163                         
2164                         dx= ibuf->x/sima->image->xrep;
2165                         dy= ibuf->y/sima->image->yrep;
2166                         sy= (sima->curtile / sima->image->xrep);
2167                         sx= sima->curtile - sy*sima->image->xrep;
2168         
2169                         sx*= dx;
2170                         sy*= dy;
2171                         
2172                         calc_image_view(sima, 'p');     /* pixel */
2173                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
2174                         
2175                         cpack(0x0);
2176                         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRects(sx,  sy,  sx+dx-1,  sy+dy-1); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
2177                         cpack(0xFFFFFF);
2178                         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRects(sx+1,  sy+1,  sx+dx,  sy+dy); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
2179                 }
2180                 else if(sima->mode==SI_TEXTURE) {
2181                         
2182                         if(sima->image->tpageflag & IMA_TILES) {
2183                                 
2184                                 /* just leave this a while */
2185                                 if(sima->image->xrep<1) return;
2186                                 if(sima->image->yrep<1) return;
2187                                 
2188                                 if(sima->curtile >= sima->image->xrep*sima->image->yrep) 
2189                                         sima->curtile = sima->image->xrep*sima->image->yrep - 1; 
2190                                 
2191                                 dx= ibuf->x/sima->image->xrep;
2192                                 dy= ibuf->y/sima->image->yrep;
2193                                 
2194                                 sy= (sima->curtile / sima->image->xrep);
2195                                 sx= sima->curtile - sy*sima->image->xrep;
2196                 
2197                                 sx*= dx;
2198                                 sy*= dy;
2199                                 
2200                                 /* create char buffer from float if needed */
2201                                 if(ibuf->rect_float && ibuf->rect==NULL)
2202                                         IMB_rect_from_float(ibuf);
2203
2204                                 rect= get_part_from_ibuf(ibuf, sx, sy, sx+dx, sy+dy);
2205                                 
2206                                 /* rect= ibuf->rect; */
2207                                 for(sy= 0; sy+dy<=ibuf->y; sy+= dy) {
2208                                         for(sx= 0; sx+dx<=ibuf->x; sx+= dx) {
2209                                                 glaDrawPixelsSafe(x1+sx*sima->zoom, y1+sy*sima->zoom, dx, dy, dx, GL_RGBA, GL_UNSIGNED_BYTE, rect);
2210                                         }
2211                                 }
2212                                 
2213                                 MEM_freeN(rect);
2214                         }
2215                         else {
2216                                 float x1_rep, y1_rep;
2217                                 int x_rep, y_rep;
2218                                 double time_current;
2219                                 short loop_draw_ok = 0;
2220                                 
2221                                 if (sima->flag & SI_DRAW_TILE) {
2222                                         loop_draw_ok= 1;
2223                                 }
2224                                 
2225                                 time_current = PIL_check_seconds_timer();
2226                                 
2227                                 for (x_rep= ((int)G.v2d->cur.xmin)-1; x_rep < G.v2d->cur.xmax; x_rep++) {
2228                                         x1_rep=x1+  ((x_rep* ibuf->x * sima->zoom)  *xuser_asp);
2229                                         for (y_rep= ((int)G.v2d->cur.ymin)-1; y_rep < G.v2d->cur.ymax; y_rep++) {
2230                                                 y1_rep=y1+  ((y_rep * ibuf->y *sima->zoom)  *yuser_asp);
2231                                 
2232                                 /* end repeating image loop */
2233                                                 
2234                                                 if(!loop_draw_ok) {
2235                                                         y1_rep = y1;
2236                                                         x1_rep = x1;
2237                                                 }
2238                                                 
2239                                                 /*printf("Drawing %d %d zoom:%.6f (%.6f %.6f), (%.6f %.6f)\n", x_rep, y_rep, sima->zoom, G.v2d->cur.xmin, G.v2d->cur.ymin, G.v2d->cur.xmax, G.v2d->cur.ymax);*/
2240                                                 
2241                                                 /* this part is generic image display */
2242                                                 if(sima->flag & SI_SHOW_ALPHA) {
2243                                                         if(ibuf->rect)
2244                                                                 sima_draw_alpha_pixels(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->rect);
2245                                                         else if(ibuf->rect_float && ibuf->channels==4)
2246                                                                 sima_draw_alpha_pixelsf(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->rect_float);
2247                                                 }
2248                                                 else if(sima->flag & SI_SHOW_ZBUF && (ibuf->zbuf || ibuf->zbuf_float || (ibuf->channels==1))) {
2249                                                         if(ibuf->zbuf)
2250                                                                 sima_draw_zbuf_pixels(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->zbuf);
2251                                                         else if(ibuf->zbuf_float)
2252                                                                 sima_draw_zbuffloat_pixels(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->zbuf_float);
2253                                                         else if(ibuf->channels==1)
2254                                                                 sima_draw_zbuffloat_pixels(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->rect_float);
2255                                                 }
2256                                                 else {
2257                                                         if(sima->flag & SI_USE_ALPHA) {
2258                                                                 sima_draw_alpha_backdrop(sima, x1_rep, y1_rep, ibuf->x*xuser_asp, ibuf->y*yuser_asp);
2259                                                                 glEnable(GL_BLEND);
2260                                                                 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
2261                                                         }
2262                                                         
2263                                                         /* detect if we need to redo the curve map. 
2264                                                            ibuf->rect is zero for compositor and render results after change 
2265                                                            convert to 32 bits always... drawing float rects isnt supported well (atis)
2266                                                         
2267                                                            NOTE: if float buffer changes, we have to manually remove the rect
2268                                                         */
2269                                                         
2270                                                         if(ibuf->rect_float) {
2271                                                                 if(ibuf->rect==NULL) {
2272                                                                         if(image_curves_active(sa))
2273                                                                                 curvemapping_do_ibuf(G.sima->cumap, ibuf);
2274                                                                         else 
2275                                                                                 IMB_rect_from_float(ibuf);
2276                                                                 }
2277                                                         }
2278                 
2279                                                         if(ibuf->rect)
2280                                                                 glaDrawPixelsSafe(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
2281                 //                                      else
2282                 //                                              glaDrawPixelsSafe(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_FLOAT, ibuf->rect_float);
2283                                                         
2284                                                         if(sima->flag & SI_USE_ALPHA)
2285                                                                 glDisable(GL_BLEND);
2286                                                 }
2287                                                 
2288                                                 /* only draw once */
2289                                                 if(!loop_draw_ok) {
2290                                                         break; /* only draw once */
2291                                                 } else if ((PIL_check_seconds_timer() - time_current) > 0.25) {
2292                                                         loop_draw_ok = 0;
2293                                                         break;
2294                                                 }
2295                                 
2296                                 /* tile draw loop */
2297                                         }
2298                                         /* only draw once */
2299                                         if(!loop_draw_ok) break;
2300                                 }
2301                                 /* tile draw loop */
2302                                 
2303                         }
2304                         
2305                         brush= G.scene->toolsettings->imapaint.brush;
2306                         if(brush && (G.scene->toolsettings->imapaint.tool == PAINT_TOOL_CLONE)) {
2307                                 int w, h;
2308                                 unsigned char *clonerect;
2309
2310                                 /* this is not very efficient, but glDrawPixels doesn't allow
2311                                    drawing with alpha */
2312                                 clonerect= alloc_alpha_clone_image(&w, &h);
2313
2314                                 if(clonerect) {
2315                                         int offx, offy;
2316                                         offx = sima->zoom*ibuf->x * + brush->clone.offset[0];
2317                                         offy = sima->zoom*ibuf->y * + brush->clone.offset[1];
2318
2319                                         glEnable(GL_BLEND);
2320                                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2321                                         glaDrawPixelsSafe(x1 + offx, y1 + offy, w, h, w, GL_RGBA, GL_UNSIGNED_BYTE, clonerect);
2322                                         glDisable(GL_BLEND);
2323
2324                                         MEM_freeN(clonerect);
2325                                 }
2326                         }
2327                         
2328                         glPixelZoom(1.0, 1.0);
2329                         
2330                         if(show_viewer==0) { 
2331                                 draw_uvs_sima();
2332                                 drawcursor_sima(xuser_asp, yuser_asp);
2333                         }
2334                 }
2335
2336                 glPixelZoom(1.0, 1.0);
2337
2338                 calc_image_view(sima, 'f');     /* float */
2339         }
2340
2341         draw_image_transform(ibuf, xuser_asp, yuser_asp);
2342
2343         mywinset(sa->win);      /* restore scissor after gla call... */
2344         myortho2(-0.375, sa->winx-0.375, -0.375, sa->winy-0.375);
2345
2346         if(G.rendering==0) {
2347                 draw_image_view_tool();
2348         }
2349         draw_area_emboss(sa);
2350
2351         /* it is important to end a view in a transform compatible with buttons */
2352         bwin_scalematrix(sa->win, sima->blockscale, sima->blockscale, sima->blockscale);
2353         if(!(G.rendering && show_render))
2354                 image_blockhandlers(sa);
2355
2356         sa->win_swap= WIN_BACK_OK;
2357 }
2358
2359 static void image_zoom_set_factor(float zoomfac)
2360 {
2361         SpaceImage *sima= curarea->spacedata.first;
2362         int width, height;
2363
2364         if (zoomfac <= 0.0f)
2365                 return;
2366
2367         sima->zoom *= zoomfac;
2368
2369         if (sima->zoom > 0.1f && sima->zoom < 4.0f)
2370                 return;
2371
2372         /* check zoom limits */
2373
2374         calc_image_view(G.sima, 'f'); /* was 'p' are there any cases where this should be 'p'?*/
2375         width= 256;
2376         height= 256;
2377         if (sima->image) {
2378                 ImBuf *ibuf= imagewindow_get_ibuf(sima);
2379
2380                 if (ibuf) {
2381                         float xim, yim;
2382                         /* I know a bit weak... but preview uses not actual image size */
2383                         if(image_preview_active(curarea, &xim, &yim)) {
2384                                 width= (int) xim;
2385                                 height= (int) yim;
2386                         }
2387                         else {
2388                                 width= ibuf->x;
2389                                 height= ibuf->y;
2390                         }
2391                 }
2392         }
2393         width *= sima->zoom;
2394         height *= sima->zoom;
2395
2396         if ((width < 4) && (height < 4))
2397                 sima->zoom /= zoomfac;
2398         else if((curarea->winrct.xmax - curarea->winrct.xmin) <= sima->zoom)
2399                 sima->zoom /= zoomfac;
2400         else if((curarea->winrct.ymax - curarea->winrct.ymin) <= sima->zoom)
2401                 sima->zoom /= zoomfac;
2402 }
2403
2404 void image_viewmove(int mode)
2405 {
2406         short mval[2], mvalo[2], zoom0;
2407         int oldcursor;
2408         Window *win;
2409         
2410         getmouseco_sc(mvalo);
2411         zoom0= G.sima->zoom;
2412         
2413         oldcursor=get_cursor();
2414         win=winlay_get_active_window();
2415         
2416         SetBlenderCursor(BC_NSEW_SCROLLCURSOR);
2417         
2418         while(get_mbut()&(L_MOUSE|M_MOUSE)) {
2419
2420                 getmouseco_sc(mval);
2421
2422                 if(mvalo[0]!=mval[0] || mvalo[1]!=mval[1]) {
2423                 
2424                         if(mode==0) {
2425                                 G.sima->xof += (mvalo[0]-mval[0])/G.sima->zoom;
2426                                 G.sima->yof += (mvalo[1]-mval[1])/G.sima->zoom;
2427                         }
2428                         else if (mode==1) {
2429                                 float factor;
2430
2431                                 factor= 1.0+(float)(mvalo[0]-mval[0]+mvalo[1]-mval[1])/300.0;
2432                                 image_zoom_set_factor(factor);
2433                         }
2434
2435                         mvalo[0]= mval[0];
2436                         mvalo[1]= mval[1];
2437                         
2438                         scrarea_do_windraw(curarea);
2439                         screen_swapbuffers();
2440                 }
2441                 else BIF_wait_for_statechange();
2442         }
2443         window_set_cursor(win, oldcursor);
2444         
2445         if(image_preview_active(curarea, NULL, NULL)) {
2446                 /* recalculates new preview rect */
2447                 scrarea_do_windraw(curarea);
2448                 image_preview_event(2);
2449         }
2450 }
2451
2452 void image_viewzoom(unsigned short event, int invert)
2453 {
2454         SpaceImage *sima= curarea->spacedata.first;
2455
2456         if(event==WHEELDOWNMOUSE || event==PADMINUS)
2457                 image_zoom_set_factor((U.uiflag & USER_WHEELZOOMDIR)? 1.25: 0.8);
2458         else if(event==WHEELUPMOUSE || event==PADPLUSKEY)
2459                 image_zoom_set_factor((U.uiflag & USER_WHEELZOOMDIR)? 0.8: 1.25);
2460         else if(event==PAD1)
2461                 sima->zoom= 1.0;
2462         else if(event==PAD2)
2463                 sima->zoom= (invert)? 2.0: 0.5;
2464         else if(event==PAD4)
2465                 sima->zoom= (invert)? 4.0: 0.25;
2466         else if(event==PAD8)
2467                 sima->zoom= (invert)? 8.0: 0.125;
2468         
2469         /* ensure pixel exact locations for draw */
2470         sima->xof= (int)sima->xof;
2471         sima->yof= (int)sima->yof;
2472         
2473         if(image_preview_active(curarea, NULL, NULL)) {
2474                 /* recalculates new preview rect */
2475                 scrarea_do_windraw(curarea);
2476                 image_preview_event(2);
2477         }
2478 }
2479
2480 /**
2481  * Updates the fields of the View2D member of the SpaceImage struct.
2482  * Default behavior is to reset the position of the image and set the zoom to 1
2483  * If the image will not fit within the window rectangle, the zoom is adjusted
2484  *
2485  * @return    void
2486  *   
2487  */
2488 void image_home(void)
2489 {
2490         ImBuf *ibuf;
2491         int width, height, imgwidth, imgheight;
2492         float zoomX, zoomY;
2493
2494         if (curarea->spacetype != SPACE_IMAGE) return;
2495         ibuf= imagewindow_get_ibuf(G.sima);
2496         
2497         if (ibuf == NULL) {
2498                 imgwidth = 256;
2499                 imgheight = 256;
2500         }
2501         else {
2502                 float xuser_asp, yuser_asp;
2503                 image_pixel_aspect(G.sima->image, &xuser_asp, &yuser_asp);
2504                 imgwidth = ibuf->x * xuser_asp;
2505                 imgheight = ibuf->y * yuser_asp;
2506         }
2507
2508         /* Check if the image will fit in the image with zoom==1 */
2509         width = curarea->winx;
2510         height = curarea->winy;
2511         if (((imgwidth >= width) || (imgheight >= height)) && 
2512                 ((width > 0) && (height > 0))) {
2513                 /* Find the zoom value that will fit the image in the image space */
2514                 zoomX = ((float)width) / ((float)imgwidth);
2515                 zoomY = ((float)height) / ((float)imgheight);
2516                 G.sima->zoom = 1.0f / power_of_2(1/ MIN2(zoomX, zoomY) );
2517         }
2518         else {
2519                 G.sima->zoom= 1.0f;
2520         }
2521
2522         G.sima->xof= G.sima->yof= 0.0f;
2523         
2524         calc_image_view(G.sima, 'f'); /* was 'p' are there any cases where this should be 'p'?*/
2525         /*calc_arearcts(curarea);*/
2526         scrarea_queue_winredraw(curarea);
2527         scrarea_queue_winredraw(curarea);
2528 }
2529
2530 void image_viewcenter(void)
2531 {
2532         ImBuf *ibuf= imagewindow_get_ibuf(G.sima);
2533         float size, min[2], max[2], d[2], xim=256.0f, yim=256.0f;
2534
2535         if( is_uv_tface_editing_allowed()==0 ) return;
2536
2537         if (!minmax_tface_uv(min, max)) return;
2538
2539         if(ibuf) {
2540                 xim= ibuf->x;
2541                 yim= ibuf->y;
2542         }
2543
2544         G.sima->xof= (int) (((min[0] + max[0])*0.5f - 0.5f)*xim);
2545         G.sima->yof= (int) (((min[1] + max[1])*0.5f - 0.5f)*yim);
2546
2547         d[0] = max[0] - min[0];
2548         d[1] = max[1] - min[1];
2549         size= 0.5*MAX2(d[0], d[1])*MAX2(xim, yim)/256.0f;
2550         
2551         if(size<=0.01) size= 0.01;
2552
2553         G.sima->zoom= 0.7/size;
2554
2555         calc_image_view(G.sima, 'f'); /* was 'p' are there any cases where 'p' is still needed? */
2556
2557         scrarea_queue_winredraw(curarea);
2558 }
2559
2560
2561 /* *********************** render callbacks ***************** */
2562
2563 /* set on initialize render, only one render output to imagewindow can exist, so the global isnt dangerous yet :) */
2564 static ScrArea *image_area= NULL;
2565
2566 /* can get as well the full picture, as the parts while rendering */
2567 static void imagewindow_progress(ScrArea *sa, RenderResult *rr, volatile rcti *renrect)
2568 {
2569         SpaceImage *sima= sa->spacedata.first;
2570         float x1, y1, *rectf= NULL;
2571         unsigned int *rect32= NULL;
2572         int ymin, ymax, xmin, xmax;
2573         
2574         /* if renrect argument, we only display scanlines */
2575         if(renrect) {
2576                 /* if ymax==recty, rendering of layer is ready, we should not draw, other things happen... */
2577                 if(rr->renlay==NULL || renrect->ymax>=rr->recty)
2578                         return;
2579                 
2580                 /* xmin here is first subrect x coord, xmax defines subrect width */
2581                 xmin = renrect->xmin;
2582                 xmax = renrect->xmax - xmin;
2583                 if (xmax<2) return;
2584                 
2585                 ymin= renrect->ymin;
2586                 ymax= renrect->ymax - ymin;
2587                 if(ymax<2)
2588                         return;
2589                 renrect->ymin= renrect->ymax;
2590         }
2591         else {
2592                 xmin = ymin = 0;
2593                 xmax = rr->rectx - 2*rr->crop;
2594                 ymax = rr->recty - 2*rr->crop;
2595         }
2596         
2597         /* image window cruft */
2598         
2599         /* find current float rect for display, first case is after composit... still weak */
2600         if(rr->rectf)
2601                 rectf= rr->rectf;
2602         else {
2603                 if(rr->rect32)
2604                         rect32= (unsigned int *)rr->rect32;
2605                 else {
2606                         if(rr->renlay==NULL || rr->renlay->rectf==NULL) return;
2607                         rectf= rr->renlay->rectf;
2608                 }
2609         }
2610         if(rectf) {
2611                 /* if scanline updates... */
2612                 rectf+= 4*(rr->rectx*ymin + xmin);
2613                 
2614                 /* when rendering more pixels than needed, we crop away cruft */
2615                 if(rr->crop)
2616                         rectf+= 4*(rr->crop*rr->rectx + rr->crop);
2617         }
2618         
2619         /* tilerect defines drawing offset from (0,0) */
2620         /* however, tilerect (xmin, ymin) is first pixel */
2621         x1 = sima->centx + (rr->tilerect.xmin + rr->crop + xmin)*sima->zoom;
2622         y1 = sima->centy + (rr->tilerect.ymin + rr->crop + ymin)*sima->zoom;
2623         
2624         /* needed for gla draw */
2625         { rcti rct= sa->winrct; rct.ymax-= RW_HEADERY; glaDefine2DArea(&rct);}
2626
2627         glPixelZoom(sima->zoom, sima->zoom);
2628         
2629         if(rect32)
2630                 glaDrawPixelsSafe(x1, y1, xmax, ymax, rr->rectx, GL_RGBA, GL_UNSIGNED_BYTE, rect32);
2631         else
2632                 glaDrawPixelsSafe_to32(x1, y1, xmax, ymax, rr->rectx, rectf);
2633         
2634         glPixelZoom(1.0, 1.0);
2635         
2636 }
2637
2638
2639 /* in render window; display a couple of scanlines of rendered image */
2640 /* NOTE: called while render, so no malloc allowed! */
2641 static void imagewindow_progress_display_cb(RenderResult *rr, volatile rcti *rect)
2642 {
2643         
2644         if (image_area) {
2645                 
2646                 imagewindow_progress(image_area, rr, rect);
2647
2648                 /* no screen_swapbuffers, prevent any other window to draw */
2649                 myswapbuffers();
2650         }
2651 }
2652
2653 /* unused, init_display_cb is called on each render */
2654 static void imagewindow_clear_display_cb(RenderResult *rr)
2655 {
2656         if (image_area) {
2657         }
2658 }
2659
2660 /* returns biggest area that is not uv/image editor. Note that it uses buttons */
2661 /* window as the last possible alternative.                                                                        */
2662 static ScrArea *biggest_non_image_area(void)
2663 {
2664         ScrArea *sa, *big= NULL;
2665         int size, maxsize= 0, bwmaxsize= 0;
2666         short foundwin= 0;
2667         
2668         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
2669                 if(sa->winx > 10 && sa->winy > 10) {
2670                         size= sa->winx*sa->winy;
2671                         if(sa->spacetype == SPACE_BUTS) {
2672                                 if(foundwin == 0 && size > bwmaxsize) {
2673                                         bwmaxsize= size;
2674                                         big= sa;        
2675                                 }
2676                         }
2677                         else if(sa->spacetype != SPACE_IMAGE && size > maxsize) {
2678                                 maxsize= size;
2679                                 big= sa;
2680                                 foundwin= 1;
2681                         }
2682                 }
2683         }
2684                 
2685         return big;
2686 }
2687
2688 static ScrArea *biggest_area(void)
2689 {
2690         ScrArea *sa, *big= NULL;
2691         int size, maxsize= 0;
2692         
2693         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
2694                 size= sa->winx*sa->winy;
2695                 if(size > maxsize) {
2696                         maxsize= size;
2697                         big= sa;
2698                 }
2699         }
2700         return big;
2701 }
2702
2703
2704 /* if R_DISPLAYIMAGE
2705       use Image Window showing Render Result
2706           else: turn largest non-image area into Image Window (not to frustrate texture or composite usage)
2707           else: then we use Image Window anyway...
2708    if R_DISPSCREEN
2709       make a new temp fullscreen area with Image Window
2710 */
2711
2712 static ScrArea *find_area_showing_r_result(void)
2713 {
2714         ScrArea *sa;
2715         SpaceImage *sima;
2716         
2717         /* find an imagewindow showing render result */
2718         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
2719                 if(sa->spacetype==SPACE_IMAGE) {
2720                         sima= sa->spacedata.first;
2721                         if(sima->image && sima->image->type==IMA_TYPE_R_RESULT)
2722                                 break;
2723                 }
2724         }
2725         return sa;
2726 }
2727
2728 static ScrArea *imagewindow_set_render_display(void)
2729 {
2730         ScrArea *sa;
2731         SpaceImage *sima;
2732         
2733         sa= find_area_showing_r_result();
2734         
2735         if(sa==NULL) {
2736                 /* find largest open non-image area */
2737                 sa= biggest_non_image_area();
2738                 if(sa) {
2739                         newspace(sa, SPACE_IMAGE);
2740                         sima= sa->spacedata.first;
2741                         
2742                         /* makes ESC go back to prev space */
2743                         sima->flag |= SI_PREVSPACE;
2744                 }
2745                 else {
2746                         /* use any area of decent size */
2747                         sa= biggest_area();
2748                         if(sa->spacetype!=SPACE_IMAGE) {
2749                                 newspace(sa, SPACE_IMAGE);
2750                                 sima= sa->spacedata.first;
2751                                 
2752                                 /* makes ESC go back to prev space */
2753                                 sima->flag |= SI_PREVSPACE;
2754                         }
2755                 }
2756         }
2757         
2758         sima= sa->spacedata.first;
2759         
2760         /* get the correct image, and scale it */
2761         sima->image= BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
2762         
2763         if(G.displaymode==R_DISPLAYSCREEN) {
2764                 if(sa->full==0) {
2765                         sima->flag |= SI_FULLWINDOW;
2766                         /* fullscreen works with lousy curarea */
2767                         curarea= sa;
2768                         area_fullscreen();
2769                         sa= curarea;
2770                 }
2771         }
2772         
2773         return sa;
2774 }
2775
2776 static void imagewindow_init_display_cb(RenderResult *rr)
2777 {
2778         
2779         image_area= imagewindow_set_render_display();
2780         
2781         if(image_area) {
2782                 SpaceImage *sima= image_area->spacedata.first;
2783                 
2784                 areawinset(image_area->win);
2785                 
2786                 /* calc location using original size (tiles don't tell) */
2787                 sima->centx= (image_area->winx - sima->zoom*(float)rr->rectx)/2.0f;
2788                 sima->centy= (image_area->winy - sima->zoom*(float)rr->recty)/2.0f;
2789                 
2790                 sima->centx-= sima->zoom*sima->xof;
2791                 sima->centy-= sima->zoom*sima->yof;
2792                 
2793                 drawimagespace(image_area, sima);
2794                 if(image_area->headertype) scrarea_do_headdraw(image_area);
2795
2796                 /* no screen_swapbuffers, prevent any other window to draw */
2797                 myswapbuffers();
2798                 
2799                 allqueue(REDRAWIMAGE, 0);       /* redraw in end */
2800         }
2801 }
2802
2803 /* coming from BIF_toggle_render_display() */
2804 void imagewindow_toggle_render(void)
2805 {
2806         ScrArea *sa;
2807         
2808         /* check if any imagewindow is showing temporal render output */
2809         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
2810                 if(sa->spacetype==SPACE_IMAGE) {
2811                         SpaceImage *sima= sa->spacedata.first;
2812                         
2813                         if(sima->image && sima->image->type==IMA_TYPE_R_RESULT)
2814                                 if(sima->flag & (SI_PREVSPACE|SI_FULLWINDOW))
2815                                         break;
2816                 }
2817         }
2818         if(sa) {
2819                 addqueue(sa->win, ESCKEY, 1);   /* also returns from fullscreen */
2820         }
2821         else {
2822                 sa= imagewindow_set_render_display();
2823                 scrarea_queue_headredraw(sa);
2824                 scrarea_queue_winredraw(sa);
2825         }
2826 }
2827
2828 /* NOTE: called while render, so no malloc allowed! */
2829 static void imagewindow_renderinfo_cb(RenderStats *rs)
2830 {
2831         
2832         if(image_area) {
2833                 BIF_make_render_text(rs);
2834
2835                 imagewindow_draw_renderinfo(image_area);
2836                 
2837                 /* no screen_swapbuffers, prevent any other window to draw */
2838                 myswapbuffers();
2839         }
2840 }
2841
2842 void imagewindow_render_callbacks(Render *re)
2843 {
2844         RE_display_init_cb(re, imagewindow_init_display_cb);
2845         RE_display_draw_cb(re, imagewindow_progress_display_cb);
2846         RE_display_clear_cb(re, imagewindow_clear_display_cb);
2847         RE_stats_draw_cb(re, imagewindow_renderinfo_cb);        
2848 }
2849