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