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