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