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