d0261ac1ad038f213ba896bf1fa883b9c2075a77
[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) {
809                         BIF_icon_draw_aspect(xPos, 5.0, ICON_STICKY_UVS, 1.0f);
810                 } else {
811                         BIF_icon_draw_aspect(xPos, 5.0, ICON_STICKY2_UVS, 1.0f);
812                 }
813                 xPos = 25.0;
814                 
815                 if (G.scene->selectmode == SCE_SELECT_FACE || G.sima->flag & SI_SELACTFACE) {
816                         BIF_icon_draw_aspect(xPos, 5.0, ICON_DRAW_UVFACES, 1.0f);
817                 }
818                 
819         } else {
820                 /* use the flags for UV mode - normal operation */      
821                 if(G.sima->flag & SI_STICKYUVS) {
822                         BIF_icon_draw_aspect(xPos, 5.0, ICON_STICKY2_UVS, 1.0f);
823                         xPos = 25.0;
824                 }
825                 else if(!(G.sima->flag & SI_LOCALSTICKY)) {
826                         BIF_icon_draw_aspect(xPos, 5.0, ICON_STICKY_UVS, 1.0f);
827                         xPos = 25.0;
828                 }
829         
830                 if(G.sima->flag & SI_SELACTFACE) {
831                         BIF_icon_draw_aspect(xPos, 5.0, ICON_DRAW_UVFACES, 1.0f);
832                 }
833         }
834         
835         glBlendFunc(GL_ONE,  GL_ZERO); 
836         glDisable(GL_BLEND);
837 }
838
839 static void draw_image_view_tool(void)
840 {
841         ToolSettings *settings= G.scene->toolsettings;
842         Brush *brush= settings->imapaint.brush;
843         short mval[2];
844         float radius;
845         int draw= 0;
846
847         if(brush) {
848                 if(settings->imapaint.flag & IMAGEPAINT_DRAWING) {
849                         if(settings->imapaint.flag & IMAGEPAINT_DRAW_TOOL_DRAWING)
850                                 draw= 1;
851                 }
852                 else if(settings->imapaint.flag & IMAGEPAINT_DRAW_TOOL)
853                         draw= 1;
854                 
855                 if(draw) {
856                         getmouseco_areawin(mval);
857
858                         radius= brush->size*G.sima->zoom/2;
859                         fdrawXORcirc(mval[0], mval[1], radius);
860
861                         if (brush->innerradius != 1.0) {
862                                 radius *= brush->innerradius;
863                                 fdrawXORcirc(mval[0], mval[1], radius);
864                         }
865                 }
866         }
867 }
868
869 /* ************ panel stuff ************* */
870
871 /* this function gets the values for cursor and vertex number buttons */
872 static void image_transform_but_attr(int *imx, int *imy, int *step, int *digits) /*, float *xcoord, float *ycoord)*/
873 {
874         ImBuf *ibuf= imagewindow_get_ibuf(G.sima);
875         if(ibuf) {
876                 *imx= ibuf->x;
877                 *imy= ibuf->y;
878         }
879         
880         if (G.sima->flag & SI_COORDFLOATS) {
881                 *step= 1;
882                 *digits= 3;
883         }
884         else {
885                 *step= 100;
886                 *digits= 2;
887         }
888 }
889
890
891 /* is used for both read and write... */
892 void image_editvertex_buts(uiBlock *block)
893 {
894         static float ocent[2];
895         float cent[2]= {0.0, 0.0};
896         int imx= 256, imy= 256;
897         int nactive= 0, step, digits;
898         EditMesh *em = G.editMesh;
899         EditFace *efa;
900         MTFace *tf;
901         
902         if( is_uv_tface_editing_allowed_silent()==0 ) return;
903         
904         image_transform_but_attr(&imx, &imy, &step, &digits);
905         
906         for (efa= em->faces.first; efa; efa= efa->next) {
907                 tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
908                 if (SIMA_FACEDRAW_CHECK(efa, tf)) {
909                         
910                         if (SIMA_UVSEL_CHECK(efa, tf, 0)) {
911                                 cent[0]+= tf->uv[0][0];
912                                 cent[1]+= tf->uv[0][1];
913                                 nactive++;
914                         }
915                         if (SIMA_UVSEL_CHECK(efa, tf, 1)) {
916                                 cent[0]+= tf->uv[1][0];
917                                 cent[1]+= tf->uv[1][1];
918                                 nactive++;
919                         }
920                         if (SIMA_UVSEL_CHECK(efa, tf, 2)) {
921                                 cent[0]+= tf->uv[2][0];
922                                 cent[1]+= tf->uv[2][1];
923                                 nactive++;
924                         }
925                         if (efa->v4 && SIMA_UVSEL_CHECK(efa, tf, 3)) {
926                                 cent[0]+= tf->uv[3][0];
927                                 cent[1]+= tf->uv[3][1];
928                                 nactive++;
929                         }
930                 }
931         }
932                 
933         if(block) {     // do the buttons
934                 if (nactive) {
935                         ocent[0]= cent[0]/nactive;
936                         ocent[1]= cent[1]/nactive;
937                         if (G.sima->flag & SI_COORDFLOATS) {
938                         } else {
939                                 ocent[0] *= imx;
940                                 ocent[1] *= imy;
941                         }
942                         
943                         uiBlockBeginAlign(block);
944                         if(nactive==1) {
945                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Vertex X:",       10, 40, 145, 19, &ocent[0], -10*imx, 10.0*imx, step, digits, "");
946                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Vertex Y:",       10, 20, 145, 19, &ocent[1], -10*imy, 10.0*imy, step, digits, "");
947                         }
948                         else {
949                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Median X:",       10, 40, 145, 19, &ocent[0], -10*imx, 10.0*imx, step, digits, "");
950                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Median Y:",       10, 20, 145, 19, &ocent[1], -10*imy, 10.0*imy, step, digits, "");
951                         }
952                         uiBlockEndAlign(block);
953                 }
954         }
955         else {  // apply event
956                 float delta[2];
957                 
958                 cent[0]= cent[0]/nactive;
959                 cent[1]= cent[1]/nactive;
960                         
961                 if (G.sima->flag & SI_COORDFLOATS) {
962                         delta[0]= ocent[0]-cent[0];
963                         delta[1]= ocent[1]-cent[1];
964                 }
965                 else {
966                         delta[0]= ocent[0]/imx - cent[0];
967                         delta[1]= ocent[1]/imy - cent[1];
968                 }
969
970                 for (efa= em->faces.first; efa; efa= efa->next) {
971                         tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
972                         if (SIMA_FACEDRAW_CHECK(efa, tf)) {
973                                 if (SIMA_UVSEL_CHECK(efa, tf, 0)) {
974                                         tf->uv[0][0]+= delta[0];
975                                         tf->uv[0][1]+= delta[1];
976                                 }
977                                 if (SIMA_UVSEL_CHECK(efa, tf, 1)) {
978                                         tf->uv[1][0]+= delta[0];
979                                         tf->uv[1][1]+= delta[1];
980                                 }
981                                 if (SIMA_UVSEL_CHECK(efa, tf, 2)) {
982                                         tf->uv[2][0]+= delta[0];
983                                         tf->uv[2][1]+= delta[1];
984                                 }
985                                 if (efa->v4 && SIMA_UVSEL_CHECK(efa, tf, 3)) {
986                                         tf->uv[3][0]+= delta[0];
987                                         tf->uv[3][1]+= delta[1];
988                                 }
989                         }
990                 }
991                         
992                 allqueue(REDRAWVIEW3D, 0);
993                 allqueue(REDRAWIMAGE, 0);
994         }
995 }
996
997
998 /* is used for both read and write... */
999 void image_editcursor_buts(uiBlock *block)
1000 {
1001         static float ocent[2];
1002         int imx= 256, imy= 256;
1003         int step, digits;
1004         
1005         if( is_uv_tface_editing_allowed_silent()==0 ) return;
1006         
1007         image_transform_but_attr(&imx, &imy, &step, &digits);
1008                 
1009         if(block) {     // do the buttons
1010                 ocent[0]= G.v2d->cursor[0];
1011                 ocent[1]= G.v2d->cursor[1];
1012                 if (G.sima->flag & SI_COORDFLOATS) {
1013                 } else {
1014                         ocent[0] *= imx;
1015                         ocent[1] *= imy;
1016                 }
1017                 
1018                 uiBlockBeginAlign(block);
1019                 uiDefButF(block, NUM, B_CURSOR_IMAGE, "Cursor X:",      165, 120, 145, 19, &ocent[0], -10*imx, 10.0*imx, step, digits, "");
1020                 uiDefButF(block, NUM, B_CURSOR_IMAGE, "Cursor Y:",      165, 100, 145, 19, &ocent[1], -10*imy, 10.0*imy, step, digits, "");
1021                 uiBlockEndAlign(block);
1022         }
1023         else {  // apply event
1024                 if (G.sima->flag & SI_COORDFLOATS) {
1025                         G.v2d->cursor[0]= ocent[0];
1026                         G.v2d->cursor[1]= ocent[1];
1027                 }
1028                 else {
1029                         G.v2d->cursor[0]= ocent[0]/imx;
1030                         G.v2d->cursor[1]= ocent[1]/imy;
1031                 }
1032                 allqueue(REDRAWIMAGE, 0);
1033         }
1034 }
1035
1036
1037 void image_info(Image *ima, ImBuf *ibuf, char *str)
1038 {
1039         int ofs= 0;
1040         
1041         str[0]= 0;
1042         
1043         if(ima==NULL) return;
1044         if(ibuf==NULL) {
1045                 sprintf(str, "Can not get an image");
1046                 return;
1047         }
1048         
1049         if(ima->source==IMA_SRC_MOVIE) {
1050                 ofs= sprintf(str, "Movie ");
1051                 if(ima->anim) 
1052                         ofs+= sprintf(str+ofs, "%d frs", IMB_anim_get_duration(ima->anim));
1053         }
1054         else
1055                 ofs= sprintf(str, "Image ");
1056
1057         ofs+= sprintf(str+ofs, ": size %d x %d,", ibuf->x, ibuf->y);
1058         
1059         if(ibuf->rect_float) {
1060                 if(ibuf->channels!=4) {
1061                         sprintf(str+ofs, "%d float channel(s)", ibuf->channels);
1062                 }
1063                 else if(ibuf->depth==32)
1064                         strcat(str, " RGBA float");
1065                 else
1066                         strcat(str, " RGB float");
1067         }
1068         else {
1069                 if(ibuf->depth==32)
1070                         strcat(str, " RGBA byte");
1071                 else
1072                         strcat(str, " RGB byte");
1073         }
1074         if(ibuf->zbuf || ibuf->zbuf_float)
1075                 strcat(str, " + Z");
1076         
1077 }
1078
1079 static void image_panel_properties(short cntrl) // IMAGE_HANDLER_PROPERTIES
1080 {
1081         uiBlock *block;
1082         
1083         block= uiNewBlock(&curarea->uiblocks, "image_panel_properties", UI_EMBOSS, UI_HELV, curarea->win);
1084         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1085         uiSetPanelHandler(IMAGE_HANDLER_PROPERTIES);  // for close and esc
1086         if(uiNewPanel(curarea, block, "Image Properties", "Image", 10, 10, 318, 204)==0)
1087                 return;
1088         
1089         /* note, it draws no bottom half in facemode, for vertex buttons */
1090         uiblock_image_panel(block, &G.sima->image, &G.sima->iuser, B_REDR, B_REDR);
1091 }       
1092
1093 static void image_panel_game_properties(short cntrl)    // IMAGE_HANDLER_GAME_PROPERTIES
1094 {
1095         ImBuf *ibuf= BKE_image_get_ibuf(G.sima->image, &G.sima->iuser);
1096         uiBlock *block;
1097
1098         block= uiNewBlock(&curarea->uiblocks, "image_panel_game_properties", UI_EMBOSS, UI_HELV, curarea->win);
1099         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1100         uiSetPanelHandler(IMAGE_HANDLER_GAME_PROPERTIES);  // for close and esc
1101         if(uiNewPanel(curarea, block, "Real-time Properties", "Image", 10, 10, 318, 204)==0)
1102                 return;
1103
1104         if (ibuf) {
1105                 char str[128];
1106                 
1107                 image_info(G.sima->image, ibuf, str);
1108                 uiDefBut(block, LABEL, B_NOP, str,              10,180,300,19, 0, 0, 0, 0, 0, "");
1109
1110                 uiBlockBeginAlign(block);
1111                 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");
1112                 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");
1113                 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");
1114                 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");
1115                 uiBlockEndAlign(block);
1116
1117                 uiBlockBeginAlign(block);
1118                 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)");
1119                 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");
1120                 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");
1121                 uiBlockBeginAlign(block);
1122
1123                 uiBlockBeginAlign(block);
1124                 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");
1125                 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");
1126                 uiBlockEndAlign(block);
1127         }
1128 }
1129
1130 static void image_panel_transform_properties(short cntrl)       // IMAGE_HANDLER_TRANSFORM_PROPERTIES
1131 {
1132         uiBlock *block;
1133
1134         block= uiNewBlock(&curarea->uiblocks, "image_transform_properties", UI_EMBOSS, UI_HELV, curarea->win);
1135         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1136         uiSetPanelHandler(IMAGE_HANDLER_TRANSFORM_PROPERTIES);  // for close and esc
1137         if(uiNewPanel(curarea, block, "Transform Properties", "Image", 10, 10, 318, 204)==0)
1138                 return;
1139         
1140         image_editvertex_buts(block);
1141         
1142 }
1143
1144 static void image_panel_view_properties(short cntrl)    // IMAGE_HANDLER_VIEW_PROPERTIES
1145 {
1146         uiBlock *block;
1147
1148         block= uiNewBlock(&curarea->uiblocks, "image_view_properties", UI_EMBOSS, UI_HELV, curarea->win);
1149         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1150         uiSetPanelHandler(IMAGE_HANDLER_VIEW_PROPERTIES);  // for close and esc
1151         if(uiNewPanel(curarea, block, "View Properties", "Image", 10, 10, 318, 204)==0)
1152                 return;
1153         
1154         
1155         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");
1156         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");
1157         
1158         
1159         if (G.sima->image) {
1160                 uiDefBut(block, LABEL, B_NOP, "Image Display:",         10,140,140,19, 0, 0, 0, 0, 0, "");
1161                 uiBlockBeginAlign(block);
1162                 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.");
1163                 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.");
1164                 uiBlockEndAlign(block);
1165         }
1166         
1167         
1168         if (EM_texFaceCheck()) {
1169                 uiDefBut(block, LABEL, B_NOP, "Draw Type:",             10, 20,120,19, 0, 0, 0, 0, 0, "");
1170                 uiBlockBeginAlign(block);
1171                 uiDefButC(block,  ROW, B_REDR, "Dash",                  10, 0,58,19, &G.sima->dt_uv, 0.0, 0.0, 0, 0, "Dashed Wire UV drawtype");
1172                 uiDefButC(block,  ROW, B_REDR, "Black",                 68, 0,58,19, &G.sima->dt_uv, 0.0, 1.0, 0, 0, "Black Wire UV drawtype");
1173                 uiDefButC(block,  ROW, B_REDR, "White",                 126,0,58,19, &G.sima->dt_uv, 0.0, 2.0, 0, 0, "White Wire UV drawtype");
1174                 uiDefButC(block,  ROW, B_REDR, "Outline",               184,0,58,19, &G.sima->dt_uv, 0.0, 3.0, 0, 0, "Outline Wire UV drawtype");
1175                 uiBlockBeginAlign(block);
1176                 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");
1177         }
1178         image_editcursor_buts(block);
1179 }
1180
1181 static void image_panel_paint(short cntrl)      // IMAGE_HANDLER_PAINT
1182 {
1183         /* B_SIMABRUSHCHANGE only redraws and eats the mouse messages  */
1184         /* so that LEFTMOUSE does not 'punch' through the floating panel */
1185         /* B_SIMANOTHING */
1186         ToolSettings *settings= G.scene->toolsettings;
1187         Brush *brush= settings->imapaint.brush;
1188         uiBlock *block;
1189         ID *id;
1190         int yco, xco, butw;
1191
1192         block= uiNewBlock(&curarea->uiblocks, "image_panel_paint", UI_EMBOSS, UI_HELV, curarea->win);
1193         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1194         uiSetPanelHandler(IMAGE_HANDLER_PAINT);  // for close and esc
1195         if(uiNewPanel(curarea, block, "Image Paint", "Image", 10, 230, 318, 204)==0)
1196                 return;
1197
1198         yco= 160;
1199
1200         uiBlockBeginAlign(block);
1201         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Draw",                0  ,yco,80,19, &settings->imapaint.tool, 7.0, PAINT_TOOL_DRAW, 0, 0, "Draw brush");
1202         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Soften",              80 ,yco,80,19, &settings->imapaint.tool, 7.0, PAINT_TOOL_SOFTEN, 0, 0, "Soften brush");
1203         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Smear",               160,yco,80,19, &settings->imapaint.tool, 7.0, PAINT_TOOL_SMEAR, 0, 0, "Smear brush");   
1204         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");     
1205         uiBlockEndAlign(block);
1206         yco -= 30;
1207
1208         uiBlockSetCol(block, TH_BUT_SETTING2);
1209         id= (ID*)settings->imapaint.brush;
1210         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);
1211         uiBlockSetCol(block, TH_AUTO);
1212
1213         if(brush && !brush->id.lib) {
1214                 butw= 320-(xco+10);
1215
1216                 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");
1217
1218                 uiDefButBitS(block, TOG|BIT, BRUSH_TORUS, B_SIMABRUSHCHANGE, "Wrap",    xco+10,yco-25,butw,19, &brush->flag, 0, 0, 0, 0, "Enables torus wrapping");
1219
1220                 uiBlockBeginAlign(block);
1221                 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)");
1222                 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");
1223                 uiBlockEndAlign(block);
1224
1225                 yco -= 25;
1226
1227                 uiBlockBeginAlign(block);
1228                 uiDefButF(block, COL, B_VPCOLSLI, "",                                   0,yco,200,19, brush->rgb, 0, 0, 0, 0, "");
1229                 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");
1230                 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");
1231                 uiDefButI(block, NUMSLI, B_SIMANOTHING, "Size ",                0,yco-40,180,19, &brush->size, 1, 200, 0, 0, "The size of the brush");
1232                 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");
1233                 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");
1234                 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");
1235                 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");
1236                 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");
1237                 uiBlockEndAlign(block);
1238
1239                 yco -= 110;
1240
1241                 if(settings->imapaint.tool == PAINT_TOOL_CLONE) {
1242                         id= (ID*)brush->clone.image;
1243                         uiBlockSetCol(block, TH_BUT_SETTING2);
1244                         xco= std_libbuttons(block, 0, yco, 0, NULL, B_SIMACLONEBROWSE, ID_IM, 0, id, 0, &G.sima->menunr, 0, 0, B_SIMACLONEDELETE, 0, 0);
1245                         uiBlockSetCol(block, TH_AUTO);
1246                         if(id) {
1247                                 butw= 320-(xco+5);
1248                                 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");
1249                         }
1250                 }
1251                 else {
1252                         MTex *mtex= brush->mtex[brush->texact];
1253
1254                         uiBlockSetCol(block, TH_BUT_SETTING2);
1255                         id= (mtex)? (ID*)mtex->tex: NULL;
1256                         xco= std_libbuttons(block, 0, yco, 0, NULL, B_SIMABTEXBROWSE, ID_TE, 0, id, NULL, &(G.sima->menunr), 0, 0, B_SIMABTEXDELETE, 0, 0);
1257                         /*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");*/
1258                         uiBlockSetCol(block, TH_AUTO);
1259                 }
1260         }
1261
1262 #if 0
1263                 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");
1264                 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");
1265 #endif
1266 }
1267
1268 static void image_panel_curves_reset(void *cumap_v, void *ibuf_v)
1269 {
1270         CurveMapping *cumap = cumap_v;
1271         int a;
1272         
1273         for(a=0; a<CM_TOT; a++)
1274                 curvemap_reset(cumap->cm+a, &cumap->clipr);
1275         
1276         cumap->black[0]=cumap->black[1]=cumap->black[2]= 0.0f;
1277         cumap->white[0]=cumap->white[1]=cumap->white[2]= 1.0f;
1278         curvemapping_set_black_white(cumap, NULL, NULL);
1279         
1280         curvemapping_changed(cumap, 0);
1281         curvemapping_do_ibuf(cumap, ibuf_v);
1282         
1283         allqueue(REDRAWIMAGE, 0);
1284 }
1285
1286
1287 static void image_panel_curves(short cntrl)     // IMAGE_HANDLER_CURVES
1288 {
1289         ImBuf *ibuf;
1290         uiBlock *block;
1291         uiBut *bt;
1292         
1293         /* and we check for spare */
1294         ibuf= imagewindow_get_ibuf(G.sima);
1295         
1296         block= uiNewBlock(&curarea->uiblocks, "image_panel_curves", UI_EMBOSS, UI_HELV, curarea->win);
1297         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1298         uiSetPanelHandler(IMAGE_HANDLER_CURVES);  // for close and esc
1299         if(uiNewPanel(curarea, block, "Curves", "Image", 10, 450, 318, 204)==0)
1300                 return;
1301         
1302         if (ibuf) {
1303                 rctf rect;
1304                 
1305                 if(G.sima->cumap==NULL)
1306                         G.sima->cumap= curvemapping_add(4, 0.0f, 0.0f, 1.0f, 1.0f);
1307                 
1308                 rect.xmin= 110; rect.xmax= 310;
1309                 rect.ymin= 10; rect.ymax= 200;
1310                 curvemap_buttons(block, G.sima->cumap, 'c', B_SIMACURVES, B_REDR, &rect);
1311                 
1312                 bt=uiDefBut(block, BUT, B_SIMARANGE, "Reset",   10, 160, 90, 19, NULL, 0.0f, 0.0f, 0, 0, "Reset Black/White point and curves");
1313                 uiButSetFunc(bt, image_panel_curves_reset, G.sima->cumap, ibuf);
1314                 
1315                 uiBlockBeginAlign(block);
1316                 uiDefButF(block, NUM, B_SIMARANGE, "Min R:",    10, 120, 90, 19, G.sima->cumap->black, -1000.0f, 1000.0f, 10, 2, "Black level");
1317                 uiDefButF(block, NUM, B_SIMARANGE, "Min G:",    10, 100, 90, 19, G.sima->cumap->black+1, -1000.0f, 1000.0f, 10, 2, "Black level");
1318                 uiDefButF(block, NUM, B_SIMARANGE, "Min B:",    10, 80, 90, 19, G.sima->cumap->black+2, -1000.0f, 1000.0f, 10, 2, "Black level");
1319                 
1320                 uiBlockBeginAlign(block);
1321                 uiDefButF(block, NUM, B_SIMARANGE, "Max R:",    10, 50, 90, 19, G.sima->cumap->white, -1000.0f, 1000.0f, 10, 2, "White level");
1322                 uiDefButF(block, NUM, B_SIMARANGE, "Max G:",    10, 30, 90, 19, G.sima->cumap->white+1, -1000.0f, 1000.0f, 10, 2, "White level");
1323                 uiDefButF(block, NUM, B_SIMARANGE, "Max B:",    10, 10, 90, 19, G.sima->cumap->white+2, -1000.0f, 1000.0f, 10, 2, "White level");
1324                 
1325         }
1326 }
1327
1328 /* are there curves? curves visible? and curves do something? */
1329 static int image_curves_active(ScrArea *sa)
1330 {
1331         SpaceImage *sima= sa->spacedata.first;
1332
1333         if(sima->cumap) {
1334                 if(curvemapping_RGBA_does_something(sima->cumap)) {
1335                         short a;
1336                         for(a=0; a<SPACE_MAXHANDLER; a+=2) {
1337                                 if(sima->blockhandler[a] == IMAGE_HANDLER_CURVES)
1338                                         return 1;
1339                         }
1340                 }
1341         }
1342         return 0;
1343 }
1344
1345 /* 0: disable preview 
1346    otherwise refresh preview
1347 */
1348 void image_preview_event(int event)
1349 {
1350         int exec= 0;
1351         
1352
1353         if(event==0) {
1354                 G.scene->r.scemode &= ~R_COMP_CROP;
1355                 exec= 1;
1356         }
1357         else {
1358                 if(image_preview_active(curarea, NULL, NULL)) {
1359                         G.scene->r.scemode |= R_COMP_CROP;
1360                         exec= 1;
1361                 }
1362                 else
1363                         G.scene->r.scemode &= ~R_COMP_CROP;
1364         }
1365         
1366         if(exec && G.scene->nodetree) {
1367                 /* should work when no node editor in screen..., so we execute right away */
1368                 
1369                 ntreeCompositTagGenerators(G.scene->nodetree);
1370
1371                 G.afbreek= 0;
1372                 G.scene->nodetree->timecursor= set_timecursor;
1373                 G.scene->nodetree->test_break= blender_test_break;
1374                 
1375                 BIF_store_spare();
1376                 
1377                 ntreeCompositExecTree(G.scene->nodetree, &G.scene->r, 1);       /* 1 is do_previews */
1378                 
1379                 G.scene->nodetree->timecursor= NULL;
1380                 G.scene->nodetree->test_break= NULL;
1381                 
1382                 scrarea_do_windraw(curarea);
1383                 waitcursor(0);
1384                 
1385                 allqueue(REDRAWNODE, 1);
1386         }       
1387 }
1388
1389
1390 /* nothing drawn here, we use it to store values */
1391 static void preview_cb(struct ScrArea *sa, struct uiBlock *block)
1392 {
1393         rctf dispf;
1394         rcti *disprect= &G.scene->r.disprect;
1395         int winx= (G.scene->r.size*G.scene->r.xsch)/100;
1396         int winy= (G.scene->r.size*G.scene->r.ysch)/100;
1397         short mval[2];
1398         
1399         if(G.scene->r.mode & R_BORDER) {
1400                 winx*= (G.scene->r.border.xmax - G.scene->r.border.xmin);
1401                 winy*= (G.scene->r.border.ymax - G.scene->r.border.ymin);
1402         }
1403         
1404         /* while dragging we need to update the rects, otherwise it doesn't end with correct one */
1405
1406         BLI_init_rctf(&dispf, 15.0f, (block->maxx - block->minx)-15.0f, 15.0f, (block->maxy - block->miny)-15.0f);
1407         ui_graphics_to_window_rct(sa->win, &dispf, disprect);
1408         
1409         /* correction for gla draw */
1410         BLI_translate_rcti(disprect, -curarea->winrct.xmin, -curarea->winrct.ymin);
1411         
1412         calc_image_view(G.sima, 'p');
1413 //      printf("winrct %d %d %d %d\n", disprect->xmin, disprect->ymin,disprect->xmax, disprect->ymax);
1414         /* map to image space coordinates */
1415         mval[0]= disprect->xmin; mval[1]= disprect->ymin;
1416         areamouseco_to_ipoco(G.v2d, mval, &dispf.xmin, &dispf.ymin);
1417         mval[0]= disprect->xmax; mval[1]= disprect->ymax;
1418         areamouseco_to_ipoco(G.v2d, mval, &dispf.xmax, &dispf.ymax);
1419         
1420         /* map to render coordinates */
1421         disprect->xmin= dispf.xmin;
1422         disprect->xmax= dispf.xmax;
1423         disprect->ymin= dispf.ymin;
1424         disprect->ymax= dispf.ymax;
1425         
1426         CLAMP(disprect->xmin, 0, winx);
1427         CLAMP(disprect->xmax, 0, winx);
1428         CLAMP(disprect->ymin, 0, winy);
1429         CLAMP(disprect->ymax, 0, winy);
1430 //      printf("drawrct %d %d %d %d\n", disprect->xmin, disprect->ymin,disprect->xmax, disprect->ymax);
1431
1432 }
1433
1434 static int is_preview_allowed(ScrArea *cur)
1435 {
1436         SpaceImage *sima= cur->spacedata.first;
1437         ScrArea *sa;
1438
1439         /* check if another areawindow has preview set */
1440         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
1441                 if(sa!=cur && sa->spacetype==SPACE_IMAGE) {
1442                         if(image_preview_active(sa, NULL, NULL))
1443                            return 0;
1444                 }
1445         }
1446         /* check image type */
1447         if(sima->image==NULL || sima->image->type!=IMA_TYPE_COMPOSITE)
1448                 return 0;
1449         
1450         return 1;
1451 }
1452
1453 static void image_panel_preview(ScrArea *sa, short cntrl)       // IMAGE_HANDLER_PREVIEW
1454 {
1455         uiBlock *block;
1456         SpaceImage *sima= sa->spacedata.first;
1457         int ofsx, ofsy;
1458         
1459         if(is_preview_allowed(sa)==0) {
1460                 rem_blockhandler(sa, IMAGE_HANDLER_PREVIEW);
1461                 G.scene->r.scemode &= ~R_COMP_CROP;     /* quite weak */
1462                 return;
1463         }
1464         
1465         block= uiNewBlock(&sa->uiblocks, "image_panel_preview", UI_EMBOSS, UI_HELV, sa->win);
1466         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | UI_PNL_SCALE | cntrl);
1467         uiSetPanelHandler(IMAGE_HANDLER_PREVIEW);  // for close and esc
1468         
1469         ofsx= -150+(sa->winx/2)/sima->blockscale;
1470         ofsy= -100+(sa->winy/2)/sima->blockscale;
1471         if(uiNewPanel(sa, block, "Preview", "Image", ofsx, ofsy, 300, 200)==0) return;
1472         
1473         uiBlockSetDrawExtraFunc(block, preview_cb);
1474         
1475 }
1476
1477 static void image_blockhandlers(ScrArea *sa)
1478 {
1479         SpaceImage *sima= sa->spacedata.first;
1480         short a;
1481
1482         /* warning; blocks need to be freed each time, handlers dont remove  */
1483         uiFreeBlocksWin(&sa->uiblocks, sa->win);
1484         
1485         for(a=0; a<SPACE_MAXHANDLER; a+=2) {
1486                 switch(sima->blockhandler[a]) {
1487
1488                 case IMAGE_HANDLER_PROPERTIES:
1489                         image_panel_properties(sima->blockhandler[a+1]);
1490                         break;
1491                 case IMAGE_HANDLER_GAME_PROPERTIES:
1492                         image_panel_game_properties(sima->blockhandler[a+1]);
1493                         break;
1494                 case IMAGE_HANDLER_TRANSFORM_PROPERTIES:
1495                         if (EM_texFaceCheck())
1496                                 image_panel_transform_properties(sima->blockhandler[a+1]);
1497                         break;
1498                 case IMAGE_HANDLER_VIEW_PROPERTIES:
1499                         image_panel_view_properties(sima->blockhandler[a+1]);
1500                         break;
1501                 case IMAGE_HANDLER_PAINT:
1502                         image_panel_paint(sima->blockhandler[a+1]);
1503                         break;          
1504                 case IMAGE_HANDLER_CURVES:
1505                         image_panel_curves(sima->blockhandler[a+1]);
1506                         break;          
1507                 case IMAGE_HANDLER_PREVIEW:
1508                         image_panel_preview(sa, sima->blockhandler[a+1]);
1509                         break;          
1510                 }
1511                 /* clear action value for event */
1512                 sima->blockhandler[a+1]= 0;
1513         }
1514         uiDrawBlocksPanels(sa, 0);
1515 }
1516
1517 void imagespace_composite_flipbook(ScrArea *sa)
1518 {
1519         SpaceImage *sima= sa->spacedata.first;
1520         ImBuf *ibuf;
1521         int cfrao= G.scene->r.cfra;
1522         int sfra, efra;
1523         
1524         if(sa->spacetype!=SPACE_IMAGE)
1525                 return;
1526         if(sima->iuser.frames<2)
1527                 return;
1528         if(G.scene->nodetree==NULL)
1529                 return;
1530         
1531         sfra= sima->iuser.sfra;
1532         efra= sima->iuser.sfra + sima->iuser.frames-1;
1533         G.scene->nodetree->test_break= blender_test_break;
1534         
1535         for(G.scene->r.cfra=sfra; G.scene->r.cfra<=efra; G.scene->r.cfra++) {
1536                 
1537                 set_timecursor(CFRA);
1538                 
1539                 BKE_image_all_free_anim_ibufs(CFRA);
1540                 ntreeCompositTagAnimated(G.scene->nodetree);
1541                 ntreeCompositExecTree(G.scene->nodetree, &G.scene->r, G.scene->r.cfra!=cfrao);  /* 1 is no previews */
1542                 
1543                 force_draw(0);
1544                 
1545                 ibuf= BKE_image_get_ibuf(sima->image, &sima->iuser);
1546                 /* save memory in flipbooks */
1547                 if(ibuf)
1548                         imb_freerectfloatImBuf(ibuf);
1549                 
1550                 if(blender_test_break())
1551                         break;
1552         }
1553         G.scene->nodetree->test_break= NULL;
1554         waitcursor(0);
1555         
1556         play_anim(0);
1557         
1558         allqueue(REDRAWNODE, 1);
1559         allqueue(REDRAWIMAGE, 1);
1560         
1561         G.scene->r.cfra= cfrao;
1562 }
1563
1564 static void imagespace_grid(SpaceImage *sima)
1565 {
1566         float gridsize, gridstep= 1.0f/32.0f;
1567         float fac, blendfac;
1568         
1569         gridsize= sima->zoom;
1570         
1571         calc_image_view(sima, 'f');
1572         myortho2(sima->v2d.cur.xmin, sima->v2d.cur.xmax, sima->v2d.cur.ymin, sima->v2d.cur.ymax);
1573         
1574         BIF_ThemeColorShade(TH_BACK, 20);
1575         glRectf(0.0, 0.0, 1.0, 1.0);
1576         
1577         if(gridsize<=0.0f) return;
1578         
1579         if(gridsize<1.0f) {
1580                 while(gridsize<1.0f) {
1581                         gridsize*= 4.0;
1582                         gridstep*= 4.0;
1583                 }
1584         }
1585         else {
1586                 while(gridsize>=4.0f) {
1587                         gridsize/= 4.0;
1588                         gridstep/= 4.0;
1589                 }
1590         }
1591         
1592         /* the fine resolution level */
1593         blendfac= 0.25*gridsize - floor(0.25*gridsize);
1594         CLAMP(blendfac, 0.0, 1.0);
1595         BIF_ThemeColorShade(TH_BACK, (int)(20.0*(1.0-blendfac)));
1596         
1597         fac= 0.0f;
1598         glBegin(GL_LINES);
1599         while(fac<1.0) {
1600                 glVertex2f(0.0f, fac);
1601                 glVertex2f(1.0f, fac);
1602                 glVertex2f(fac, 0.0f);
1603                 glVertex2f(fac, 1.0f);
1604                 fac+= gridstep;
1605         }
1606         
1607         /* the large resolution level */
1608         BIF_ThemeColor(TH_BACK);
1609         
1610         fac= 0.0f;
1611         while(fac<1.0) {
1612                 glVertex2f(0.0f, fac);
1613                 glVertex2f(1.0f, fac);
1614                 glVertex2f(fac, 0.0f);
1615                 glVertex2f(fac, 1.0f);
1616                 fac+= 4.0*gridstep;
1617         }
1618         glEnd();
1619         
1620 }
1621
1622 static void sima_draw_alpha_backdrop(SpaceImage *sima, float x1, float y1, float xsize, float ysize)
1623 {
1624         float tile= sima->zoom*15.0f;
1625         float x, y, maxx, maxy;
1626         
1627         glColor3ub(100, 100, 100);
1628         glRectf(x1, y1, x1 + sima->zoom*xsize, y1 + sima->zoom*ysize);
1629         glColor3ub(160, 160, 160);
1630         
1631         maxx= x1+sima->zoom*xsize;
1632         maxy= y1+sima->zoom*ysize;
1633         
1634         for(x=0; x<xsize; x+=30) {
1635                 for(y=0; y<ysize; y+=30) {
1636                         float fx= x1 + sima->zoom*x;
1637                         float fy= y1 + sima->zoom*y;
1638                         float tilex= tile, tiley= tile;
1639                         
1640                         if(fx+tile > maxx)
1641                                 tilex= maxx-fx;
1642                         if(fy+tile > maxy)
1643                                 tiley= maxy-fy;
1644                         
1645                         glRectf(fx, fy, fx + tilex, fy + tiley);
1646                 }
1647         }
1648         for(x=15; x<xsize; x+=30) {
1649                 for(y=15; y<ysize; y+=30) {
1650                         float fx= x1 + sima->zoom*x;
1651                         float fy= y1 + sima->zoom*y;
1652                         float tilex= tile, tiley= tile;
1653                         
1654                         if(fx+tile > maxx)
1655                                 tilex= maxx-fx;
1656                         if(fy+tile > maxy)
1657                                 tiley= maxy-fy;
1658                         
1659                         glRectf(fx, fy, fx + tilex, fy + tiley);
1660                 }
1661         }
1662 }
1663
1664 static void sima_draw_alpha_pixels(float x1, float y1, int rectx, int recty, unsigned int *recti)
1665 {
1666         
1667         /* swap bytes, so alpha is most significant one, then just draw it as luminance int */
1668         if(G.order==B_ENDIAN)
1669                 glPixelStorei(GL_UNPACK_SWAP_BYTES, 1);
1670         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_UNSIGNED_INT, recti);
1671         glPixelStorei(GL_UNPACK_SWAP_BYTES, 0);
1672 }
1673
1674 static void sima_draw_alpha_pixelsf(float x1, float y1, int rectx, int recty, float *rectf)
1675 {
1676         float *trectf= MEM_mallocN(rectx*recty*4, "temp");
1677         int a, b;
1678         
1679         for(a= rectx*recty -1, b= 4*a+3; a>=0; a--, b-=4)
1680                 trectf[a]= rectf[b];
1681         
1682         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_FLOAT, trectf);
1683         MEM_freeN(trectf);
1684         /* ogl trick below is slower... (on ATI 9600) */
1685 //      glColorMask(1, 0, 0, 0);
1686 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+3);
1687 //      glColorMask(0, 1, 0, 0);
1688 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+2);
1689 //      glColorMask(0, 0, 1, 0);
1690 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+1);
1691 //      glColorMask(1, 1, 1, 1);
1692 }
1693
1694 static void sima_draw_zbuf_pixels(float x1, float y1, int rectx, int recty, int *recti)
1695 {
1696         if(recti==NULL)
1697                 return;
1698         
1699         /* zbuffer values are signed, so we need to shift color range */
1700         glPixelTransferf(GL_RED_SCALE, 0.5f);
1701         glPixelTransferf(GL_GREEN_SCALE, 0.5f);
1702         glPixelTransferf(GL_BLUE_SCALE, 0.5f);
1703         glPixelTransferf(GL_RED_BIAS, 0.5f);
1704         glPixelTransferf(GL_GREEN_BIAS, 0.5f);
1705         glPixelTransferf(GL_BLUE_BIAS, 0.5f);
1706         
1707         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_INT, recti);
1708         
1709         glPixelTransferf(GL_RED_SCALE, 1.0f);
1710         glPixelTransferf(GL_GREEN_SCALE, 1.0f);
1711         glPixelTransferf(GL_BLUE_SCALE, 1.0f);
1712         glPixelTransferf(GL_RED_BIAS, 0.0f);
1713         glPixelTransferf(GL_GREEN_BIAS, 0.0f);
1714         glPixelTransferf(GL_BLUE_BIAS, 0.0f);
1715 }
1716
1717 static void sima_draw_zbuffloat_pixels(float x1, float y1, int rectx, int recty, float *rect_float)
1718 {
1719         float bias, scale, *rectf, clipend;
1720         int a;
1721         
1722         if(rect_float==NULL)
1723                 return;
1724         
1725         if(G.scene->camera && G.scene->camera->type==OB_CAMERA) {
1726                 bias= ((Camera *)G.scene->camera->data)->clipsta;
1727                 clipend= ((Camera *)G.scene->camera->data)->clipend;
1728                 scale= 1.0f/(clipend-bias);
1729         }
1730         else {
1731                 bias= 0.1f;
1732                 scale= 0.01f;
1733                 clipend= 100.0f;
1734         }
1735         
1736         rectf= MEM_mallocN(rectx*recty*4, "temp");
1737         for(a= rectx*recty -1; a>=0; a--) {
1738                 if(rect_float[a]>clipend)
1739                         rectf[a]= 0.0f;
1740                 else if(rect_float[a]<bias)
1741                         rectf[a]= 1.0f;
1742                 else {
1743                         rectf[a]= 1.0f - (rect_float[a]-bias)*scale;
1744                         rectf[a]*= rectf[a];
1745                 }
1746         }
1747         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_FLOAT, rectf);
1748         
1749         MEM_freeN(rectf);
1750 }
1751
1752 static void imagewindow_draw_renderinfo(ScrArea *sa)
1753 {
1754         SpaceImage *sima= sa->spacedata.first;
1755         rcti rect;
1756         float colf[3];
1757         char *str= sima->showspare?sima->info_spare:sima->info_str;
1758         
1759         if(str==NULL)
1760                 return;
1761         
1762         rect= sa->winrct;
1763         rect.ymin= rect.ymax-RW_HEADERY;
1764         
1765         glaDefine2DArea(&rect);
1766         
1767         /* clear header rect */
1768         BIF_GetThemeColor3fv(TH_BACK, colf);
1769         glClearColor(colf[0]+0.1f, colf[1]+0.1f, colf[2]+0.1f, 1.0); 
1770         glClear(GL_COLOR_BUFFER_BIT);
1771         
1772         BIF_ThemeColor(TH_TEXT_HI);
1773         glRasterPos2i(12, 5);
1774         if(sima->showspare) {
1775                 BMF_DrawString(G.fonts, "(Previous)");
1776                 glRasterPos2i(72, 5);
1777         }               
1778         BMF_DrawString(G.fonts, str);
1779 }
1780
1781 void drawimagespace(ScrArea *sa, void *spacedata)
1782 {
1783         SpaceImage *sima= spacedata;
1784         ImBuf *ibuf= NULL;
1785         Brush *brush;
1786         float col[3];
1787         unsigned int *rect;
1788         float x1, y1;
1789         short sx, sy, dx, dy, show_render= 0, show_viewer= 0;
1790         float xuser_asp, yuser_asp;
1791                 /* If derived data is used then make sure that object
1792                  * is up-to-date... might not be the case because updates
1793                  * are normally done in drawview and could get here before
1794                  * drawing a View3D.
1795                  */
1796         if (!G.obedit && OBACT && (sima->flag & SI_DRAWSHADOW)) {
1797                 object_handle_update(OBACT);
1798         }
1799         
1800         BIF_GetThemeColor3fv(TH_BACK, col);
1801         glClearColor(col[0], col[1], col[2], 0.0);
1802         glClear(GL_COLOR_BUFFER_BIT);
1803
1804         bwin_clear_viewmat(sa->win);    /* clear buttons view */
1805         glLoadIdentity();
1806         
1807         if(sima->image && sima->image->source==IMA_SRC_VIEWER) {
1808                 show_viewer= 1;
1809                 if(sima->image->type==IMA_TYPE_R_RESULT)
1810                         show_render= 1;
1811         }
1812         what_image(sima);
1813         
1814         aspect_sima(sima, &xuser_asp, &yuser_asp);
1815         
1816         if(sima->image) {
1817                 
1818                 /* UGLY hack? until now iusers worked fine... but for flipbook viewer we need this */
1819                 if(sima->image->type==IMA_TYPE_COMPOSITE) {
1820                         ImageUser *iuser= ntree_get_active_iuser(G.scene->nodetree);
1821                         if(iuser) {
1822                                 BKE_image_user_calc_imanr(iuser, G.scene->r.cfra, 0);
1823                                 G.sima->iuser= *iuser;
1824                         }
1825                 }
1826                 /* and we check for spare */
1827                 ibuf= imagewindow_get_ibuf(sima);
1828         }
1829         
1830         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL)) {
1831                 imagespace_grid(sima);
1832                 if(show_viewer==0) {
1833                         draw_uvs_sima();
1834                         drawcursor_sima(xuser_asp, yuser_asp);
1835                 }
1836         }
1837         else {
1838                 float xim, yim, xoffs=0.0f, yoffs= 0.0f;
1839                 
1840                 if(image_preview_active(sa, &xim, &yim)) {
1841                         xoffs= G.scene->r.disprect.xmin;
1842                         yoffs= G.scene->r.disprect.ymin;
1843                         glColor3ub(0,0,0);
1844                         calc_image_view(sima, 'f');     
1845                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
1846                         glRectf(0.0f, 0.0f, 1.0f, 1.0f);
1847                         glLoadIdentity();
1848                 }
1849                 else {
1850                         xim= ibuf->x * xuser_asp; yim= ibuf->y * yuser_asp;
1851                 }
1852                 
1853                 /* calc location */
1854                 x1= sima->zoom*xoffs + ((float)sa->winx - sima->zoom*(float)xim)/2.0f;
1855                 y1= sima->zoom*yoffs + ((float)sa->winy - sima->zoom*(float)yim)/2.0f;
1856         
1857                 x1-= sima->zoom*sima->xof;
1858                 y1-= sima->zoom*sima->yof;
1859                 
1860                 /* needed for gla draw */
1861                 if(show_render) { 
1862                         rcti rct= sa->winrct; 
1863                         
1864                         imagewindow_draw_renderinfo(sa);        /* calls glaDefine2DArea too */
1865                         
1866                         rct.ymax-=RW_HEADERY; 
1867                         glaDefine2DArea(&rct);
1868                 }
1869                 else glaDefine2DArea(&sa->winrct);
1870                 
1871                 glPixelZoom(sima->zoom * xuser_asp, sima->zoom * yuser_asp);
1872                                 
1873                 if(sima->flag & SI_EDITTILE) {
1874                         /* create char buffer from float if needed */
1875                         if(ibuf->rect_float && ibuf->rect==NULL)
1876                                 IMB_rect_from_float(ibuf);
1877
1878                         glaDrawPixelsSafe(x1, y1, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1879                         
1880                         glPixelZoom(1.0, 1.0);
1881                         
1882                         dx= ibuf->x/sima->image->xrep;
1883                         dy= ibuf->y/sima->image->yrep;
1884                         sy= (sima->curtile / sima->image->xrep);
1885                         sx= sima->curtile - sy*sima->image->xrep;
1886         
1887                         sx*= dx;
1888                         sy*= dy;
1889                         
1890                         calc_image_view(sima, 'p');     /* pixel */
1891                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
1892                         
1893                         cpack(0x0);
1894                         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRects(sx,  sy,  sx+dx-1,  sy+dy-1); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1895                         cpack(0xFFFFFF);
1896                         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRects(sx+1,  sy+1,  sx+dx,  sy+dy); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1897                 }
1898                 else if(sima->mode==SI_TEXTURE) {
1899                         
1900                         if(sima->image->tpageflag & IMA_TILES) {
1901                                 
1902                                 /* just leave this a while */
1903                                 if(sima->image->xrep<1) return;
1904                                 if(sima->image->yrep<1) return;
1905                                 
1906                                 if(sima->curtile >= sima->image->xrep*sima->image->yrep) 
1907                                         sima->curtile = sima->image->xrep*sima->image->yrep - 1; 
1908                                 
1909                                 dx= ibuf->x/sima->image->xrep;
1910                                 dy= ibuf->y/sima->image->yrep;
1911                                 
1912                                 sy= (sima->curtile / sima->image->xrep);
1913                                 sx= sima->curtile - sy*sima->image->xrep;
1914                 
1915                                 sx*= dx;
1916                                 sy*= dy;
1917                                 
1918                                 /* create char buffer from float if needed */
1919                                 if(ibuf->rect_float && ibuf->rect==NULL)
1920                                         IMB_rect_from_float(ibuf);
1921
1922                                 rect= get_part_from_ibuf(ibuf, sx, sy, sx+dx, sy+dy);
1923                                 
1924                                 /* rect= ibuf->rect; */
1925                                 for(sy= 0; sy+dy<=ibuf->y; sy+= dy) {
1926                                         for(sx= 0; sx+dx<=ibuf->x; sx+= dx) {
1927                                                 glaDrawPixelsSafe(x1+sx*sima->zoom, y1+sy*sima->zoom, dx, dy, dx, GL_RGBA, GL_UNSIGNED_BYTE, rect);
1928                                         }
1929                                 }
1930                                 
1931                                 MEM_freeN(rect);
1932                         }
1933                         else {
1934                                 float x1_rep, y1_rep;
1935                                 int x_rep, y_rep;
1936                                 double time_current;
1937                                 short loop_draw_ok = 0;
1938                                 
1939                                 if (sima->flag & SI_DRAW_TILE) {
1940                                         loop_draw_ok= 1;
1941                                 }
1942                                 
1943                                 time_current = PIL_check_seconds_timer();
1944                                 
1945                                 for (x_rep= ((int)G.v2d->cur.xmin)-1; x_rep < G.v2d->cur.xmax; x_rep++) {
1946                                         x1_rep=x1+  ((x_rep* ibuf->x * sima->zoom)  *xuser_asp);
1947                                         for (y_rep= ((int)G.v2d->cur.ymin)-1; y_rep < G.v2d->cur.ymax; y_rep++) {
1948                                                 y1_rep=y1+  ((y_rep * ibuf->y *sima->zoom)  *yuser_asp);
1949                                 
1950                                 /* end repeating image loop */
1951                                                 
1952                                                 if(!loop_draw_ok) {
1953                                                         y1_rep = y1;
1954                                                         x1_rep = x1;
1955                                                 }
1956                                                 
1957                                                 /*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);*/
1958                                                 
1959                                                 /* this part is generic image display */
1960                                                 if(sima->flag & SI_SHOW_ALPHA) {
1961                                                         if(ibuf->rect)
1962                                                                 sima_draw_alpha_pixels(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->rect);
1963                                                         else if(ibuf->rect_float && ibuf->channels==4)
1964                                                                 sima_draw_alpha_pixelsf(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->rect_float);
1965                                                 }
1966                                                 else if(sima->flag & SI_SHOW_ZBUF && ((ibuf->zbuf || ibuf->zbuf_float || (ibuf->channels==1)) == 0)) {
1967                                                         if(ibuf->zbuf)
1968                                                                 sima_draw_zbuf_pixels(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->zbuf);
1969                                                         else if(ibuf->zbuf_float)
1970                                                                 sima_draw_zbuffloat_pixels(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->zbuf_float);
1971                                                         else if(ibuf->channels==1)
1972                                                                 sima_draw_zbuffloat_pixels(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->rect_float);
1973                                                 }
1974                                                 else {
1975                                                         if(sima->flag & SI_USE_ALPHA) {
1976                                                                 sima_draw_alpha_backdrop(sima, x1_rep, y1_rep, (float)ibuf->x, (float)ibuf->y);
1977                                                                 glEnable(GL_BLEND);
1978                                                                 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
1979                                                         }
1980                                                         
1981                                                         /* detect if we need to redo the curve map. 
1982                                                            ibuf->rect is zero for compositor and render results after change 
1983                                                            convert to 32 bits always... drawing float rects isnt supported well (atis)
1984                                                         
1985                                                            NOTE: if float buffer changes, we have to manually remove the rect
1986                                                         */
1987                                                         
1988                                                         if(ibuf->rect_float) {
1989                                                                 if(ibuf->rect==NULL) {
1990                                                                         if(image_curves_active(sa))
1991                                                                                 curvemapping_do_ibuf(G.sima->cumap, ibuf);
1992                                                                         else 
1993                                                                                 IMB_rect_from_float(ibuf);
1994                                                                 }
1995                                                         }
1996                 
1997                                                         if(ibuf->rect)
1998                                                                 glaDrawPixelsSafe(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1999                 //                                      else
2000                 //                                              glaDrawPixelsSafe(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_FLOAT, ibuf->rect_float);
2001                                                         
2002                                                         if(sima->flag & SI_USE_ALPHA)
2003                                                                 glDisable(GL_BLEND);
2004                                                 }
2005                                                 
2006                                                 /* only draw once */
2007                                                 if(!loop_draw_ok) {
2008                                                         break; /* only draw once */
2009                                                 } else if ((PIL_check_seconds_timer() - time_current) > 0.25) {
2010                                                         loop_draw_ok = 0;
2011                                                         break;
2012                                                 }
2013                                 
2014                                 /* tile draw loop */
2015                                         }
2016                                         /* only draw once */
2017                                         if(!loop_draw_ok) break;
2018                                 }
2019                                 /* tile draw loop */
2020                                 
2021                         }
2022                         
2023                         brush= G.scene->toolsettings->imapaint.brush;
2024                         if(brush && (G.scene->toolsettings->imapaint.tool == PAINT_TOOL_CLONE)) {
2025                                 int w, h;
2026                                 unsigned char *clonerect;
2027
2028                                 /* this is not very efficient, but glDrawPixels doesn't allow
2029                                    drawing with alpha */
2030                                 clonerect= alloc_alpha_clone_image(&w, &h);
2031
2032                                 if(clonerect) {
2033                                         int offx, offy;
2034                                         offx = sima->zoom*ibuf->x * + brush->clone.offset[0];
2035                                         offy = sima->zoom*ibuf->y * + brush->clone.offset[1];
2036
2037                                         glEnable(GL_BLEND);
2038                                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2039                                         glaDrawPixelsSafe(x1 + offx, y1 + offy, w, h, w, GL_RGBA, GL_UNSIGNED_BYTE, clonerect);
2040                                         glDisable(GL_BLEND);
2041
2042                                         MEM_freeN(clonerect);
2043                                 }
2044                         }
2045                         
2046                         glPixelZoom(1.0, 1.0);
2047                         
2048                         if(show_viewer==0) { 
2049                                 draw_uvs_sima();
2050                                 drawcursor_sima(xuser_asp, yuser_asp);
2051                         }
2052                 }
2053
2054                 glPixelZoom(1.0, 1.0);
2055
2056                 calc_image_view(sima, 'f');     /* float */
2057         }
2058
2059         draw_image_transform(ibuf, xuser_asp, yuser_asp);
2060
2061         mywinset(sa->win);      /* restore scissor after gla call... */
2062         myortho2(-0.375, sa->winx-0.375, -0.375, sa->winy-0.375);
2063
2064         if(G.rendering==0) {
2065                 draw_image_view_tool();
2066                 draw_image_view_icon();
2067         }
2068         draw_area_emboss(sa);
2069
2070         /* it is important to end a view in a transform compatible with buttons */
2071         bwin_scalematrix(sa->win, sima->blockscale, sima->blockscale, sima->blockscale);
2072         if(!(G.rendering && show_render))
2073                 image_blockhandlers(sa);
2074
2075         sa->win_swap= WIN_BACK_OK;
2076 }
2077
2078 static void image_zoom_power_of_two(void)
2079 {
2080         /* Make zoom a power of 2 */
2081
2082         G.sima->zoom = 1 / G.sima->zoom;
2083         G.sima->zoom = log(G.sima->zoom) / log(2);
2084         G.sima->zoom = ceil(G.sima->zoom);
2085         G.sima->zoom = pow(2, G.sima->zoom);
2086         G.sima->zoom = 1 / G.sima->zoom;
2087 }
2088
2089 static void image_zoom_set_factor(float zoomfac)
2090 {
2091         SpaceImage *sima= curarea->spacedata.first;
2092         int width, height;
2093
2094         if (zoomfac <= 0.0f)
2095                 return;
2096
2097         sima->zoom *= zoomfac;
2098
2099         if (sima->zoom > 0.1f && sima->zoom < 4.0f)
2100                 return;
2101
2102         /* check zoom limits */
2103
2104         calc_image_view(G.sima, 'f'); /* was 'p' are there any cases where this should be 'p'?*/
2105         width= 256;
2106         height= 256;
2107         if (sima->image) {
2108                 ImBuf *ibuf= imagewindow_get_ibuf(sima);
2109
2110                 if (ibuf) {
2111                         float xim, yim;
2112                         /* I know a bit weak... but preview uses not actual image size */
2113                         if(image_preview_active(curarea, &xim, &yim)) {
2114                                 width= (int) xim;
2115                                 height= (int) yim;
2116                         }
2117                         else {
2118                                 width= ibuf->x;
2119                                 height= ibuf->y;
2120                         }
2121                 }
2122         }
2123         width *= sima->zoom;
2124         height *= sima->zoom;
2125
2126         if ((width < 4) && (height < 4))
2127                 sima->zoom /= zoomfac;
2128         else if((curarea->winrct.xmax - curarea->winrct.xmin) <= sima->zoom)
2129                 sima->zoom /= zoomfac;
2130         else if((curarea->winrct.ymax - curarea->winrct.ymin) <= sima->zoom)
2131                 sima->zoom /= zoomfac;
2132 }
2133
2134 void image_viewmove(int mode)
2135 {
2136         short mval[2], mvalo[2], zoom0;
2137         int oldcursor;
2138         Window *win;
2139         
2140         getmouseco_sc(mvalo);
2141         zoom0= G.sima->zoom;
2142         
2143         oldcursor=get_cursor();
2144         win=winlay_get_active_window();
2145         
2146         SetBlenderCursor(BC_NSEW_SCROLLCURSOR);
2147         
2148         while(get_mbut()&(L_MOUSE|M_MOUSE)) {
2149
2150                 getmouseco_sc(mval);
2151
2152                 if(mvalo[0]!=mval[0] || mvalo[1]!=mval[1]) {
2153                 
2154                         if(mode==0) {
2155                                 G.sima->xof += (mvalo[0]-mval[0])/G.sima->zoom;
2156                                 G.sima->yof += (mvalo[1]-mval[1])/G.sima->zoom;
2157                         }
2158                         else if (mode==1) {
2159                                 float factor;
2160
2161                                 factor= 1.0+(float)(mvalo[0]-mval[0]+mvalo[1]-mval[1])/300.0;
2162                                 image_zoom_set_factor(factor);
2163                         }
2164
2165                         mvalo[0]= mval[0];
2166                         mvalo[1]= mval[1];
2167                         
2168                         scrarea_do_windraw(curarea);
2169                         screen_swapbuffers();
2170                 }
2171                 else BIF_wait_for_statechange();
2172         }
2173         window_set_cursor(win, oldcursor);
2174         
2175         if(image_preview_active(curarea, NULL, NULL)) {
2176                 /* recalculates new preview rect */
2177                 scrarea_do_windraw(curarea);
2178                 image_preview_event(2);
2179         }
2180 }
2181
2182 void image_viewzoom(unsigned short event, int invert)
2183 {
2184         SpaceImage *sima= curarea->spacedata.first;
2185
2186         if(event==WHEELDOWNMOUSE || event==PADMINUS)
2187                 image_zoom_set_factor((U.uiflag & USER_WHEELZOOMDIR)? 1.25: 0.8);
2188         else if(event==WHEELUPMOUSE || event==PADPLUSKEY)
2189                 image_zoom_set_factor((U.uiflag & USER_WHEELZOOMDIR)? 0.8: 1.25);
2190         else if(event==PAD1)
2191                 sima->zoom= 1.0;
2192         else if(event==PAD2)
2193                 sima->zoom= (invert)? 2.0: 0.5;
2194         else if(event==PAD4)
2195                 sima->zoom= (invert)? 4.0: 0.25;
2196         else if(event==PAD8)
2197                 sima->zoom= (invert)? 8.0: 0.125;
2198         
2199         /* ensure pixel exact locations for draw */
2200         sima->xof= (int)sima->xof;
2201         sima->yof= (int)sima->yof;
2202         
2203         if(image_preview_active(curarea, NULL, NULL)) {
2204                 /* recalculates new preview rect */
2205                 scrarea_do_windraw(curarea);
2206                 image_preview_event(2);
2207         }
2208 }
2209
2210 /**
2211  * Updates the fields of the View2D member of the SpaceImage struct.
2212  * Default behavior is to reset the position of the image and set the zoom to 1
2213  * If the image will not fit within the window rectangle, the zoom is adjusted
2214  *
2215  * @return    void
2216  *   
2217  */
2218 void image_home(void)
2219 {
2220         ImBuf *ibuf;
2221         int width, height, imgwidth, imgheight;
2222         float zoomX, zoomY;
2223
2224         if (curarea->spacetype != SPACE_IMAGE) return;
2225         ibuf= imagewindow_get_ibuf(G.sima);
2226         
2227         if (ibuf == NULL) {
2228                 imgwidth = 256;
2229                 imgheight = 256;
2230         }
2231         else {
2232                 imgwidth = ibuf->x;
2233                 imgheight = ibuf->y;
2234         }
2235
2236         /* Check if the image will fit in the image with zoom==1 */
2237         width = curarea->winx;
2238         height = curarea->winy;
2239         if (((imgwidth >= width) || (imgheight >= height)) && 
2240                 ((width > 0) && (height > 0))) {
2241                 /* Find the zoom value that will fit the image in the image space */
2242                 zoomX = ((float)width) / ((float)imgwidth);
2243                 zoomY = ((float)height) / ((float)imgheight);
2244                 G.sima->zoom= MIN2(zoomX, zoomY);
2245
2246                 image_zoom_power_of_two();
2247         }
2248         else {
2249                 G.sima->zoom= 1.0f;
2250         }
2251
2252         G.sima->xof= G.sima->yof= 0.0f;
2253         
2254         calc_image_view(G.sima, 'f'); /* was 'p' are there any cases where this should be 'p'?*/
2255         /*calc_arearcts(curarea);*/
2256         scrarea_queue_winredraw(curarea);
2257         scrarea_queue_winredraw(curarea);
2258 }
2259
2260 void image_viewcenter(void)
2261 {
2262         ImBuf *ibuf= BKE_image_get_ibuf(G.sima->image, &G.sima->iuser);
2263         float size, min[2], max[2], d[2], xim=256.0f, yim=256.0f;
2264
2265         if( is_uv_tface_editing_allowed()==0 ) return;
2266
2267         if (!minmax_tface_uv(min, max)) return;
2268
2269         if(ibuf) {
2270                 xim= ibuf->x;
2271                 yim= ibuf->y;
2272         }
2273
2274         G.sima->xof= (int) (((min[0] + max[0])*0.5f - 0.5f)*xim);
2275         G.sima->yof= (int) (((min[1] + max[1])*0.5f - 0.5f)*yim);
2276
2277         d[0] = max[0] - min[0];
2278         d[1] = max[1] - min[1];
2279         size= 0.5*MAX2(d[0], d[1])*MAX2(xim, yim)/256.0f;
2280         
2281         if(size<=0.01) size= 0.01;
2282
2283         G.sima->zoom= 0.7/size;
2284
2285         calc_image_view(G.sima, 'f'); /* was 'p' are there any cases where 'p' is still needed? */
2286
2287         scrarea_queue_winredraw(curarea);
2288 }
2289
2290
2291 /* *********************** render callbacks ***************** */
2292
2293 /* set on initialize render, only one render output to imagewindow can exist, so the global isnt dangerous yet :) */
2294 static ScrArea *image_area= NULL;
2295
2296 /* can get as well the full picture, as the parts while rendering */
2297 static void imagewindow_progress(ScrArea *sa, RenderResult *rr, volatile rcti *renrect)
2298 {
2299         SpaceImage *sima= sa->spacedata.first;
2300         float x1, y1, *rectf= NULL;
2301         unsigned int *rect32= NULL;
2302         int ymin, ymax, xmin, xmax;
2303         
2304         /* if renrect argument, we only display scanlines */
2305         if(renrect) {
2306                 /* if ymax==recty, rendering of layer is ready, we should not draw, other things happen... */
2307                 if(rr->renlay==NULL || renrect->ymax>=rr->recty)
2308                         return;
2309                 
2310                 /* xmin here is first subrect x coord, xmax defines subrect width */
2311                 xmin = renrect->xmin;
2312                 xmax = renrect->xmax - xmin;
2313                 if (xmax<2) return;
2314                 
2315                 ymin= renrect->ymin;
2316                 ymax= renrect->ymax - ymin;
2317                 if(ymax<2)
2318                         return;
2319                 renrect->ymin= renrect->ymax;
2320         }
2321         else {
2322                 xmin = ymin = 0;
2323                 xmax = rr->rectx - 2*rr->crop;
2324                 ymax = rr->recty - 2*rr->crop;
2325         }
2326         
2327         /* image window cruft */
2328         
2329         /* find current float rect for display, first case is after composit... still weak */
2330         if(rr->rectf)
2331                 rectf= rr->rectf;
2332         else {
2333                 if(rr->rect32)
2334                         rect32= (unsigned int *)rr->rect32;
2335                 else {
2336                         if(rr->renlay==NULL || rr->renlay->rectf==NULL) return;
2337                         rectf= rr->renlay->rectf;
2338                 }
2339         }
2340         if(rectf) {
2341                 /* if scanline updates... */
2342                 rectf+= 4*(rr->rectx*ymin + xmin);
2343                 
2344                 /* when rendering more pixels than needed, we crop away cruft */
2345                 if(rr->crop)
2346                         rectf+= 4*(rr->crop*rr->rectx + rr->crop);
2347         }
2348         
2349         /* tilerect defines drawing offset from (0,0) */
2350         /* however, tilerect (xmin, ymin) is first pixel */
2351         x1 = sima->centx + (rr->tilerect.xmin + rr->crop + xmin)*sima->zoom;
2352         y1 = sima->centy + (rr->tilerect.ymin + rr->crop + ymin)*sima->zoom;
2353         
2354         /* needed for gla draw */
2355         { rcti rct= sa->winrct; rct.ymax-= RW_HEADERY; glaDefine2DArea(&rct);}
2356
2357         glPixelZoom(sima->zoom, sima->zoom);
2358         
2359         if(rect32)
2360                 glaDrawPixelsSafe(x1, y1, xmax, ymax, rr->rectx, GL_RGBA, GL_UNSIGNED_BYTE, rect32);
2361         else
2362                 glaDrawPixelsSafe_to32(x1, y1, xmax, ymax, rr->rectx, rectf);
2363         
2364         glPixelZoom(1.0, 1.0);
2365         
2366 }
2367
2368
2369 /* in render window; display a couple of scanlines of rendered image */
2370 /* NOTE: called while render, so no malloc allowed! */
2371 static void imagewindow_progress_display_cb(RenderResult *rr, volatile rcti *rect)
2372 {
2373         
2374         if (image_area) {
2375                 
2376                 imagewindow_progress(image_area, rr, rect);
2377
2378                 /* no screen_swapbuffers, prevent any other window to draw */
2379                 myswapbuffers();
2380         }
2381 }
2382
2383 /* unused, init_display_cb is called on each render */
2384 static void imagewindow_clear_display_cb(RenderResult *rr)
2385 {
2386         if (image_area) {
2387         }
2388 }
2389
2390 /* returns biggest area that is not uv/image editor. Note that it uses buttons */
2391 /* window as the last possible alternative.                                                                        */
2392 static ScrArea *biggest_non_image_area(void)
2393 {
2394         ScrArea *sa, *big= NULL;
2395         int size, maxsize= 0, bwmaxsize= 0;
2396         short foundwin= 0;
2397         
2398         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
2399                 if(sa->winx > 10 && sa->winy > 10) {
2400                         size= sa->winx*sa->winy;
2401                         if(sa->spacetype == SPACE_BUTS) {
2402                                 if(foundwin == 0 && size > bwmaxsize) {
2403                                         bwmaxsize= size;
2404                                         big= sa;        
2405                                 }
2406                         }
2407                         else if(sa->spacetype != SPACE_IMAGE && size > maxsize) {
2408                                 maxsize= size;
2409                                 big= sa;
2410                                 foundwin= 1;
2411                         }
2412                 }
2413         }
2414                 
2415         return big;
2416 }
2417
2418 static ScrArea *biggest_area(void)
2419 {
2420         ScrArea *sa, *big= NULL;
2421         int size, maxsize= 0;
2422         
2423         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
2424                 size= sa->winx*sa->winy;
2425                 if(size > maxsize) {
2426                         maxsize= size;
2427                         big= sa;
2428                 }
2429         }
2430         return big;
2431 }
2432
2433
2434 /* if R_DISPLAYIMAGE
2435       use Image Window showing Render Result
2436           else: turn largest non-image area into Image Window (not to frustrate texture or composite usage)
2437           else: then we use Image Window anyway...
2438    if R_DISPSCREEN
2439       make a new temp fullscreen area with Image Window
2440 */
2441
2442 static ScrArea *find_area_showing_r_result(void)
2443 {
2444         ScrArea *sa;
2445         SpaceImage *sima;
2446         
2447         /* find an imagewindow showing render result */
2448         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
2449                 if(sa->spacetype==SPACE_IMAGE) {
2450                         sima= sa->spacedata.first;
2451                         if(sima->image && sima->image->type==IMA_TYPE_R_RESULT)
2452                                 break;
2453                 }
2454         }
2455         return sa;
2456 }
2457
2458 static ScrArea *imagewindow_set_render_display(void)
2459 {
2460         ScrArea *sa;
2461         SpaceImage *sima;
2462         
2463         sa= find_area_showing_r_result();
2464         
2465         if(sa==NULL) {
2466                 /* find largest open non-image area */
2467                 sa= biggest_non_image_area();
2468                 if(sa) {
2469                         newspace(sa, SPACE_IMAGE);
2470                         sima= sa->spacedata.first;
2471                         
2472                         /* makes ESC go back to prev space */
2473                         sima->flag |= SI_PREVSPACE;
2474                 }
2475                 else {
2476                         /* use any area of decent size */
2477                         sa= biggest_area();
2478                         if(sa->spacetype!=SPACE_IMAGE) {
2479                                 newspace(sa, SPACE_IMAGE);
2480                                 sima= sa->spacedata.first;
2481                                 
2482                                 /* makes ESC go back to prev space */
2483                                 sima->flag |= SI_PREVSPACE;
2484                         }
2485                 }
2486         }
2487         
2488         sima= sa->spacedata.first;
2489         
2490         /* get the correct image, and scale it */
2491         sima->image= BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
2492         
2493         if(G.displaymode==R_DISPLAYSCREEN) {
2494                 if(sa->full==0) {
2495                         sima->flag |= SI_FULLWINDOW;
2496                         /* fullscreen works with lousy curarea */
2497                         curarea= sa;
2498                         area_fullscreen();
2499                         sa= curarea;
2500                 }
2501         }
2502         
2503         return sa;
2504 }
2505
2506 static void imagewindow_init_display_cb(RenderResult *rr)
2507 {
2508         
2509         image_area= imagewindow_set_render_display();
2510         
2511         if(image_area) {
2512                 SpaceImage *sima= image_area->spacedata.first;
2513                 
2514                 areawinset(image_area->win);
2515                 
2516                 if(sima->info_str==NULL)
2517                         sima->info_str= MEM_callocN(RW_MAXTEXT, "info str imagewin");
2518                 
2519                 /* calc location using original size (tiles don't tell) */
2520                 sima->centx= (image_area->winx - sima->zoom*(float)rr->rectx)/2.0f;
2521                 sima->centy= (image_area->winy - sima->zoom*(float)rr->recty)/2.0f;
2522                 
2523                 sima->centx-= sima->zoom*sima->xof;
2524                 sima->centy-= sima->zoom*sima->yof;
2525                 
2526                 drawimagespace(image_area, sima);
2527                 if(image_area->headertype) scrarea_do_headdraw(image_area);
2528                 screen_swapbuffers();
2529                 
2530                 allqueue(REDRAWIMAGE, 0);       /* redraw in end */
2531         }
2532 }
2533
2534 /* coming from BIF_toggle_render_display() */
2535 void imagewindow_toggle_render(void)
2536 {
2537         ScrArea *sa;
2538         
2539         /* check if any imagewindow is showing temporal render output */
2540         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
2541                 if(sa->spacetype==SPACE_IMAGE) {
2542                         SpaceImage *sima= sa->spacedata.first;
2543                         
2544                         if(sima->image && sima->image->type==IMA_TYPE_R_RESULT)
2545                                 if(sima->flag & (SI_PREVSPACE|SI_FULLWINDOW))
2546                                         break;
2547                 }
2548         }
2549         if(sa) {
2550                 addqueue(sa->win, ESCKEY, 1);   /* also returns from fullscreen */
2551         }
2552         else {
2553                 sa= imagewindow_set_render_display();
2554                 scrarea_queue_headredraw(sa);
2555                 scrarea_queue_winredraw(sa);
2556         }
2557 }
2558
2559 /* NOTE: called while render, so no malloc allowed! */
2560 static void imagewindow_renderinfo_cb(RenderStats *rs)
2561 {
2562         
2563         if(image_area) {
2564                 SpaceImage *sima= image_area->spacedata.first;
2565                 
2566                 if(rs)
2567                         make_renderinfo_string(rs, sima->info_str);
2568
2569                 imagewindow_draw_renderinfo(image_area);
2570                 
2571                 /* no screen_swapbuffers, prevent any other window to draw */
2572                 myswapbuffers();
2573         }
2574 }
2575
2576 void imagewindow_render_callbacks(Render *re)
2577 {
2578         RE_display_init_cb(re, imagewindow_init_display_cb);
2579         RE_display_draw_cb(re, imagewindow_progress_display_cb);
2580         RE_display_clear_cb(re, imagewindow_clear_display_cb);
2581         RE_stats_draw_cb(re, imagewindow_renderinfo_cb);        
2582 }
2583
2584 void imagewin_store_spare(void)
2585 {
2586         ScrArea *sa= find_area_showing_r_result();
2587
2588         if(sa) {
2589                 ImBuf *ibuf;
2590                 SpaceImage *sima= sa->spacedata.first;
2591                 
2592                 if(sima->spare==NULL)
2593                         return;
2594                 
2595                 /* only store when it does not show spare */
2596                 if(sima->showspare==0)
2597                         return;
2598                 sima->showspare= 0;
2599                 
2600                 /* free spare */
2601                 IMB_freeImBuf(sima->spare);
2602                 
2603                 /* make a copy of render result */
2604                 ibuf= BKE_image_get_ibuf(sima->image, &sima->iuser);
2605                 sima->spare= IMB_dupImBuf(ibuf);
2606                 
2607                 if(sima->info_str)
2608                         BLI_strncpy(sima->info_spare, sima->info_str, RW_MAXTEXT);
2609
2610         }
2611 }
2612
2613 /* context: in current image window? */
2614 void imagewindow_swap_render_rects(void)
2615 {
2616         ScrArea *sa= find_area_showing_r_result();
2617                                         
2618         if(sa) {
2619                 SpaceImage *sima= sa->spacedata.first;
2620                 ImBuf *ibuf= BKE_image_get_ibuf(sima->image, &sima->iuser);
2621                 if(ibuf) {
2622                         
2623                         sima->showspare ^= 1;
2624                         
2625                         if(sima->spare==NULL)
2626                                 sima->spare= IMB_allocImBuf(ibuf->x, ibuf->y, 32, 0, 0);
2627                         if(sima->info_spare==NULL)
2628                                 sima->info_spare= MEM_callocN(RW_MAXTEXT, "info str imagewin");
2629                         
2630                         allqueue(REDRAWIMAGE, 0);
2631                 }
2632         }
2633 }
2634