Image Stamping patch by Diego (and peach request)- stamps image info into metadata...
[blender.git] / source / blender / src / drawview.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 //#define NAN_LINEAR_PHYSICS
34
35 #include <math.h>
36 #include <string.h>
37
38 #ifndef WIN32
39 #include <unistd.h>
40 #include <sys/times.h>
41 #else
42 #include <io.h>
43 #endif   
44
45 #ifdef WIN32
46 #ifndef snprintf
47 #define snprintf _snprintf
48 #endif
49 #endif
50
51 #include "MEM_guardedalloc.h"
52
53 #include "PIL_time.h"
54
55 #include "BMF_Api.h"
56
57 #include "IMB_imbuf_types.h"
58 #include "IMB_imbuf.h"
59
60 #include "DNA_action_types.h"
61 #include "DNA_armature_types.h"
62 #include "DNA_brush_types.h"
63 #include "DNA_camera_types.h"
64 #include "DNA_constraint_types.h"
65 #include "DNA_curve_types.h"
66 #include "DNA_group_types.h"
67 #include "DNA_image_types.h"
68 #include "DNA_key_types.h"
69 #include "DNA_lattice_types.h"
70 #include "DNA_mesh_types.h"
71 #include "DNA_meshdata_types.h"
72 #include "DNA_meta_types.h"
73 #include "DNA_object_types.h"
74 #include "DNA_screen_types.h"
75 #include "DNA_scene_types.h"
76 #include "DNA_space_types.h"
77 #include "DNA_texture_types.h"
78 #include "DNA_userdef_types.h"
79 #include "DNA_view3d_types.h"
80 #include "DNA_world_types.h"
81
82 #include "BLI_blenlib.h"
83 #include "BLI_arithb.h"
84 #include "BLI_editVert.h"
85
86 #include "BKE_action.h"
87 #include "BKE_armature.h"
88 #include "BKE_anim.h"
89 #include "BKE_constraint.h"
90 #include "BKE_curve.h"
91 #include "BKE_customdata.h"
92 #include "BKE_displist.h"
93 #include "BKE_depsgraph.h"
94 #include "BKE_DerivedMesh.h"
95 #include "BKE_global.h"
96 #include "BKE_lattice.h"
97 #include "BKE_library.h"
98 #include "BKE_image.h"
99 #include "BKE_ipo.h"
100 #include "BKE_key.h"
101 #include "BKE_main.h"
102 #include "BKE_mesh.h"
103 #include "BKE_object.h"
104 #include "BKE_scene.h"
105 #include "BKE_texture.h"
106 #include "BKE_utildefines.h"
107
108 #include "BIF_butspace.h"
109 #include "BIF_drawimage.h"
110 #include "BIF_editgroup.h"
111 #include "BIF_editarmature.h"
112 #include "BIF_editmesh.h"
113 #include "BIF_gl.h"
114 #include "BIF_glutil.h"
115 #include "BIF_interface.h"
116 #include "BIF_interface_icons.h"
117 #include "BIF_mywindow.h"
118 #include "BIF_poseobject.h"
119 #include "BIF_previewrender.h"
120 #include "BIF_resources.h"
121 #include "BIF_retopo.h"
122 #include "BIF_screen.h"
123 #include "BIF_space.h"
124
125 #ifdef WITH_VERSE
126 #include "BIF_verse.h"
127 #endif
128
129 #include "BDR_drawmesh.h"
130 #include "BDR_drawobject.h"
131 #include "BDR_editobject.h"
132 #include "BDR_vpaint.h"
133 #include "BDR_sculptmode.h"
134
135 #include "BSE_drawview.h"
136 #include "BSE_filesel.h"
137 #include "BSE_headerbuttons.h"
138 #include "BSE_seqaudio.h"
139 #include "BSE_sequence.h"
140 #include "BSE_trans_types.h"
141 #include "BSE_time.h"
142 #include "BSE_view.h"
143
144 #include "BPY_extern.h"
145
146 #include "RE_render_ext.h"
147
148 #include "blendef.h"
149 #include "mydevice.h"
150 #include "butspace.h"  // event codes
151
152 #include "BIF_transform.h"
153
154 #include "RE_pipeline.h"        // make_stars
155
156 #include "multires.h"
157
158 /* For MULTISAMPLE_ARB #define.
159    Note that older systems like irix 
160    may not have this, and will need a #ifdef
161    to disable it.*/
162 /* #include "GL/glext.h" Disabled for release, to avoid possibly breaking platforms.
163    Instead, the define we need will just be #defined if it's not in the platform opengl.h.
164 */
165
166 /* Modules used */
167 #include "radio.h"
168
169 /* locals */
170 void drawname(Object *ob);
171
172 static void star_stuff_init_func(void)
173 {
174         cpack(-1);
175         glPointSize(1.0);
176         glBegin(GL_POINTS);
177 }
178 static void star_stuff_vertex_func(float* i)
179 {
180         glVertex3fv(i);
181 }
182 static void star_stuff_term_func(void)
183 {
184         glEnd();
185 }
186
187 void default_gl_light(void)
188 {
189         int a;
190         
191         /* initialize */
192         if(U.light[0].flag==0 && U.light[1].flag==0 && U.light[2].flag==0) {
193                 U.light[0].flag= 1;
194                 U.light[0].vec[0]= -0.3; U.light[0].vec[1]= 0.3; U.light[0].vec[2]= 0.9;
195                 U.light[0].col[0]= 0.8; U.light[0].col[1]= 0.8; U.light[0].col[2]= 0.8;
196                 U.light[0].spec[0]= 0.5; U.light[0].spec[1]= 0.5; U.light[0].spec[2]= 0.5;
197                 U.light[0].spec[3]= 1.0;
198                 
199                 U.light[1].flag= 0;
200                 U.light[1].vec[0]= 0.5; U.light[1].vec[1]= 0.5; U.light[1].vec[2]= 0.1;
201                 U.light[1].col[0]= 0.4; U.light[1].col[1]= 0.4; U.light[1].col[2]= 0.8;
202                 U.light[1].spec[0]= 0.3; U.light[1].spec[1]= 0.3; U.light[1].spec[2]= 0.5;
203                 U.light[1].spec[3]= 1.0;
204         
205                 U.light[2].flag= 0;
206                 U.light[2].vec[0]= 0.3; U.light[2].vec[1]= -0.3; U.light[2].vec[2]= -0.2;
207                 U.light[2].col[0]= 0.8; U.light[2].col[1]= 0.5; U.light[2].col[2]= 0.4;
208                 U.light[2].spec[0]= 0.5; U.light[2].spec[1]= 0.4; U.light[2].spec[2]= 0.3;
209                 U.light[2].spec[3]= 1.0;
210         }
211         
212
213         glLightfv(GL_LIGHT0, GL_POSITION, U.light[0].vec); 
214         glLightfv(GL_LIGHT0, GL_DIFFUSE, U.light[0].col); 
215         glLightfv(GL_LIGHT0, GL_SPECULAR, U.light[0].spec); 
216
217         glLightfv(GL_LIGHT1, GL_POSITION, U.light[1].vec); 
218         glLightfv(GL_LIGHT1, GL_DIFFUSE, U.light[1].col); 
219         glLightfv(GL_LIGHT1, GL_SPECULAR, U.light[1].spec); 
220
221         glLightfv(GL_LIGHT2, GL_POSITION, U.light[2].vec); 
222         glLightfv(GL_LIGHT2, GL_DIFFUSE, U.light[2].col); 
223         glLightfv(GL_LIGHT2, GL_SPECULAR, U.light[2].spec); 
224
225         for(a=0; a<8; a++) {
226                 if(a<3) {
227                         if(U.light[a].flag) glEnable(GL_LIGHT0+a);
228                         else glDisable(GL_LIGHT0+a);
229                         
230                         // clear stuff from other opengl lamp usage
231                         glLightf(GL_LIGHT0+a, GL_SPOT_CUTOFF, 180.0);
232                         glLightf(GL_LIGHT0+a, GL_CONSTANT_ATTENUATION, 1.0);
233                         glLightf(GL_LIGHT0+a, GL_LINEAR_ATTENUATION, 0.0);
234                 }
235                 else glDisable(GL_LIGHT0+a);
236         }
237         
238         glDisable(GL_LIGHTING);
239
240         glDisable(GL_COLOR_MATERIAL);
241 }
242
243 /* also called when render 'ogl' */
244 void init_gl_stuff(void)        
245 {
246         float mat_ambient[] = { 0.0, 0.0, 0.0, 0.0 };
247         float mat_specular[] = { 0.5, 0.5, 0.5, 1.0 };
248         float mat_shininess[] = { 35.0 };
249         int a, x, y;
250         GLubyte pat[32*32];
251         const GLubyte *patc= pat;
252         
253         
254         glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient);
255         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_specular);
256         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
257         glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
258
259         default_gl_light();
260         
261         /* no local viewer, looks ugly in ortho mode */
262         /* glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, &one); */
263         
264         glDepthFunc(GL_LEQUAL);
265         /* scaling matrices */
266         glEnable(GL_NORMALIZE);
267
268         glShadeModel(GL_FLAT);
269
270         glDisable(GL_ALPHA_TEST);
271         glDisable(GL_BLEND);
272         glDisable(GL_DEPTH_TEST);
273         glDisable(GL_FOG);
274         glDisable(GL_LIGHTING);
275         glDisable(GL_LOGIC_OP);
276         glDisable(GL_STENCIL_TEST);
277         glDisable(GL_TEXTURE_1D);
278         glDisable(GL_TEXTURE_2D);
279
280         /* default on, disable/enable should be local per function */
281         glEnableClientState(GL_VERTEX_ARRAY);
282         glEnableClientState(GL_NORMAL_ARRAY);
283         
284         glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
285         glPixelTransferi(GL_RED_SCALE, 1);
286         glPixelTransferi(GL_RED_BIAS, 0);
287         glPixelTransferi(GL_GREEN_SCALE, 1);
288         glPixelTransferi(GL_GREEN_BIAS, 0);
289         glPixelTransferi(GL_BLUE_SCALE, 1);
290         glPixelTransferi(GL_BLUE_BIAS, 0);
291         glPixelTransferi(GL_ALPHA_SCALE, 1);
292         glPixelTransferi(GL_ALPHA_BIAS, 0);
293         
294         glPixelTransferi(GL_DEPTH_BIAS, 0);
295         glPixelTransferi(GL_DEPTH_SCALE, 1);
296         glDepthRange(0.0, 1.0);
297         
298         a= 0;
299         for(x=0; x<32; x++) {
300                 for(y=0; y<4; y++) {
301                         if( (x) & 1) pat[a++]= 0x88;
302                         else pat[a++]= 0x22;
303                 }
304         }
305         
306         glPolygonStipple(patc);
307
308
309         init_realtime_GL();     
310 }
311
312 void circf(float x, float y, float rad)
313 {
314         GLUquadricObj *qobj = gluNewQuadric(); 
315         
316         gluQuadricDrawStyle(qobj, GLU_FILL); 
317         
318         glPushMatrix(); 
319         
320         glTranslatef(x,  y, 0.); 
321         
322         gluDisk( qobj, 0.0,  rad, 32, 1); 
323         
324         glPopMatrix(); 
325         
326         gluDeleteQuadric(qobj);
327 }
328
329 void circ(float x, float y, float rad)
330 {
331         GLUquadricObj *qobj = gluNewQuadric(); 
332         
333         gluQuadricDrawStyle(qobj, GLU_SILHOUETTE); 
334         
335         glPushMatrix(); 
336         
337         glTranslatef(x,  y, 0.); 
338         
339         gluDisk( qobj, 0.0,  rad, 32, 1); 
340         
341         glPopMatrix(); 
342         
343         gluDeleteQuadric(qobj);
344 }
345
346 /* **********  ********** */
347
348 static void draw_bgpic(void)
349 {
350         BGpic *bgpic;
351         Image *ima;
352         ImBuf *ibuf= NULL;
353         float vec[4], fac, asp, zoomx, zoomy;
354         float x1, y1, x2, y2, cx, cy;
355         
356         bgpic= G.vd->bgpic;
357         if(bgpic==NULL) return;
358         
359         ima= bgpic->ima;
360         
361         if(ima)
362                 ibuf= BKE_image_get_ibuf(ima, &bgpic->iuser);
363         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL) ) 
364                 return;
365         if(ibuf->channels!=4)
366                 return;
367         if(ibuf->rect==NULL)
368                 IMB_rect_from_float(ibuf);
369         
370         if(G.vd->persp==2) {
371                 rctf vb;
372
373                 calc_viewborder(G.vd, &vb);
374
375                 x1= vb.xmin;
376                 y1= vb.ymin;
377                 x2= vb.xmax;
378                 y2= vb.ymax;
379         }
380         else {
381                 float sco[2];
382
383                 /* calc window coord */
384                 initgrabz(0.0, 0.0, 0.0);
385                 window_to_3d(vec, 1, 0);
386                 fac= MAX3( fabs(vec[0]), fabs(vec[1]), fabs(vec[1]) );
387                 fac= 1.0/fac;
388         
389                 asp= ( (float)ibuf->y)/(float)ibuf->x;
390
391                 vec[0] = vec[1] = vec[2] = 0.0;
392                 view3d_project_float(curarea, vec, sco, G.vd->persmat);
393                 cx = sco[0];
394                 cy = sco[1];
395         
396                 x1=  cx+ fac*(bgpic->xof-bgpic->size);
397                 y1=  cy+ asp*fac*(bgpic->yof-bgpic->size);
398                 x2=  cx+ fac*(bgpic->xof+bgpic->size);
399                 y2=  cy+ asp*fac*(bgpic->yof+bgpic->size);
400         }
401         
402         /* complete clip? */
403         
404         if(x2 < 0 ) return;
405         if(y2 < 0 ) return;
406         if(x1 > curarea->winx ) return;
407         if(y1 > curarea->winy ) return;
408         
409         zoomx= (x2-x1)/ibuf->x;
410         zoomy= (y2-y1)/ibuf->y;
411         
412         /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
413         if(zoomx < 1.0f || zoomy < 1.0f) {
414                 float tzoom= MIN2(zoomx, zoomy);
415                 int mip= 0;
416                 
417                 if(ibuf->mipmap[0]==NULL)
418                         IMB_makemipmap(ibuf, 0);
419                 
420                 while(tzoom < 1.0f && mip<8 && ibuf->mipmap[mip]) {
421                         tzoom*= 2.0f;
422                         zoomx*= 2.0f;
423                         zoomy*= 2.0f;
424                         mip++;
425                 }
426                 if(mip>0)
427                         ibuf= ibuf->mipmap[mip-1];
428         }
429         
430         if(G.vd->zbuf) glDisable(GL_DEPTH_TEST);
431
432         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
433          
434         glMatrixMode(GL_PROJECTION);
435         glPushMatrix();
436         glMatrixMode(GL_MODELVIEW);
437         glPushMatrix();
438         
439         glaDefine2DArea(&curarea->winrct);
440
441         glEnable(GL_BLEND);
442
443         glPixelZoom(zoomx, zoomy);
444         glColor4f(1.0, 1.0, 1.0, 1.0-bgpic->blend);
445         glaDrawPixelsTex(x1, y1, ibuf->x, ibuf->y, GL_UNSIGNED_BYTE, ibuf->rect);
446         
447         glPixelZoom(1.0, 1.0);
448         glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
449
450         glMatrixMode(GL_PROJECTION);
451         glPopMatrix();
452         glMatrixMode(GL_MODELVIEW);
453         glPopMatrix();
454         
455         glDisable(GL_BLEND);
456         if(G.vd->zbuf) glEnable(GL_DEPTH_TEST);
457         
458         areawinset(curarea->win);       // restore viewport / scissor
459 }
460
461 static void drawgrid_draw(float wx, float wy, float x, float y, float dx)
462 {
463         float fx, fy;
464         
465         x+= (wx); 
466         y+= (wy);
467         fx= x/dx;
468         fx= x-dx*floor(fx);
469         
470         while(fx< curarea->winx) {
471                 fdrawline(fx,  0.0,  fx,  (float)curarea->winy); 
472                 fx+= dx; 
473         }
474
475         fy= y/dx;
476         fy= y-dx*floor(fy);
477         
478
479         while(fy< curarea->winy) {
480                 fdrawline(0.0,  fy,  (float)curarea->winx,  fy); 
481                 fy+= dx;
482         }
483
484 }
485
486 // not intern, called in editobject for constraint axis too
487 void make_axis_color(char *col, char *col2, char axis)
488 {
489         if(axis=='x') {
490                 col2[0]= col[0]>219?255:col[0]+36;
491                 col2[1]= col[1]<26?0:col[1]-26;
492                 col2[2]= col[2]<26?0:col[2]-26;
493         }
494         else if(axis=='y') {
495                 col2[0]= col[0]<46?0:col[0]-36;
496                 col2[1]= col[1]>189?255:col[1]+66;
497                 col2[2]= col[2]<46?0:col[2]-36; 
498         }
499         else {
500                 col2[0]= col[0]<26?0:col[0]-26; 
501                 col2[1]= col[1]<26?0:col[1]-26; 
502                 col2[2]= col[2]>209?255:col[2]+46;
503         }
504         
505 }
506
507 static void drawgrid(void)
508 {
509         /* extern short bgpicmode; */
510         float wx, wy, x, y, fw, fx, fy, dx;
511         float vec4[4];
512         char col[3], col2[3];
513         short sublines = G.vd->gridsubdiv;
514         
515         vec4[0]=vec4[1]=vec4[2]=0.0; 
516         vec4[3]= 1.0;
517         Mat4MulVec4fl(G.vd->persmat, vec4);
518         fx= vec4[0]; 
519         fy= vec4[1]; 
520         fw= vec4[3];
521
522         wx= (curarea->winx/2.0);        /* because of rounding errors, grid at wrong location */
523         wy= (curarea->winy/2.0);
524
525         x= (wx)*fx/fw;
526         y= (wy)*fy/fw;
527
528         vec4[0]=vec4[1]=G.vd->grid; 
529         vec4[2]= 0.0;
530         vec4[3]= 1.0;
531         Mat4MulVec4fl(G.vd->persmat, vec4);
532         fx= vec4[0]; 
533         fy= vec4[1]; 
534         fw= vec4[3];
535
536         dx= fabs(x-(wx)*fx/fw);
537         if(dx==0) dx= fabs(y-(wy)*fy/fw);
538         
539         glDepthMask(0);         // disable write in zbuffer
540
541         /* check zoom out */
542         BIF_ThemeColor(TH_GRID);
543         persp(PERSP_WIN);
544         
545         if(dx<6.0) {
546                 G.vd->gridview*= sublines;
547                 dx*= sublines;
548                 
549                 if(dx<6.0) {    
550                         G.vd->gridview*= sublines;
551                         dx*= sublines;
552                         
553                         if(dx<6.0) {
554                                 G.vd->gridview*= sublines;
555                                 dx*=sublines;
556                                 if(dx<6.0);
557                                 else {
558                                         BIF_ThemeColor(TH_GRID);
559                                         drawgrid_draw(wx, wy, x, y, dx);
560                                 }
561                         }
562                         else {  // start blending out
563                                 BIF_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
564                                 drawgrid_draw(wx, wy, x, y, dx);
565                         
566                                 BIF_ThemeColor(TH_GRID);
567                                 drawgrid_draw(wx, wy, x, y, sublines*dx);
568                         }
569                 }
570                 else {  // start blending out (6 < dx < 60)
571                         BIF_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
572                         drawgrid_draw(wx, wy, x, y, dx);
573                         
574                         BIF_ThemeColor(TH_GRID);
575                         drawgrid_draw(wx, wy, x, y, sublines*dx);
576                 }
577         }
578         else {
579                 if(dx>60.0) {           // start blending in
580                         G.vd->gridview/= sublines;
581                         dx/= sublines;                  
582                         if(dx>60.0) {           // start blending in
583                                 G.vd->gridview/= sublines;
584                                 dx/= sublines;
585                                 if(dx>60.0) {
586                                         BIF_ThemeColor(TH_GRID);
587                                         drawgrid_draw(wx, wy, x, y, dx);
588                                 }
589                                 else {
590                                         BIF_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
591                                         drawgrid_draw(wx, wy, x, y, dx);
592                                         BIF_ThemeColor(TH_GRID);
593                                         drawgrid_draw(wx, wy, x, y, dx*sublines);
594                                 }
595                         }
596                         else {
597                                 BIF_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
598                                 drawgrid_draw(wx, wy, x, y, dx);
599                                 BIF_ThemeColor(TH_GRID);                                
600                                 drawgrid_draw(wx, wy, x, y, dx*sublines);
601                         }
602                 }
603                 else {
604                         BIF_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
605                         drawgrid_draw(wx, wy, x, y, dx);
606                         BIF_ThemeColor(TH_GRID);
607                         drawgrid_draw(wx, wy, x, y, dx*sublines);
608                 }
609         }
610
611         x+= (wx); 
612         y+= (wy);
613         BIF_GetThemeColor3ubv(TH_GRID, col);
614
615         setlinestyle(0);
616         
617         /* center cross */
618         if(G.vd->view==3) make_axis_color(col, col2, 'y');
619         else make_axis_color(col, col2, 'x');
620         glColor3ubv((GLubyte *)col2);
621         
622         fdrawline(0.0,  y,  (float)curarea->winx,  y); 
623         
624         if(G.vd->view==7) make_axis_color(col, col2, 'y');
625         else make_axis_color(col, col2, 'z');
626         glColor3ubv((GLubyte *)col2);
627
628         fdrawline(x, 0.0, x, (float)curarea->winy); 
629
630         glDepthMask(1);         // enable write in zbuffer
631         persp(PERSP_VIEW);
632 }
633
634
635
636 static void drawfloor(void)
637 {
638         View3D *vd;
639         float vert[3], grid;
640         int a, gridlines, emphasise;
641         char col[3], col2[3];
642         short draw_line = 0;
643                 
644         vd= curarea->spacedata.first;
645
646         vert[2]= 0.0;
647
648         if(vd->gridlines<3) return;
649         
650         if(G.vd->zbuf && G.obedit) glDepthMask(0);      // for zbuffer-select
651         
652         gridlines= vd->gridlines/2;
653         grid= gridlines*vd->grid;
654         
655         BIF_GetThemeColor3ubv(TH_GRID, col);
656         BIF_GetThemeColor3ubv(TH_BACK, col2);
657         
658         /* emphasise division lines lighter instead of darker, if background is darker than grid */
659         if ( ((col[0]+col[1]+col[2])/3+10) > (col2[0]+col2[1]+col2[2])/3 )
660                 emphasise = 20;
661         else
662                 emphasise = -10;
663         
664         /* draw the Y axis and/or grid lines */
665         for(a= -gridlines;a<=gridlines;a++) {
666                 if(a==0) {
667                         /* check for the 'show Y axis' preference */
668                         if (vd->gridflag & V3D_SHOW_Y) { 
669                                 make_axis_color(col, col2, 'y');
670                                 glColor3ubv((GLubyte *)col2);
671                                 
672                                 draw_line = 1;
673                         } else if (vd->gridflag & V3D_SHOW_FLOOR) {
674                                 BIF_ThemeColorShade(TH_GRID, emphasise);
675                         } else {
676                                 draw_line = 0;
677                         }
678                 } else {
679                         /* check for the 'show grid floor' preference */
680                         if (vd->gridflag & V3D_SHOW_FLOOR) {
681                                 if( (a % 10)==0) {
682                                         BIF_ThemeColorShade(TH_GRID, emphasise);
683                                 }
684                                 else BIF_ThemeColorShade(TH_GRID, 10);
685                                 
686                                 draw_line = 1;
687                         } else {
688                                 draw_line = 0;
689                         }
690                 }
691                 
692                 if (draw_line) {
693                         glBegin(GL_LINE_STRIP);
694                 vert[0]= a*vd->grid;
695                 vert[1]= grid;
696                 glVertex3fv(vert);
697                 vert[1]= -grid;
698                 glVertex3fv(vert);
699                         glEnd();
700                 }
701         }
702         
703         /* draw the X axis and/or grid lines */
704         for(a= -gridlines;a<=gridlines;a++) {
705                 if(a==0) {
706                         /* check for the 'show X axis' preference */
707                         if (vd->gridflag & V3D_SHOW_X) { 
708                                 make_axis_color(col, col2, 'x');
709                                 glColor3ubv((GLubyte *)col2);
710                                 
711                                 draw_line = 1;
712                         } else if (vd->gridflag & V3D_SHOW_FLOOR) {
713                                 BIF_ThemeColorShade(TH_GRID, emphasise);
714                         } else {
715                                 draw_line = 0;
716                         }
717                 } else {
718                         /* check for the 'show grid floor' preference */
719                         if (vd->gridflag & V3D_SHOW_FLOOR) {
720                                 if( (a % 10)==0) {
721                                         BIF_ThemeColorShade(TH_GRID, emphasise);
722                                 }
723                                 else BIF_ThemeColorShade(TH_GRID, 10);
724                                 
725                                 draw_line = 1;
726                         } else {
727                                 draw_line = 0;
728                         }
729                 }
730                 
731                 if (draw_line) {
732                         glBegin(GL_LINE_STRIP);
733                 vert[1]= a*vd->grid;
734                 vert[0]= grid;
735                 glVertex3fv(vert );
736                 vert[0]= -grid;
737                 glVertex3fv(vert);
738                         glEnd();
739                 }
740         }
741         
742         /* draw the Z axis line */      
743         /* check for the 'show Z axis' preference */
744         if (vd->gridflag & V3D_SHOW_Z) {
745                 make_axis_color(col, col2, 'z');
746                 glColor3ubv((GLubyte *)col2);
747                 
748                 glBegin(GL_LINE_STRIP);
749                 vert[0]= 0;
750                 vert[1]= 0;
751                 vert[2]= grid;
752                 glVertex3fv(vert );
753                 vert[2]= -grid;
754                 glVertex3fv(vert);
755                 glEnd();
756         }
757
758         if(G.vd->zbuf && G.obedit) glDepthMask(1);      
759
760 }
761
762 static void drawcursor(View3D *v3d)
763 {
764         short mx,my,co[2];
765         int flag;
766         
767         /* we dont want the clipping for cursor */
768         flag= v3d->flag;
769         v3d->flag= 0;
770         project_short( give_cursor(), co);
771         v3d->flag= flag;
772         
773         mx = co[0];
774         my = co[1];
775
776         if(mx!=IS_CLIPPED) {
777                 setlinestyle(0); 
778                 cpack(0xFF);
779                 circ((float)mx, (float)my, 10.0);
780                 setlinestyle(4); 
781                 cpack(0xFFFFFF);
782                 circ((float)mx, (float)my, 10.0);
783                 setlinestyle(0);
784                 cpack(0x0);
785                 
786                 sdrawline(mx-20, my, mx-5, my);
787                 sdrawline(mx+5, my, mx+20, my);
788                 sdrawline(mx, my-20, mx, my-5);
789                 sdrawline(mx, my+5, mx, my+20);
790         }
791 }
792
793 /* ********* custom clipping *********** */
794
795 static void view3d_draw_clipping(View3D *v3d)
796 {
797         BoundBox *bb= v3d->clipbb;
798         
799         BIF_ThemeColorShade(TH_BACK, -8);
800         
801         glBegin(GL_QUADS);
802
803         glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[1]); glVertex3fv(bb->vec[2]); glVertex3fv(bb->vec[3]);
804         glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[5]); glVertex3fv(bb->vec[1]);
805         glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[6]); glVertex3fv(bb->vec[5]);
806         glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[3]); glVertex3fv(bb->vec[2]); glVertex3fv(bb->vec[6]);
807         glVertex3fv(bb->vec[1]); glVertex3fv(bb->vec[5]); glVertex3fv(bb->vec[6]); glVertex3fv(bb->vec[2]);
808         glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[3]);
809         
810         glEnd();
811 }
812
813 void view3d_set_clipping(View3D *v3d)
814 {
815         double plane[4];
816         int a;
817         
818         for(a=0; a<4; a++) {
819                 QUATCOPY(plane, v3d->clip[a]);
820                 glClipPlane(GL_CLIP_PLANE0+a, plane);
821                 glEnable(GL_CLIP_PLANE0+a);
822         }
823 }
824
825 void view3d_clr_clipping(void)
826 {
827         int a;
828         
829         for(a=0; a<4; a++) {
830                 glDisable(GL_CLIP_PLANE0+a);
831         }
832 }
833
834 int view3d_test_clipping(View3D *v3d, float *vec)
835 {
836         /* vec in world coordinates, returns 1 if clipped */
837         float view[3];
838         
839         VECCOPY(view, vec);
840         
841         if(0.0f < v3d->clip[0][3] + INPR(view, v3d->clip[0]))
842                 if(0.0f < v3d->clip[1][3] + INPR(view, v3d->clip[1]))
843                         if(0.0f < v3d->clip[2][3] + INPR(view, v3d->clip[2]))
844                                 if(0.0f < v3d->clip[3][3] + INPR(view, v3d->clip[3]))
845                                         return 0;
846
847         return 1;
848 }
849
850 /* ********* end custom clipping *********** */
851
852 static void view3d_get_viewborder_size(View3D *v3d, float size_r[2])
853 {
854         float winmax= MAX2(v3d->area->winx, v3d->area->winy);
855         float aspect= (float) (G.scene->r.xsch*G.scene->r.xasp)/(G.scene->r.ysch*G.scene->r.yasp);
856
857         if(aspect>1.0) {
858                 size_r[0]= winmax;
859                 size_r[1]= winmax/aspect;
860         } else {
861                 size_r[0]= winmax*aspect;
862                 size_r[1]= winmax;
863         }
864 }
865
866 void calc_viewborder(struct View3D *v3d, rctf *viewborder_r)
867 {
868         float zoomfac, size[2];
869         float dx= 0.0f, dy= 0.0f;
870         
871         view3d_get_viewborder_size(v3d, size);
872
873                 /* magic zoom calculation, no idea what
874              * it signifies, if you find out, tell me! -zr
875                  */
876         /* simple, its magic dude!
877          * well, to be honest, this gives a natural feeling zooming
878          * with multiple keypad presses (ton)
879          */
880         
881         zoomfac= (M_SQRT2 + v3d->camzoom/50.0);
882         zoomfac= (zoomfac*zoomfac)*0.25;
883         
884         size[0]= size[0]*zoomfac;
885         size[1]= size[1]*zoomfac;
886
887                 /* center in window */
888         viewborder_r->xmin= 0.5*v3d->area->winx - 0.5*size[0];
889         viewborder_r->ymin= 0.5*v3d->area->winy - 0.5*size[1];
890         viewborder_r->xmax= viewborder_r->xmin + size[0];
891         viewborder_r->ymax= viewborder_r->ymin + size[1];
892         
893         dx= v3d->area->winx*G.vd->camdx*zoomfac*2.0f;
894         dy= v3d->area->winy*G.vd->camdy*zoomfac*2.0f;
895         
896         /* apply offset */
897         viewborder_r->xmin-= dx;
898         viewborder_r->ymin-= dy;
899         viewborder_r->xmax-= dx;
900         viewborder_r->ymax-= dy;
901         
902         if(v3d->camera && v3d->camera->type==OB_CAMERA) {
903                 Camera *cam= v3d->camera->data;
904                 float w = viewborder_r->xmax - viewborder_r->xmin;
905                 float h = viewborder_r->ymax - viewborder_r->ymin;
906                 float side = MAX2(w, h);
907
908                 viewborder_r->xmin+= cam->shiftx*side;
909                 viewborder_r->xmax+= cam->shiftx*side;
910                 viewborder_r->ymin+= cam->shifty*side;
911                 viewborder_r->ymax+= cam->shifty*side;
912         }
913 }
914
915 void view3d_set_1_to_1_viewborder(View3D *v3d)
916 {
917         float size[2];
918         int im_width= (G.scene->r.size*G.scene->r.xsch)/100;
919
920         view3d_get_viewborder_size(v3d, size);
921
922         v3d->camzoom= (sqrt(4.0*im_width/size[0]) - M_SQRT2)*50.0;
923         v3d->camzoom= CLAMPIS(v3d->camzoom, -30, 300);
924 }
925
926
927 static void drawviewborder_flymode(void)        
928 {
929         /* draws 4 edge brackets that frame the safe area where the
930         mouse can move during fly mode without spinning the view */
931         float x1, x2, y1, y2;
932         
933         x1= 0.45*(float)curarea->winx;
934         y1= 0.45*(float)curarea->winy;
935         x2= 0.55*(float)curarea->winx;
936         y2= 0.55*(float)curarea->winy;
937         cpack(0);
938         
939         
940         glBegin(GL_LINES);
941         /* bottom left */
942         glVertex2f(x1,y1); 
943         glVertex2f(x1,y1+5);
944         
945         glVertex2f(x1,y1); 
946         glVertex2f(x1+5,y1);
947
948         /* top right */
949         glVertex2f(x2,y2); 
950         glVertex2f(x2,y2-5);
951         
952         glVertex2f(x2,y2); 
953         glVertex2f(x2-5,y2);
954         
955         /* top left */
956         glVertex2f(x1,y2); 
957         glVertex2f(x1,y2-5);
958         
959         glVertex2f(x1,y2); 
960         glVertex2f(x1+5,y2);
961         
962         /* bottom right */
963         glVertex2f(x2,y1); 
964         glVertex2f(x2,y1+5);
965         
966         glVertex2f(x2,y1); 
967         glVertex2f(x2-5,y1);
968         glEnd();        
969 }
970
971
972 static void drawviewborder(void)
973 {
974         extern void gl_round_box(int mode, float minx, float miny, float maxx, float maxy, float rad);          // interface_panel.c
975         float fac, a;
976         float x1, x2, y1, y2;
977         float x3, y3, x4, y4;
978         rctf viewborder;
979         Camera *ca= NULL;
980
981         if(G.vd->camera==NULL)
982                 return;
983         if(G.vd->camera->type==OB_CAMERA)
984                 ca = G.vd->camera->data;
985         
986         calc_viewborder(G.vd, &viewborder);
987         x1= viewborder.xmin;
988         y1= viewborder.ymin;
989         x2= viewborder.xmax;
990         y2= viewborder.ymax;
991
992         /* passepartout, specified in camera edit buttons */
993         if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001) {
994                 if (ca->passepartalpha == 1.0) {
995                         glColor3f(0, 0, 0);
996                 } else {
997                         glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
998                         glEnable(GL_BLEND);
999                         glColor4f(0, 0, 0, ca->passepartalpha);
1000                 }
1001                 if (x1 > 0.0)
1002                         glRectf(0.0, (float)curarea->winy, x1, 0.0);
1003                 if (x2 < (float)curarea->winx)
1004                         glRectf(x2, (float)curarea->winy, (float)curarea->winx, 0.0);
1005                 if (y2 < (float)curarea->winy)
1006                         glRectf(x1, (float)curarea->winy, x2, y2);
1007                 if (y2 > 0.0) 
1008                         glRectf(x1, y1, x2, 0.0);
1009
1010                 glDisable(GL_BLEND);
1011         }
1012         
1013         /* edge */
1014         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); 
1015         
1016         setlinestyle(0);
1017         BIF_ThemeColor(TH_BACK);
1018         glRectf(x1, y1, x2, y2);
1019         
1020         setlinestyle(3);
1021         BIF_ThemeColor(TH_WIRE);
1022         glRectf(x1, y1, x2, y2);
1023                 
1024         /* camera name - draw in highlighted text color */
1025         if (ca && (ca->flag & CAM_SHOWNAME)) {
1026                 BIF_ThemeColor(TH_TEXT_HI);
1027                 glRasterPos2f(x1, y1-15);
1028                 
1029                 BMF_DrawString(G.font, G.vd->camera->id.name+2);
1030                 BIF_ThemeColor(TH_WIRE);
1031         }
1032
1033
1034         /* border */
1035         if(G.scene->r.mode & R_BORDER) {
1036                 
1037                 cpack(0);
1038                 x3= x1+ G.scene->r.border.xmin*(x2-x1);
1039                 y3= y1+ G.scene->r.border.ymin*(y2-y1);
1040                 x4= x1+ G.scene->r.border.xmax*(x2-x1);
1041                 y4= y1+ G.scene->r.border.ymax*(y2-y1);
1042                 
1043                 cpack(0x4040FF);
1044                 glRectf(x3,  y3,  x4,  y4); 
1045         }
1046
1047         /* safety border */
1048         if (ca && (ca->flag & CAM_SHOWTITLESAFE)) {
1049                 fac= 0.1;
1050                 
1051                 a= fac*(x2-x1);
1052                 x1+= a; 
1053                 x2-= a;
1054         
1055                 a= fac*(y2-y1);
1056                 y1+= a;
1057                 y2-= a;
1058         
1059                 BIF_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1060                 
1061                 uiSetRoundBox(15);
1062                 gl_round_box(GL_LINE_LOOP, x1, y1, x2, y2, 12.0);
1063         }
1064         
1065         setlinestyle(0);
1066         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1067
1068 }
1069
1070 void backdrawview3d(int test)
1071 {
1072         struct Base *base;
1073
1074 /*for 2.43 release, don't use glext and just define the constant.
1075   this to avoid possibly breaking platforms before release.*/
1076 #ifndef GL_MULTISAMPLE_ARB
1077         #define GL_MULTISAMPLE_ARB      0x809D
1078 #endif
1079
1080 #ifdef GL_MULTISAMPLE_ARB
1081         int m;
1082 #endif
1083
1084         if(G.f & G_VERTEXPAINT || G.f & G_WEIGHTPAINT || G.f & G_TEXTUREPAINT);
1085         else if(G.obedit && G.vd->drawtype>OB_WIRE && (G.vd->flag & V3D_ZBUF_SELECT));
1086         else {
1087                 G.vd->flag &= ~V3D_NEEDBACKBUFDRAW;
1088                 return;
1089         }
1090
1091         if( !(G.vd->flag & V3D_NEEDBACKBUFDRAW) ) return;
1092
1093         if(test) {
1094                 if(qtest()) {
1095                         addafterqueue(curarea->win, BACKBUFDRAW, 1);
1096                         return;
1097                 }
1098         }
1099         persp(PERSP_VIEW);
1100
1101         /*Disable FSAA for backbuffer selection.  
1102         
1103         Only works if GL_MULTISAMPLE_ARB is defined by the header
1104         file, which is should be for every OS that supports FSAA.*/
1105
1106 #ifdef GL_MULTISAMPLE_ARB
1107         m = glIsEnabled(GL_MULTISAMPLE_ARB);
1108         if (m) glDisable(GL_MULTISAMPLE_ARB);
1109 #endif
1110
1111 #ifdef __APPLE__
1112         glDrawBuffer(GL_AUX0);
1113 #endif  
1114         if(G.vd->drawtype > OB_WIRE) G.vd->zbuf= TRUE;
1115         curarea->win_swap &= ~WIN_BACK_OK;
1116         
1117         glDisable(GL_DITHER);
1118
1119         glClearColor(0.0, 0.0, 0.0, 0.0); 
1120         if(G.vd->zbuf) {
1121                 glEnable(GL_DEPTH_TEST);
1122                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1123         }
1124         else {
1125                 glClear(GL_COLOR_BUFFER_BIT);
1126                 glDisable(GL_DEPTH_TEST);
1127         }
1128         
1129         if(G.vd->flag & V3D_CLIPPING)
1130                 view3d_set_clipping(G.vd);
1131         
1132         G.f |= G_BACKBUFSEL;
1133         
1134         base= (G.scene->basact);
1135         if(base && (base->lay & G.vd->lay)) {
1136                 draw_object_backbufsel(base->object);
1137         }
1138
1139         G.vd->flag &= ~V3D_NEEDBACKBUFDRAW;
1140
1141         G.f &= ~G_BACKBUFSEL;
1142         G.vd->zbuf= FALSE; 
1143         glDisable(GL_DEPTH_TEST);
1144         glEnable(GL_DITHER);
1145
1146 #ifdef __APPLE__
1147         glDrawBuffer(GL_BACK); /* we were in aux buffers */
1148 #endif
1149
1150         if(G.vd->flag & V3D_CLIPPING)
1151                 view3d_clr_clipping();
1152
1153 #ifdef GL_MULTISAMPLE_ARB
1154         if (m) glEnable(GL_MULTISAMPLE_ARB);
1155 #endif
1156
1157         /* it is important to end a view in a transform compatible with buttons */
1158         persp(PERSP_WIN);  // set ortho
1159         bwin_scalematrix(curarea->win, G.vd->blockscale, G.vd->blockscale, G.vd->blockscale);
1160
1161 }
1162
1163 void check_backbuf(void)
1164 {
1165         if(G.vd->flag & V3D_NEEDBACKBUFDRAW)
1166                 backdrawview3d(0);
1167 }
1168
1169 /* samples a single pixel (copied from vpaint) */
1170 unsigned int sample_backbuf(int x, int y)
1171 {
1172         unsigned int col;
1173         
1174         if(x>=curarea->winx || y>=curarea->winy) return 0;
1175         x+= curarea->winrct.xmin;
1176         y+= curarea->winrct.ymin;
1177         
1178         check_backbuf(); // actually not needed for apple
1179
1180 #ifdef __APPLE__
1181         glReadBuffer(GL_AUX0);
1182 #endif
1183         glReadPixels(x,  y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,  &col);
1184         glReadBuffer(GL_BACK);  
1185         
1186         if(G.order==B_ENDIAN) SWITCH_INT(col);
1187         
1188         return framebuffer_to_index(col);
1189 }
1190
1191 /* reads full rect, converts indices */
1192 ImBuf *read_backbuf(short xmin, short ymin, short xmax, short ymax)
1193 {
1194         unsigned int *dr, *rd;
1195         struct ImBuf *ibuf, *ibuf1;
1196         int a;
1197         short xminc, yminc, xmaxc, ymaxc, xs, ys;
1198         
1199         /* clip */
1200         if(xmin<0) xminc= 0; else xminc= xmin;
1201         if(xmax>=curarea->winx) xmaxc= curarea->winx-1; else xmaxc= xmax;
1202         if(xminc > xmaxc) return NULL;
1203
1204         if(ymin<0) yminc= 0; else yminc= ymin;
1205         if(ymax>=curarea->winy) ymaxc= curarea->winy-1; else ymaxc= ymax;
1206         if(yminc > ymaxc) return NULL;
1207         
1208         ibuf= IMB_allocImBuf((xmaxc-xminc+1), (ymaxc-yminc+1), 32, IB_rect,0);
1209
1210         check_backbuf(); // actually not needed for apple
1211         
1212 #ifdef __APPLE__
1213         glReadBuffer(GL_AUX0);
1214 #endif
1215         glReadPixels(curarea->winrct.xmin+xminc, curarea->winrct.ymin+yminc, (xmaxc-xminc+1), (ymaxc-yminc+1), GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1216         glReadBuffer(GL_BACK);  
1217
1218         if(G.order==B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
1219
1220         a= (xmaxc-xminc+1)*(ymaxc-yminc+1);
1221         dr= ibuf->rect;
1222         while(a--) {
1223                 if(*dr) *dr= framebuffer_to_index(*dr);
1224                 dr++;
1225         }
1226         
1227         /* put clipped result back, if needed */
1228         if(xminc==xmin && xmaxc==xmax && yminc==ymin && ymaxc==ymax) 
1229                 return ibuf;
1230         
1231         ibuf1= IMB_allocImBuf( (xmax-xmin+1),(ymax-ymin+1),32,IB_rect,0);
1232         rd= ibuf->rect;
1233         dr= ibuf1->rect;
1234                 
1235         for(ys= ymin; ys<=ymax; ys++) {
1236                 for(xs= xmin; xs<=xmax; xs++, dr++) {
1237                         if( xs>=xminc && xs<=xmaxc && ys>=yminc && ys<=ymaxc) {
1238                                 *dr= *rd;
1239                                 rd++;
1240                         }
1241                 }
1242         }
1243         IMB_freeImBuf(ibuf);
1244         return ibuf1;
1245 }
1246
1247 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
1248 unsigned int sample_backbuf_rect(short mval[2], int size, unsigned int min, unsigned int max, int *dist, short strict, unsigned int (*indextest)(unsigned int index))
1249 {
1250         struct ImBuf *buf;
1251         unsigned int *bufmin, *bufmax, *tbuf;
1252         int minx, miny;
1253         int a, b, rc, nr, amount, dirvec[4][2];
1254         int distance=0;
1255         unsigned int index = 0;
1256         short indexok = 0;      
1257
1258         amount= (size-1)/2;
1259
1260         minx = mval[0]-(amount+1);
1261         miny = mval[1]-(amount+1);
1262         buf = read_backbuf(minx, miny, minx+size-1, miny+size-1);
1263         if (!buf) return 0;
1264
1265         rc= 0;
1266         
1267         dirvec[0][0]= 1; dirvec[0][1]= 0;
1268         dirvec[1][0]= 0; dirvec[1][1]= -size;
1269         dirvec[2][0]= -1; dirvec[2][1]= 0;
1270         dirvec[3][0]= 0; dirvec[3][1]= size;
1271         
1272         bufmin = buf->rect;
1273         tbuf = buf->rect;
1274         bufmax = buf->rect + size*size;
1275         tbuf+= amount*size+ amount;
1276         
1277         for(nr=1; nr<=size; nr++) {
1278                 
1279                 for(a=0; a<2; a++) {
1280                         for(b=0; b<nr; b++, distance++) {
1281                                 if (*tbuf && *tbuf>=min && *tbuf<max) { //we got a hit
1282                                         if(strict){
1283                                                 indexok =  indextest(*tbuf - min+1);
1284                                                 if(indexok){
1285                                                         *dist= (short) sqrt( (float)distance   );
1286                                                         index = *tbuf - min+1;
1287                                                         goto exit; 
1288                                                 }                                               
1289                                         }
1290                                         else{
1291                                                 *dist= (short) sqrt( (float)distance ); // XXX, this distance is wrong - 
1292                                                 index = *tbuf - min+1; // messy yah, but indices start at 1
1293                                                 goto exit;
1294                                         }                       
1295                                 }
1296                                 
1297                                 tbuf+= (dirvec[rc][0]+dirvec[rc][1]);
1298                                 
1299                                 if(tbuf<bufmin || tbuf>=bufmax) {
1300                                         goto exit;
1301                                 }
1302                         }
1303                         rc++;
1304                         rc &= 3;
1305                 }
1306         }
1307
1308 exit:
1309         IMB_freeImBuf(buf);
1310         return index;
1311 }
1312
1313 void drawname(Object *ob)
1314 {
1315         cpack(0x404040);
1316         glRasterPos3f(0.0,  0.0,  0.0);
1317         
1318         BMF_DrawString(G.font, " ");
1319         BMF_DrawString(G.font, ob->id.name+2);
1320 }
1321
1322
1323 static void draw_selected_name(Object *ob)
1324 {
1325         char info[128];
1326         short offset=30;
1327
1328         if(ob->type==OB_ARMATURE) {
1329                 bArmature *arm= ob->data;
1330                 char *name= NULL;
1331                 
1332                 if(ob==G.obedit) {
1333                         EditBone *ebo;
1334                         for (ebo=G.edbo.first; ebo; ebo=ebo->next){
1335                                 if ((ebo->flag & BONE_ACTIVE) && (ebo->layer & arm->layer)) {
1336                                         name= ebo->name;
1337                                         break;
1338                                 }
1339                         }
1340                 }
1341                 else if(ob->pose && (ob->flag & OB_POSEMODE)) {
1342                         bPoseChannel *pchan;
1343                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1344                                 if((pchan->bone->flag & BONE_ACTIVE) && (pchan->bone->layer & arm->layer)) {
1345                                         name= pchan->name;
1346                                         break;
1347                                 }
1348                         }
1349                 }
1350                 if(name)
1351                         sprintf(info, "(%d) %s %s", CFRA, ob->id.name+2, name);
1352                 else
1353                         sprintf(info, "(%d) %s", CFRA, ob->id.name+2);
1354         }
1355         else if(ob->type==OB_MESH) {
1356                 Key *key= NULL;
1357                 KeyBlock *kb = NULL;
1358                 char shapes[75];
1359                 
1360                 shapes[0] = 0;
1361                 key = ob_get_key(ob);
1362                 if(key){
1363                         kb = BLI_findlink(&key->block, ob->shapenr-1);
1364                         if(kb){
1365                                 sprintf(shapes, ": %s ", kb->name);             
1366                                 if(ob->shapeflag == OB_SHAPE_LOCK){
1367                                         sprintf(shapes, "%s (Pinned)",shapes);
1368                                 }
1369                         }
1370                 }
1371                 sprintf(info, "(%d) %s %s", CFRA, ob->id.name+2, shapes);
1372         }
1373         else sprintf(info, "(%d) %s", CFRA, ob->id.name+2);
1374
1375         BIF_ThemeColor(TH_TEXT_HI);
1376         if (U.uiflag & USER_SHOW_ROTVIEWICON)
1377                 offset = 14 + (U.rvisize * 2);
1378
1379         glRasterPos2i(offset,  10);
1380         BMF_DrawString(G.fonts, info);
1381 }
1382
1383
1384 /* Draw a live substitute of the view icon, which is always shown */
1385 static void draw_view_axis(void)
1386 {
1387         const float k = U.rvisize;   /* axis size */
1388         const float toll = 0.5;      /* used to see when view is quasi-orthogonal */
1389         const float start = k + 1.0; /* axis center in screen coordinates, x=y */
1390         float ydisp = 0.0;          /* vertical displacement to allow obj info text */
1391         
1392         /* rvibright ranges approx. from original axis icon color to gizmo color */
1393         float bright = U.rvibright / 15.0f;
1394         
1395         unsigned char col[3];
1396         unsigned char gridcol[3];
1397         float colf[3];
1398         
1399         float vec[4];
1400         float dx, dy;
1401         float h, s, v;
1402         
1403         BIF_GetThemeColor3ubv(TH_GRID, (char *)gridcol);
1404         
1405         /* X */
1406         vec[0] = vec[3] = 1;
1407         vec[1] = vec[2] = 0;
1408         QuatMulVecf(G.vd->viewquat, vec);
1409         
1410         make_axis_color((char *)gridcol, (char *)col, 'x');
1411         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
1412         s = s<0.5 ? s+0.5 : 1.0;
1413         v = 0.3;
1414         v = (v<1.0-(bright) ? v+bright : 1.0);
1415         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
1416         glColor3fv(colf);
1417         
1418         dx = vec[0] * k;
1419         dy = vec[1] * k;
1420         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
1421         if (fabs(dx) > toll || fabs(dy) > toll) {
1422                 glRasterPos2i(start + dx + 2, start + dy + ydisp + 2);
1423                 BMF_DrawString(G.fonts, "x");
1424         }
1425         
1426         /* Y */
1427         vec[1] = vec[3] = 1;
1428         vec[0] = vec[2] = 0;
1429         QuatMulVecf(G.vd->viewquat, vec);
1430         
1431         make_axis_color((char *)gridcol, (char *)col, 'y');
1432         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
1433         s = s<0.5 ? s+0.5 : 1.0;
1434         v = 0.3;
1435         v = (v<1.0-(bright) ? v+bright : 1.0);
1436         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
1437         glColor3fv(colf);
1438         
1439         dx = vec[0] * k;
1440         dy = vec[1] * k;
1441         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
1442         if (fabs(dx) > toll || fabs(dy) > toll) {
1443                 glRasterPos2i(start + dx + 2, start + dy + ydisp + 2);
1444                 BMF_DrawString(G.fonts, "y");
1445         }
1446         
1447         /* Z */
1448         vec[2] = vec[3] = 1;
1449         vec[1] = vec[0] = 0;
1450         QuatMulVecf(G.vd->viewquat, vec);
1451         
1452         make_axis_color((char *)gridcol, (char *)col, 'z');
1453         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
1454         s = s<0.5 ? s+0.5 : 1.0;
1455         v = 0.5;
1456         v = (v<1.0-(bright) ? v+bright : 1.0);
1457         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
1458         glColor3fv(colf);
1459         
1460         dx = vec[0] * k;
1461         dy = vec[1] * k;
1462         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
1463         if (fabs(dx) > toll || fabs(dy) > toll) {
1464                 glRasterPos2i(start + dx + 2, start + dy + ydisp + 2);
1465                 BMF_DrawString(G.fonts, "z");
1466         }
1467 }
1468
1469         
1470 static void draw_view_icon(void)
1471 {
1472         BIFIconID icon;
1473         
1474         if(G.vd->view==7) icon= ICON_AXIS_TOP;
1475         else if(G.vd->view==1) icon= ICON_AXIS_FRONT;
1476         else if(G.vd->view==3) icon= ICON_AXIS_SIDE;
1477         else return ;
1478
1479         glEnable(GL_BLEND);
1480         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
1481         
1482         BIF_icon_draw(5.0, 5.0, icon);
1483         
1484         glDisable(GL_BLEND);
1485 }
1486
1487 static void draw_viewport_name(ScrArea *sa)
1488 {
1489         char *name = NULL;
1490         char *printable = NULL;
1491         
1492         switch(G.vd->view) {
1493                 case 1:
1494                         if (G.vd->persp & V3D_PERSP_DO_3D_PERSP)
1495                                 name = (G.vd->flag2 & V3D_OPP_DIRECTION_NAME) ? "Back Persp" : "Front Persp";
1496                         else
1497                                 name = (G.vd->flag2 & V3D_OPP_DIRECTION_NAME) ? "Back Ortho" : "Front Ortho";
1498                         break;
1499                 case 3:
1500                         if (G.vd->persp & V3D_PERSP_DO_3D_PERSP)
1501                                 name = (G.vd->flag2 & V3D_OPP_DIRECTION_NAME) ? "Left Persp" : "Right Persp";
1502                         else
1503                                 name = (G.vd->flag2 & V3D_OPP_DIRECTION_NAME) ? "Left Ortho" : "Right Ortho";
1504                         break;
1505                 case 7:
1506                         if (G.vd->persp & V3D_PERSP_DO_3D_PERSP)
1507                                 name = (G.vd->flag2 & V3D_OPP_DIRECTION_NAME) ? "Bottom Persp" : "Top Persp";
1508                         else
1509                                 name = (G.vd->flag2 & V3D_OPP_DIRECTION_NAME) ? "Bottom Ortho" : "Top Ortho";
1510                         break;
1511                 default:
1512                         if(G.vd->persp==V3D_PERSP_USE_THE_CAMERA) {
1513                                 if (G.vd->camera->type == OB_CAMERA) {
1514                                         Camera *cam;
1515                                         cam = G.vd->camera->data;
1516                                         name = (cam->type != CAM_ORTHO) ? "Camera Persp" : "Camera Ortho";
1517                                 } else {
1518                                         name = "Object as Camera";
1519                                 }
1520                         } else { 
1521                                 name = (G.vd->persp & V3D_PERSP_DO_3D_PERSP) ? "User Persp" : "User Ortho";
1522                         }
1523         }
1524         
1525         if (G.vd->localview) {
1526                 printable = malloc(strlen(name) + strlen(" (Local)_")); /* '_' gives space for '\0' */
1527                 strcpy(printable, name);
1528                 strcat(printable, " (Local)");
1529         } else {
1530                 printable = name;
1531         }
1532
1533         if (printable) {
1534                 BIF_ThemeColor(TH_TEXT_HI);
1535                 glRasterPos2i(10,  sa->winy-20);
1536                 BMF_DrawString(G.fonts, printable);
1537         }
1538
1539         if (G.vd->localview) {
1540                 free(printable);
1541         }
1542 }
1543
1544 /* ******************* view3d space & buttons ************** */
1545
1546
1547 /* temporal struct for storing transform properties */
1548 typedef struct {
1549         float ob_eul[4];        // used for quat too....
1550         float ob_scale[3]; // need temp space due to linked values
1551         float ob_dims[3];
1552         short link_scale;
1553         float ve_median[5];
1554         int curdef;
1555         float *defweightp;
1556 } TransformProperties;
1557
1558 /* is used for both read and write... */
1559 static void v3d_editvertex_buts(uiBlock *block, Object *ob, float lim)
1560 {
1561         EditMesh *em = G.editMesh;
1562         EditVert *eve, *evedef=NULL;
1563         EditEdge *eed;
1564         MDeformVert *dvert=NULL;
1565         TransformProperties *tfp= G.vd->properties_storage;
1566         float median[5];
1567         int tot, totw, totweight, totedge;
1568         char defstr[320];
1569         
1570         median[0]= median[1]= median[2]= median[3]= median[4]= 0.0;
1571         tot= totw= totweight= totedge= 0;
1572         defstr[0]= 0;
1573
1574         if(ob->type==OB_MESH) {         
1575                 eve= em->verts.first;
1576                 while(eve) {
1577                         if(eve->f & 1) {
1578                                 evedef= eve;
1579                                 tot++;
1580                                 VecAddf(median, median, eve->co);
1581                         }
1582                         eve= eve->next;
1583                 }
1584                 eed= em->edges.first;
1585                 while(eed) {
1586                         if((eed->f & SELECT)) {
1587                                 totedge++;
1588                                 median[3]+= eed->crease;
1589                         }
1590                         eed= eed->next;
1591                 }
1592
1593                 /* check for defgroups */
1594                 if(evedef)
1595                         dvert= CustomData_em_get(&em->vdata, evedef->data, CD_MDEFORMVERT);
1596                 if(tot==1 && dvert && dvert->totweight) {
1597                         bDeformGroup *dg;
1598                         int i, max=1, init=1;
1599                         char str[320];
1600                         
1601                         for (i=0; i<dvert->totweight; i++){
1602                                 dg = BLI_findlink (&ob->defbase, dvert->dw[i].def_nr);
1603                                 if(dg) {
1604                                         max+= snprintf(str, sizeof(str), "%s %%x%d|", dg->name, dvert->dw[i].def_nr); 
1605                                         if(max<320) strcat(defstr, str);
1606                                 }
1607                                 else printf("oh no!\n");
1608                                 if(tfp->curdef==dvert->dw[i].def_nr) {
1609                                         init= 0;
1610                                         tfp->defweightp= &dvert->dw[i].weight;
1611                                 }
1612                         }
1613                         
1614                         if(init) {      // needs new initialized 
1615                                 tfp->curdef= dvert->dw[0].def_nr;
1616                                 tfp->defweightp= &dvert->dw[0].weight;
1617                         }
1618                 }
1619         }
1620         else if(ob->type==OB_CURVE || ob->type==OB_SURF) {
1621                 extern ListBase editNurb; /* editcurve.c */
1622                 Nurb *nu;
1623                 BPoint *bp;
1624                 BezTriple *bezt;
1625                 int a;
1626                 
1627                 nu= editNurb.first;
1628                 while(nu) {
1629                         if((nu->type & 7)==CU_BEZIER) {
1630                                 bezt= nu->bezt;
1631                                 a= nu->pntsu;
1632                                 while(a--) {
1633                                         if(bezt->f2 & 1) {
1634                                                 VecAddf(median, median, bezt->vec[1]);
1635                                                 tot++;
1636                                                 median[4]+= bezt->weight;
1637                                                 totweight++;
1638                                         }
1639                                         else {
1640                                                 if(bezt->f1 & 1) {
1641                                                         VecAddf(median, median, bezt->vec[0]);
1642                                                         tot++;
1643                                                 }
1644                                                 if(bezt->f3 & 1) {
1645                                                         VecAddf(median, median, bezt->vec[2]);
1646                                                         tot++;
1647                                                 }
1648                                         }
1649                                         bezt++;
1650                                 }
1651                         }
1652                         else {
1653                                 bp= nu->bp;
1654                                 a= nu->pntsu*nu->pntsv;
1655                                 while(a--) {
1656                                         if(bp->f1 & 1) {
1657                                                 VecAddf(median, median, bp->vec);
1658                                                 median[3]+= bp->vec[3];
1659                                                 totw++;
1660                                                 tot++;
1661                                                 median[4]+= bp->weight;
1662                                                 totweight++;
1663                                         }
1664                                         bp++;
1665                                 }
1666                         }
1667                         nu= nu->next;
1668                 }
1669         }
1670         else if(ob->type==OB_LATTICE) {
1671                 BPoint *bp;
1672                 int a;
1673                 
1674                 a= editLatt->pntsu*editLatt->pntsv*editLatt->pntsw;
1675                 bp= editLatt->def;
1676                 while(a--) {
1677                         if(bp->f1 & SELECT) {
1678                                 VecAddf(median, median, bp->vec);
1679                                 tot++;
1680                                 median[4]+= bp->weight;
1681                                 totweight++;
1682                         }
1683                         bp++;
1684                 }
1685         }
1686         
1687         if(tot==0) return;
1688
1689         median[0] /= (float)tot;
1690         median[1] /= (float)tot;
1691         median[2] /= (float)tot;
1692         if(totedge) median[3] /= (float)totedge;
1693         else if(totw) median[3] /= (float)totw;
1694         if(totweight) median[4] /= (float)totweight;
1695         
1696         if(G.vd->flag & V3D_GLOBAL_STATS)
1697                 Mat4MulVecfl(ob->obmat, median);
1698         
1699         if(block) {     // buttons
1700         
1701                 uiBlockBeginAlign(block);
1702                 if((ob->parent) && (ob->partype == PARBONE)) {
1703                         uiDefButBitS(block, TOG, V3D_GLOBAL_STATS, REDRAWVIEW3D, "Global",              160, 135, 70, 19, &G.vd->flag, 0, 0, 0, 0, "Displays global values");
1704                         uiDefButBitS(block, TOGN, V3D_GLOBAL_STATS, REDRAWVIEW3D, "Local",              230, 135, 70, 19, &G.vd->flag, 0, 0, 0, 0, "Displays local values");
1705                 }
1706                 else {
1707                         uiDefButBitS(block, TOG, V3D_GLOBAL_STATS, REDRAWVIEW3D, "Global",              160, 150, 70, 19, &G.vd->flag, 0, 0, 0, 0, "Displays global values");
1708                         uiDefButBitS(block, TOGN, V3D_GLOBAL_STATS, REDRAWVIEW3D, "Local",              230, 150, 70, 19, &G.vd->flag, 0, 0, 0, 0, "Displays local values");
1709                 }
1710
1711                 memcpy(tfp->ve_median, median, sizeof(tfp->ve_median));
1712                 
1713                 uiBlockBeginAlign(block);
1714                 if(tot==1) {
1715                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Vertex X:", 10, 110, 290, 19, &(tfp->ve_median[0]), -lim, lim, 10, 3, "");
1716                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Vertex Y:", 10, 90, 290, 19, &(tfp->ve_median[1]), -lim, lim, 10, 3, "");
1717                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Vertex Z:", 10, 70, 290, 19, &(tfp->ve_median[2]), -lim, lim, 10, 3, "");
1718                         if(totw==1)
1719                                 uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Vertex W:", 10, 50, 290, 19, &(tfp->ve_median[3]), 0.01, 100.0, 10, 3, "");
1720                         uiBlockEndAlign(block);
1721         
1722                         if(defstr[0]) {
1723                                 uiDefBut(block, LABEL, 1, "Vertex Deform Groups",               10, 40, 290, 20, NULL, 0.0, 0.0, 0, 0, "");
1724
1725                                 uiBlockBeginAlign(block);
1726                                 uiDefButF(block, NUM, B_NOP, "Weight:",                 10, 20, 150, 19, tfp->defweightp, 0.0f, 1.0f, 10, 3, "Weight value");
1727                                 uiDefButI(block, MENU, REDRAWVIEW3D, defstr,    160, 20, 140, 19, &tfp->curdef, 0.0, 0.0, 0, 0, "Current Vertex Group");
1728                                 uiBlockEndAlign(block);
1729                         }
1730                         else if(totweight)
1731                                 uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Weight:",   10, 20, 290, 19, &(tfp->ve_median[4]), 0.0, 1.0, 10, 3, "");
1732
1733                 }
1734                 else {
1735                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Median X:", 10, 110, 290, 19, &(tfp->ve_median[0]), -lim, lim, 10, 3, "");
1736                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Median Y:", 10, 90, 290, 19, &(tfp->ve_median[1]), -lim, lim, 10, 3, "");
1737                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Median Z:", 10, 70, 290, 19, &(tfp->ve_median[2]), -lim, lim, 10, 3, "");
1738                         if(totw==tot)
1739                                 uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Median W:", 10, 50, 290, 19, &(tfp->ve_median[3]), 0.01, 100.0, 10, 3, "");
1740                         uiBlockEndAlign(block);
1741                         if(totweight)
1742                                 uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Weight:",   10, 20, 290, 19, &(tfp->ve_median[4]), 0.0, 1.0, 10, 3, "Weight is used for SoftBody Goal");
1743                 }
1744                 
1745                 if(totedge==1)
1746                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Crease W:", 10, 30, 290, 19, &(tfp->ve_median[3]), 0.0, 1.0, 10, 3, "");
1747                 else if(totedge>1)
1748                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Median Crease W:",  10, 30, 290, 19, &(tfp->ve_median[3]), 0.0, 1.0, 10, 3, "");
1749                 
1750         }
1751         else {  // apply
1752                 
1753                 if(G.vd->flag & V3D_GLOBAL_STATS) {
1754                         Mat4Invert(ob->imat, ob->obmat);
1755                         Mat4MulVecfl(ob->imat, median);
1756                         Mat4MulVecfl(ob->imat, tfp->ve_median);
1757                 }
1758                 VecSubf(median, tfp->ve_median, median);
1759                 median[3]= tfp->ve_median[3]-median[3];
1760                 median[4]= tfp->ve_median[4]-median[4];
1761                 
1762                 if(ob->type==OB_MESH) {
1763                         
1764                         eve= em->verts.first;
1765                         while(eve) {
1766                                 if(eve->f & 1) {
1767                                         VecAddf(eve->co, eve->co, median);
1768                                 }
1769                                 eve= eve->next;
1770                         }
1771                         
1772                         for(eed= em->edges.first; eed; eed= eed->next) {
1773                                 if(eed->f & SELECT) {
1774                                         /* ensure the median can be set to zero or one */
1775                                         if(tfp->ve_median[3]==0.0f) eed->crease= 0.0f;
1776                                         else if(tfp->ve_median[3]==1.0f) eed->crease= 1.0f;
1777                                         else {
1778                                                 eed->crease+= median[3];
1779                                                 CLAMP(eed->crease, 0.0, 1.0);
1780                                         }
1781                                 }
1782                         }
1783                         
1784                         recalc_editnormals();
1785                 }
1786                 else if(ob->type==OB_CURVE || ob->type==OB_SURF) {
1787                         extern ListBase editNurb; /* editcurve.c */
1788                         Nurb *nu;
1789                         BPoint *bp;
1790                         BezTriple *bezt;
1791                         int a;
1792                         
1793                         nu= editNurb.first;
1794                         while(nu) {
1795                                 if((nu->type & 7)==1) {
1796                                         bezt= nu->bezt;
1797                                         a= nu->pntsu;
1798                                         while(a--) {
1799                                                 if(bezt->f2 & 1) {
1800                                                         VecAddf(bezt->vec[0], bezt->vec[0], median);
1801                                                         VecAddf(bezt->vec[1], bezt->vec[1], median);
1802                                                         VecAddf(bezt->vec[2], bezt->vec[2], median);
1803                                                         bezt->weight+= median[4];
1804                                                 }
1805                                                 else {
1806                                                         if(bezt->f1 & 1) {
1807                                                                 VecAddf(bezt->vec[0], bezt->vec[0], median);
1808                                                         }
1809                                                         if(bezt->f3 & 1) {
1810                                                                 VecAddf(bezt->vec[2], bezt->vec[2], median);
1811                                                         }
1812                                                 }
1813                                                 bezt++;
1814                                         }
1815                                 }
1816                                 else {
1817                                         bp= nu->bp;
1818                                         a= nu->pntsu*nu->pntsv;
1819                                         while(a--) {
1820                                                 if(bp->f1 & 1) {
1821                                                         VecAddf(bp->vec, bp->vec, median);
1822                                                         bp->vec[3]+= median[3];
1823                                                         bp->weight+= median[4];
1824                                                 }
1825                                                 bp++;
1826                                         }
1827                                 }
1828                                 test2DNurb(nu);
1829                                 testhandlesNurb(nu); /* test for bezier too */
1830
1831                                 nu= nu->next;
1832                         }
1833                 }
1834                 else if(ob->type==OB_LATTICE) {
1835                         BPoint *bp;
1836                         int a;
1837                         
1838                         a= editLatt->pntsu*editLatt->pntsv*editLatt->pntsw;
1839                         bp= editLatt->def;
1840                         while(a--) {
1841                                 if(bp->f1 & SELECT) {
1842                                         VecAddf(bp->vec, bp->vec, median);
1843                                         bp->weight+= median[4];
1844                                 }
1845                                 bp++;
1846                         }
1847                 }
1848                 
1849                 BIF_undo_push("Transform properties");
1850         }
1851 }
1852
1853 /* assumes armature active */
1854 static void validate_bonebutton_cb(void *bonev, void *namev)
1855 {
1856         Object *ob= OBACT;
1857         
1858         if(ob && ob->type==OB_ARMATURE) {
1859                 Bone *bone= bonev;
1860                 char oldname[32], newname[32];
1861                 
1862                 /* need to be on the stack */
1863                 BLI_strncpy(newname, bone->name, 32);
1864                 BLI_strncpy(oldname, (char *)namev, 32);
1865                 /* restore */
1866                 BLI_strncpy(bone->name, oldname, 32);
1867                 
1868                 armature_bone_rename(ob->data, oldname, newname); // editarmature.c
1869                 allqueue(REDRAWALL, 0);
1870         }
1871 }
1872
1873 static void v3d_posearmature_buts(uiBlock *block, Object *ob, float lim)
1874 {
1875         uiBut *but;
1876         bArmature *arm;
1877         bPoseChannel *pchan;
1878         Bone *bone= NULL;
1879         TransformProperties *tfp= G.vd->properties_storage;
1880
1881         arm = get_armature(OBACT);
1882         if (!arm || !ob->pose) return;
1883
1884         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1885                 bone = pchan->bone;
1886                 if(bone && (bone->flag & BONE_ACTIVE) && (bone->layer & arm->layer))
1887                         break;
1888         }
1889         if (!pchan || !bone) return;
1890
1891         if((ob->parent) && (ob->partype == PARBONE))
1892                 but= uiDefBut (block, TEX, B_DIFF, "Bone:",                             160, 130, 140, 19, bone->name, 1, 31, 0, 0, "");
1893         else
1894                 but= uiDefBut(block, TEX, B_DIFF, "Bone:",                              160, 140, 140, 19, bone->name, 1, 31, 0, 0, "");
1895         uiButSetFunc(but, validate_bonebutton_cb, bone, NULL);
1896         
1897         QuatToEul(pchan->quat, tfp->ob_eul);
1898         tfp->ob_eul[0]*= 180.0/M_PI;
1899         tfp->ob_eul[1]*= 180.0/M_PI;
1900         tfp->ob_eul[2]*= 180.0/M_PI;
1901         
1902         uiBlockBeginAlign(block);
1903         uiDefIconButBitS(block, ICONTOG, OB_LOCK_LOCX, REDRAWVIEW3D, ICON_UNLOCKED,     10,140,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1904         uiDefButF(block, NUM, B_ARMATUREPANEL2, "LocX:",        30, 140, 120, 19, pchan->loc, -lim, lim, 100, 3, "");
1905         uiDefIconButBitS(block, ICONTOG, OB_LOCK_LOCY, REDRAWVIEW3D, ICON_UNLOCKED,     10,120,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1906         uiDefButF(block, NUM, B_ARMATUREPANEL2, "LocY:",        30, 120, 120, 19, pchan->loc+1, -lim, lim, 100, 3, "");
1907         uiDefIconButBitS(block, ICONTOG, OB_LOCK_LOCZ, REDRAWVIEW3D, ICON_UNLOCKED,     10,100,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1908         uiDefButF(block, NUM, B_ARMATUREPANEL2, "LocZ:",        30, 100, 120, 19, pchan->loc+2, -lim, lim, 100, 3, "");
1909
1910         uiBlockBeginAlign(block);
1911         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTX, REDRAWVIEW3D, ICON_UNLOCKED,     10,70,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1912         uiDefButF(block, NUM, B_ARMATUREPANEL3, "RotX:",        30, 70, 120, 19, tfp->ob_eul, -1000.0, 1000.0, 100, 3, "");
1913         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTY, REDRAWVIEW3D, ICON_UNLOCKED,     10,50,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1914         uiDefButF(block, NUM, B_ARMATUREPANEL3, "RotY:",        30, 50, 120, 19, tfp->ob_eul+1, -1000.0, 1000.0, 100, 3, "");
1915         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTZ, REDRAWVIEW3D, ICON_UNLOCKED,     10,30,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1916         uiDefButF(block, NUM, B_ARMATUREPANEL3, "RotZ:",        30, 30, 120, 19, tfp->ob_eul+2, -1000.0, 1000.0, 100, 3, "");
1917         
1918         uiBlockBeginAlign(block);
1919         uiDefIconButBitS(block, ICONTOG, OB_LOCK_SCALEX, REDRAWVIEW3D, ICON_UNLOCKED,   160,70,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1920         uiDefButF(block, NUM, B_ARMATUREPANEL2, "ScaleX:",      180, 70, 120, 19, pchan->size, -lim, lim, 10, 3, "");
1921         uiDefIconButBitS(block, ICONTOG, OB_LOCK_SCALEY, REDRAWVIEW3D, ICON_UNLOCKED,   160,50,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1922         uiDefButF(block, NUM, B_ARMATUREPANEL2, "ScaleY:",      180, 50, 120, 19, pchan->size+1, -lim, lim, 10, 3, "");
1923         uiDefIconButBitS(block, ICONTOG, OB_LOCK_SCALEZ, REDRAWVIEW3D, ICON_UNLOCKED,   160,30,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1924         uiDefButF(block, NUM, B_ARMATUREPANEL2, "ScaleZ:",      180, 30, 120, 19, pchan->size+2, -lim, lim, 10, 3, "");
1925         uiBlockEndAlign(block);
1926 }
1927
1928 static void v3d_editarmature_buts(uiBlock *block, Object *ob, float lim)
1929 {
1930         bArmature *arm= G.obedit->data;
1931         EditBone *ebone;
1932         uiBut *but;
1933         TransformProperties *tfp= G.vd->properties_storage;
1934         
1935         ebone= G.edbo.first;
1936
1937         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1938                 if ((ebone->flag & BONE_ACTIVE) && (ebone->layer & arm->layer))
1939                         break;
1940         }
1941
1942         if (!ebone)
1943                 return;
1944         
1945         if((ob->parent) && (ob->partype == PARBONE))
1946                 but= uiDefBut(block, TEX, B_DIFF, "Bone:", 160, 130, 140, 19, ebone->name, 1, 31, 0, 0, "");
1947         else
1948                 but= uiDefBut(block, TEX, B_DIFF, "Bone:",                      160, 150, 140, 19, ebone->name, 1, 31, 0, 0, "");
1949         uiButSetFunc(but, validate_editbonebutton_cb, ebone, NULL);
1950
1951         uiBlockBeginAlign(block);
1952         uiDefButF(block, NUM, B_ARMATUREPANEL1, "HeadX:",       10, 70, 140, 19, ebone->head, -lim, lim, 10, 3, "");
1953         uiDefButF(block, NUM, B_ARMATUREPANEL1, "HeadY:",       10, 50, 140, 19, ebone->head+1, -lim, lim, 10, 3, "");
1954         uiDefButF(block, NUM, B_ARMATUREPANEL1, "HeadZ:",       10, 30, 140, 19, ebone->head+2, -lim, lim, 10, 3, "");
1955         uiBlockBeginAlign(block);
1956         uiDefButF(block, NUM, B_ARMATUREPANEL1, "TailX:",       160, 70, 140, 19, ebone->tail, -lim, lim, 10, 3, "");
1957         uiDefButF(block, NUM, B_ARMATUREPANEL1, "TailY:",       160, 50, 140, 19, ebone->tail+1, -lim, lim, 10, 3, "");
1958         uiDefButF(block, NUM, B_ARMATUREPANEL1, "TailZ:",       160, 30, 140, 19, ebone->tail+2, -lim, lim, 10, 3, "");
1959         uiBlockEndAlign(block);
1960         
1961         tfp->ob_eul[0]= 180.0*ebone->roll/M_PI;
1962         uiDefButF(block, NUM, B_ARMATUREPANEL1, "Roll:",        10, 100, 140, 19, tfp->ob_eul, -lim, lim, 1000, 3, "");
1963
1964         uiBlockBeginAlign(block);
1965         uiDefButF(block, NUM, B_ARMATUREPANEL1, "TailRadius:",  10, 150, 140, 19, &ebone->rad_tail, 0, lim, 10, 3, "");
1966         if (ebone->parent && ebone->flag & BONE_CONNECTED )
1967                 uiDefButF(block, NUM, B_ARMATUREPANEL1, "HeadRadius:",  10, 130, 140, 19, &ebone->parent->rad_tail, 0, lim, 10, 3, "");
1968         else
1969                 uiDefButF(block, NUM, B_ARMATUREPANEL1, "HeadRadius:",  10, 130, 140, 19, &ebone->rad_head, 0, lim, 10, 3, "");
1970         uiBlockEndAlign(block);
1971 }
1972
1973 static void v3d_editmetaball_buts(uiBlock *block, Object *ob, float lim)
1974 {
1975         extern MetaElem *lastelem;
1976
1977         if(lastelem) {
1978                 uiBlockBeginAlign(block);
1979                 uiDefButF(block, NUM, B_RECALCMBALL, "LocX:", 10, 70, 140, 19, &lastelem->x, -lim, lim, 100, 3, "");
1980                 uiDefButF(block, NUM, B_RECALCMBALL, "LocY:", 10, 50, 140, 19, &lastelem->y, -lim, lim, 100, 3, "");
1981                 uiDefButF(block, NUM, B_RECALCMBALL, "LocZ:", 10, 30, 140, 19, &lastelem->z, -lim, lim, 100, 3, "");
1982
1983                 uiBlockBeginAlign(block);
1984                 if(lastelem->type!=MB_BALL)
1985                         uiDefButF(block, NUM, B_RECALCMBALL, "dx:", 160, 70, 140, 19, &lastelem->expx, 0, lim, 100, 3, "");
1986                 if((lastelem->type!=MB_BALL) && (lastelem->type!=MB_TUBE))
1987                         uiDefButF(block, NUM, B_RECALCMBALL, "dy:", 160, 50, 140, 19, &lastelem->expy, 0, lim, 100, 3, "");
1988                 if((lastelem->type==MB_ELIPSOID) || (lastelem->type==MB_CUBE))
1989                         uiDefButF(block, NUM, B_RECALCMBALL, "dz:", 160, 30, 140, 19, &lastelem->expz, 0, lim, 100, 3, "");
1990
1991                 uiBlockEndAlign(block); 
1992
1993                 uiBlockBeginAlign(block);
1994                 uiDefButF(block, NUM, B_RECALCMBALL, "Radius:", 10, 120, 140, 19, &lastelem->rad, 0, lim, 100, 3, "Size of the active metaball");
1995                 uiDefButF(block, NUM, B_RECALCMBALL, "Stiffness:", 10, 100, 140, 19, &lastelem->s, 0, 10, 100, 3, "Stiffness of the active metaball");
1996                 uiBlockEndAlign(block);
1997                 
1998                 uiDefButS(block, MENU, B_RECALCMBALL, "Type%t|Ball%x0|Tube%x4|Plane%x5|Elipsoid%x6|Cube%x7", 160, 120, 140, 19, &lastelem->type, 0.0, 0.0, 0, 0, "Set active element type");
1999                 
2000         }
2001 }
2002
2003 void do_viewbuts(unsigned short event)
2004 {
2005         BoundBox *bb;
2006         View3D *vd;
2007         Object *ob= OBACT;
2008         TransformProperties *tfp= G.vd->properties_storage;
2009         
2010         vd= G.vd;
2011         if(vd==NULL) return;
2012
2013         switch(event) {
2014                 
2015         case B_OBJECTPANEL:
2016                 DAG_object_flush_update(G.scene, ob, OB_RECALC_OB);
2017                 allqueue(REDRAWVIEW3D, 1);
2018                 break;
2019                 
2020         case B_OBJECTPANELROT:
2021                 if(ob) {
2022                         ob->rot[0]= M_PI*tfp->ob_eul[0]/180.0;
2023                         ob->rot[1]= M_PI*tfp->ob_eul[1]/180.0;
2024                         ob->rot[2]= M_PI*tfp->ob_eul[2]/180.0;
2025                         DAG_object_flush_update(G.scene, ob, OB_RECALC_OB);
2026                         allqueue(REDRAWVIEW3D, 1);
2027                 }
2028                 break;
2029
2030         case B_OBJECTPANELSCALE:
2031                 if(ob) {
2032
2033                         /* link scale; figure out which axis changed */
2034                         if (tfp->link_scale) {
2035                                 float ratio, tmp, max = 0.0;
2036                                 int axis;
2037                                 
2038                                 axis = 0;
2039                                 max = fabs(tfp->ob_scale[0] - ob->size[0]);
2040                                 tmp = fabs(tfp->ob_scale[1] - ob->size[1]);
2041                                 if (tmp > max) {
2042                                         axis = 1;
2043                                         max = tmp;
2044                                 }
2045                                 tmp = fabs(tfp->ob_scale[2] - ob->size[2]);
2046                                 if (tmp > max) {
2047                                         axis = 2;
2048                                         max = tmp;
2049                                 }
2050                         
2051                                 if (ob->size[axis] != tfp->ob_scale[axis]) {
2052                                         if (fabs(ob->size[axis]) > FLT_EPSILON) {
2053                                                 ratio = tfp->ob_scale[axis] / ob->size[axis];
2054                                                 ob->size[0] *= ratio;
2055                                                 ob->size[1] *= ratio;
2056                                                 ob->size[2] *= ratio;
2057                                         }
2058                                 }
2059                         }
2060                         else {
2061                                 VECCOPY(ob->size, tfp->ob_scale);
2062                                 
2063                         }
2064                         DAG_object_flush_update(G.scene, ob, OB_RECALC_OB);
2065                         allqueue(REDRAWVIEW3D, 1);
2066                 }
2067                 break;
2068
2069         case B_OBJECTPANELDIMS:
2070                 bb= object_get_boundbox(ob);
2071                 if(bb) {
2072                         float old_dims[3], scale[3], ratio, len[3];
2073                         int axis;
2074
2075                         Mat4ToSize(ob->obmat, scale);
2076
2077                         len[0] = bb->vec[4][0] - bb->vec[0][0];
2078                         len[1] = bb->vec[2][1] - bb->vec[0][1];
2079                         len[2] = bb->vec[1][2] - bb->vec[0][2];
2080
2081                         old_dims[0] = fabs(scale[0]) * len[0];
2082                         old_dims[1] = fabs(scale[1]) * len[1];
2083                         old_dims[2] = fabs(scale[2]) * len[2];
2084
2085                         /* for each axis changed */
2086                         for (axis = 0; axis<3; axis++) {
2087                                 if (fabs(old_dims[axis] - tfp->ob_dims[axis]) > 0.0001) {
2088                                         if (old_dims[axis] > 0.0) {
2089                                                 ratio = tfp->ob_dims[axis] / old_dims[axis]; 
2090                                                 if (tfp->link_scale) {
2091                                                         ob->size[0] *= ratio;
2092                                                         ob->size[1] *= ratio;
2093                                                         ob->size[2] *= ratio;
2094                                                         break;
2095                                                 }
2096                                                 else {
2097                                                         ob->size[axis] *= ratio;
2098                                                 }
2099                                         }
2100                                         else {
2101                                                 if (len[axis] > 0) {
2102                                                         ob->size[axis] = tfp->ob_dims[axis] / len[axis];
2103                                                 }
2104                                         }
2105                                 }
2106                         }
2107                         
2108                         /* prevent multiple B_OBJECTPANELDIMS events to keep scaling, cycling with TAB on buttons can cause that */
2109                         VECCOPY(tfp->ob_dims, old_dims);
2110                         
2111                         DAG_object_flush_update(G.scene, ob, OB_RECALC_OB);
2112                         allqueue(REDRAWVIEW3D, 1);
2113                 }
2114                 break;
2115         
2116         case B_OBJECTPANELMEDIAN:
2117                 if(ob) {
2118                         v3d_editvertex_buts(NULL, ob, 1.0);
2119                         DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
2120                         allqueue(REDRAWVIEW3D, 1);
2121                 }
2122                 break;
2123                 
2124                 /* note; this case also used for parbone */
2125         case B_OBJECTPANELPARENT:
2126                 if(ob) {
2127                         if(ob->id.lib || test_parent_loop(ob->parent, ob) ) 
2128                                 ob->parent= NULL;
2129                         else {
2130                                 DAG_scene_sort(G.scene);
2131                                 DAG_object_flush_update(G.scene, ob, OB_RECALC_OB);
2132                         }
2133                         allqueue(REDRAWVIEW3D, 1);
2134                         allqueue(REDRAWBUTSOBJECT, 0);
2135                 }
2136                 break;
2137                 
2138         case B_ARMATUREPANEL1:
2139                 {
2140                         bArmature *arm= G.obedit->data;
2141                         EditBone *ebone, *child;
2142                         
2143                         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
2144                                 if ((ebone->flag & BONE_ACTIVE) && (ebone->layer & arm->layer))
2145                                         break;
2146                         }
2147                         if (ebone) {
2148                                 ebone->roll= M_PI*tfp->ob_eul[0]/180.0;
2149                                 //      Update our parent
2150                                 if (ebone->parent && ebone->flag & BONE_CONNECTED){
2151                                         VECCOPY (ebone->parent->tail, ebone->head);
2152                                 }
2153                         
2154                                 //      Update our children if necessary
2155                                 for (child = G.edbo.first; child; child=child->next){
2156                                         if (child->parent == ebone && (child->flag & BONE_CONNECTED)){
2157                                                 VECCOPY (child->head, ebone->tail);
2158                                         }
2159                                 }
2160                                 if(arm->flag & ARM_MIRROR_EDIT) {
2161                                         EditBone *eboflip= armature_bone_get_mirrored(ebone);
2162                                         if(eboflip) {
2163                                                 eboflip->roll= -ebone->roll;
2164                                                 eboflip->head[0]= -ebone->head[0];
2165                                                 eboflip->tail[0]= -ebone->tail[0];
2166                                                 
2167                                                 //      Update our parent
2168                                                 if (eboflip->parent && eboflip->flag & BONE_CONNECTED){
2169                                                         VECCOPY (eboflip->parent->tail, eboflip->head);
2170                                                 }
2171                                                 
2172                                                 //      Update our children if necessary
2173                                                 for (child = G.edbo.first; child; child=child->next){
2174                                                         if (child->parent == eboflip && (child->flag & BONE_CONNECTED)){
2175                                                                 VECCOPY (child->head, eboflip->tail);
2176                                                         }
2177                                                 }
2178                                         }
2179                                 }
2180                                 
2181                                 allqueue(REDRAWVIEW3D, 1);
2182                         }
2183                 }
2184                 break;
2185         case B_ARMATUREPANEL3:  // rotate button on channel
2186                 {
2187                         bArmature *arm;
2188                         bPoseChannel *pchan;
2189                         Bone *bone;
2190                         float eul[3];
2191                         
2192                         arm = get_armature(OBACT);
2193                         if (!arm || !ob->pose) return;
2194                                 
2195                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2196                                 bone = pchan->bone;
2197                                 if(bone && (bone->flag & BONE_ACTIVE) && (bone->layer & arm->layer))
2198                                         break;
2199                         }
2200                         if (!pchan) return;
2201                         
2202                         /* make a copy to eul[3], to allow TAB on buttons to work */
2203                         eul[0]= M_PI*tfp->ob_eul[0]/180.0;
2204                         eul[1]= M_PI*tfp->ob_eul[1]/180.0;
2205                         eul[2]= M_PI*tfp->ob_eul[2]/180.0;
2206                         EulToQuat(eul, pchan->quat);
2207                 }
2208                 /* no break, pass on */
2209         case B_ARMATUREPANEL2:
2210                 {
2211                         ob->pose->flag |= (POSE_LOCKED|POSE_DO_UNLOCK);
2212                         DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
2213                         allqueue(REDRAWVIEW3D, 1);
2214                 }
2215                 break;
2216         }
2217 }
2218
2219
2220 static void view3d_panel_object(short cntrl)    // VIEW3D_HANDLER_OBJECT
2221 {
2222         uiBlock *block;
2223         uiBut *bt;
2224         Object *ob= OBACT;
2225         TransformProperties *tfp;
2226         float lim;
2227         static char hexcol[128];
2228         
2229         if(ob==NULL) return;
2230
2231         /* make sure we got storage */
2232         if(G.vd->properties_storage==NULL)
2233                 G.vd->properties_storage= MEM_callocN(sizeof(TransformProperties), "TransformProperties");
2234         tfp= G.vd->properties_storage;
2235         
2236         block= uiNewBlock(&curarea->uiblocks, "view3d_panel_object", UI_EMBOSS, UI_HELV, curarea->win);
2237         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
2238         uiSetPanelHandler(VIEW3D_HANDLER_OBJECT);  // for close and esc
2239
2240         if(!uiNewPanel(curarea, block, "Transform Properties", "View3d", 10, 230, 318, 204))
2241                 return;
2242
2243         uiSetButLock(object_data_is_libdata(ob), ERROR_LIBDATA_MESSAGE);
2244         
2245         if(G.f & (G_VERTEXPAINT|G_TEXTUREPAINT|G_WEIGHTPAINT)) {
2246                 uiBlockSetFlag(block, UI_BLOCK_FRONTBUFFER);    // force old style frontbuffer draw
2247         }
2248         else {
2249                 bt= uiDefBut(block, TEX, B_IDNAME, "OB: ",      10,180,140,20, ob->id.name+2, 0.0, 21.0, 0, 0, "");
2250 #ifdef WITH_VERSE
2251                 if(ob->vnode) uiButSetFunc(bt, test_and_send_idbutton_cb, ob, ob->id.name);
2252                 else uiButSetFunc(bt, test_idbutton_cb, ob->id.name, NULL);
2253 #else
2254                 uiButSetFunc(bt, test_idbutton_cb, ob->id.name, NULL);
2255 #endif
2256
2257                 uiBlockBeginAlign(block);
2258                 uiDefIDPoinBut(block, test_obpoin_but, ID_OB, B_OBJECTPANELPARENT, "Par:", 160, 180, 140, 20, &ob->parent, "Parent Object"); 
2259                 if((ob->parent) && (ob->partype == PARBONE)) {
2260                         bt= uiDefBut(block, TEX, B_OBJECTPANELPARENT, "ParBone:", 160, 160, 140, 20, ob->parsubstr, 0, 30, 0, 0, "");
2261                         uiButSetCompleteFunc(bt, autocomplete_bone, (void *)ob->parent);
2262                 }
2263                 else {
2264                         strcpy(ob->parsubstr, "");
2265                 }
2266                 uiBlockEndAlign(block);
2267         }
2268
2269         lim= 10000.0f*MAX2(1.0, G.vd->grid);
2270
2271         if(ob==G.obedit) {
2272                 if(ob->type==OB_ARMATURE) v3d_editarmature_buts(block, ob, lim);
2273                 if(ob->type==OB_MBALL) v3d_editmetaball_buts(block, ob, lim);
2274                 else v3d_editvertex_buts(block, ob, lim);
2275         }
2276         else if(ob->flag & OB_POSEMODE) {
2277                 v3d_posearmature_buts(block, ob, lim);
2278         }
2279         else if(G.f & G_WEIGHTPAINT) {
2280                 uiNewPanelTitle(block, "Weight Paint Properties");
2281                 weight_paint_buttons(block);
2282         }
2283         else if(G.f & (G_VERTEXPAINT|G_TEXTUREPAINT)) {
2284                 extern VPaint Gvp;         /* from vpaint */
2285                 static float hsv[3], old[3];    // used as temp mem for picker
2286                 float *rgb= NULL;
2287                 ToolSettings *settings= G.scene->toolsettings;
2288
2289                 if(G.f & G_VERTEXPAINT) rgb= &Gvp.r;
2290                 else if(settings->imapaint.brush) rgb= settings->imapaint.brush->rgb;
2291                 
2292                 uiNewPanelTitle(block, "Paint Properties");
2293                 if (rgb)
2294                         /* 'f' is for floating panel */
2295                         uiBlockPickerButtons(block, rgb, hsv, old, hexcol, 'f', REDRAWBUTSEDIT);
2296         }
2297         else if(G.f & G_SCULPTMODE) {
2298                 uiNewPanelTitle(block, "Sculpt Properties");
2299                 sculptmode_draw_interface_tools(block,10,150);
2300         } else {
2301                 BoundBox *bb = NULL;
2302
2303                 uiBlockBeginAlign(block);
2304                 uiDefIconButBitS(block, ICONTOG, OB_LOCK_LOCX, REDRAWVIEW3D, ICON_UNLOCKED,     10,150,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2305                 uiDefButF(block, NUM, B_OBJECTPANEL, "LocX:",           30, 150, 120, 19, &(ob->loc[0]), -lim, lim, 100, 3, "");
2306                 uiDefIconButBitS(block, ICONTOG, OB_LOCK_LOCY, REDRAWVIEW3D, ICON_UNLOCKED,     10,130,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2307                 uiDefButF(block, NUM, B_OBJECTPANEL, "LocY:",           30, 130, 120, 19, &(ob->loc[1]), -lim, lim, 100, 3, "");
2308                 uiDefIconButBitS(block, ICONTOG, OB_LOCK_LOCZ, REDRAWVIEW3D, ICON_UNLOCKED,     10,110,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2309                 uiDefButF(block, NUM, B_OBJECTPANEL, "LocZ:",           30, 110, 120, 19, &(ob->loc[2]), -lim, lim, 100, 3, "");
2310                 
2311                 tfp->ob_eul[0]= 180.0*ob->rot[0]/M_PI;
2312                 tfp->ob_eul[1]= 180.0*ob->rot[1]/M_PI;
2313                 tfp->ob_eul[2]= 180.0*ob->rot[2]/M_PI;
2314                 
2315                 uiBlockBeginAlign(block);
2316                 if ((ob->parent) && (ob->partype == PARBONE)) {
2317                         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTX, REDRAWVIEW3D, ICON_UNLOCKED,     160,130,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2318                         uiDefButF(block, NUM, B_OBJECTPANELROT, "RotX:",        180, 130, 120, 19, &(tfp->ob_eul[0]), -lim, lim, 1000, 3, "");
2319                         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTY, REDRAWVIEW3D, ICON_UNLOCKED,     160,110,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2320                         uiDefButF(block, NUM, B_OBJECTPANELROT, "RotY:",        180, 110, 120, 19, &(tfp->ob_eul[1]), -lim, lim, 1000, 3, "");
2321                         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTZ, REDRAWVIEW3D, ICON_UNLOCKED,     160,90,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2322                         uiDefButF(block, NUM, B_OBJECTPANELROT, "RotZ:",        180, 90, 120, 19, &(tfp->ob_eul[2]), -lim, lim, 1000, 3, "");
2323
2324                 }
2325                 else {
2326                         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTX, REDRAWVIEW3D, ICON_UNLOCKED,     160,150,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2327                         uiDefButF(block, NUM, B_OBJECTPANELROT, "RotX:",        180, 150, 120, 19, &(tfp->ob_eul[0]), -lim, lim, 1000, 3, "");
2328                         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTY, REDRAWVIEW3D, ICON_UNLOCKED,     160,130,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2329                         uiDefButF(block, NUM, B_OBJECTPANELROT, "RotY:",        180, 130, 120, 19, &(tfp->ob_eul[1]), -lim, lim, 1000, 3, "");
2330                         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTZ, REDRAWVIEW3D, ICON_UNLOCKED,     160,110,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2331                         uiDefButF(block, NUM, B_OBJECTPANELROT, "RotZ:",        180, 110, 120, 19, &(tfp->ob_eul[2]), -lim, lim, 1000, 3, "");
2332                 }
2333
2334                 tfp->ob_scale[0]= ob->size[0];
2335                 tfp->ob_scale[1]= ob->size[1];
2336                 tfp->ob_scale[2]= ob->size[2];
2337
2338                 uiBlockBeginAlign(block);
2339                 uiDefIconButBitS(block, ICONTOG, OB_LOCK_SCALEX, REDRAWVIEW3D, ICON_UNLOCKED,   10,80,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2340                 uiDefButF(block, NUM, B_OBJECTPANELSCALE, "ScaleX:",            30, 80, 120, 19, &(tfp->ob_scale[0]), -lim, lim, 10, 3, "");
2341                 uiDefIconButBitS(block, ICONTOG, OB_LOCK_SCALEY, REDRAWVIEW3D, ICON_UNLOCKED,   10,60,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2342                 uiDefButF(block, NUM, B_OBJECTPANELSCALE, "ScaleY:",            30, 60, 120, 19, &(tfp->ob_scale[1]), -lim, lim, 10, 3, "");
2343                 uiDefIconButBitS(block, ICONTOG, OB_LOCK_SCALEZ, REDRAWVIEW3D, ICON_UNLOCKED,   10,40,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2344                 uiDefButF(block, NUM, B_OBJECTPANELSCALE, "ScaleZ:",            30, 40, 120, 19, &(tfp->ob_scale[2]), -lim, lim, 10, 3, "");
2345                 uiBlockEndAlign(block);
2346                 
2347                 uiDefButS(block, TOG, REDRAWVIEW3D, "Link Scale",               10, 10, 140, 19, &(tfp->link_scale), 0, 1, 0, 0, "Scale values vary proportionally in all directions");
2348
2349                 bb= object_get_boundbox(ob);
2350                 if (bb) {
2351                         float scale[3];
2352
2353                         Mat4ToSize(ob->obmat, scale);
2354
2355                         tfp->ob_dims[0] = fabs(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2356                         tfp->ob_dims[1] = fabs(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2357                         tfp->ob_dims[2] = fabs(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2358
2359                         uiBlockBeginAlign(block);
2360                         if ((ob->parent) && (ob->partype == PARBONE)) {
2361                                 uiDefButF(block, NUM, B_OBJECTPANELDIMS, "DimX:",               160, 60, 140, 19, &(tfp->ob_dims[0]), 0.0, lim, 10, 3, "Manipulate bounding box size");
2362                                 uiDefButF(block, NUM, B_OBJECTPANELDIMS, "DimY:",               160, 40, 140, 19, &(tfp->ob_dims[1]), 0.0, lim, 10, 3, "Manipulate bounding box size");
2363                                 uiDefButF(block, NUM, B_OBJECTPANELDIMS, "DimZ:",               160, 20, 140, 19, &(tfp->ob_dims[2]), 0.0, lim, 10, 3, "Manipulate bounding box size");
2364
2365                         }
2366                         else {
2367                                 uiDefButF(block, NUM, B_OBJECTPANELDIMS, "DimX:",               160, 80, 140, 19, &(tfp->ob_dims[0]), 0.0, lim, 10, 3, "Manipulate bounding box size");
2368                                 uiDefButF(block, NUM, B_OBJECTPANELDIMS, "DimY:",               160, 60, 140, 19, &(tfp->ob_dims[1]), 0.0, lim, 10, 3, "Manipulate bounding box size");
2369                                 uiDefButF(block, NUM, B_OBJECTPANELDIMS, "DimZ:",               160, 40, 140, 19, &(tfp->ob_dims[2]), 0.0, lim, 10, 3, "Manipulate bounding box size");
2370                         }
2371
2372                         uiBlockEndAlign(block);
2373                 }
2374         }
2375         uiClearButLock();
2376 }
2377
2378 static void view3d_panel_background(short cntrl)        // VIEW3D_HANDLER_BACKGROUND
2379 {
2380         uiBlock *block;
2381         View3D *vd;
2382         
2383         vd= G.vd;
2384
2385         block= uiNewBlock(&curarea->uiblocks, "view3d_panel_background", UI_EMBOSS, UI_HELV, curarea->win);
2386         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE  | cntrl);
2387         uiSetPanelHandler(VIEW3D_HANDLER_BACKGROUND);  // for close and esc
2388         if(uiNewPanel(curarea, block, "Background Image", "View3d", 340, 10, 318, 204)==0) return;
2389
2390         if(G.f & G_VERTEXPAINT || G.f & G_WEIGHTPAINT || G.f & G_TEXTUREPAINT) {
2391                 uiBlockSetFlag(block, UI_BLOCK_FRONTBUFFER);    // force old style frontbuffer draw
2392         }
2393         
2394         if(vd->flag & V3D_DISPBGPIC) {
2395                 if(vd->bgpic==NULL) {
2396                         vd->bgpic= MEM_callocN(sizeof(BGpic), "bgpic");
2397                         vd->bgpic->size= 5.0;
2398                         vd->bgpic->blend= 0.5;
2399                         vd->bgpic->iuser.fie_ima= 2;
2400                         vd->bgpic->iuser.ok= 1;
2401                 }
2402         }
2403         
2404         if(!(vd->flag & V3D_DISPBGPIC)) {
2405                 uiDefButBitS(block, TOG, V3D_DISPBGPIC, B_REDR, "Use Background Image", 10, 180, 150, 20, &vd->flag, 0, 0, 0, 0, "Display an image in the background of this 3D View");
2406                 uiDefBut(block, LABEL, 1, " ",  160, 180, 150, 20, NULL, 0.0, 0.0, 0, 0, "");
2407         }
2408         else {
2409                 uiBlockBeginAlign(block);
2410                 uiDefButBitS(block, TOG, V3D_DISPBGPIC, B_REDR, "Use", 10, 225, 50, 20, &vd->flag, 0, 0, 0, 0, "Display an image in the background of this 3D View");
2411                 uiDefButF(block, NUMSLI, B_REDR, "Blend:",      60, 225, 150, 20, &vd->bgpic->blend, 0.0,1.0, 0, 0, "Set the transparency of the background image");
2412                 uiDefButF(block, NUM, B_REDR, "Size:",          210, 225, 100, 20, &vd->bgpic->size, 0.1, 250.0*vd->grid, 100, 0, "Set the size (width) of the background image");
2413
2414                 uiDefButF(block, NUM, B_REDR, "X Offset:",      10, 205, 150, 20, &vd->bgpic->xof, -250.0*vd->grid,250.0*vd->grid, 10, 2, "Set the horizontal offset of the background image");
2415                 uiDefButF(block, NUM, B_REDR, "Y Offset:",      160, 205, 150, 20, &vd->bgpic->yof, -250.0*vd->grid,250.0*vd->grid, 10, 2, "Set the vertical offset of the background image");
2416                 
2417                 uiblock_image_panel(block, &vd->bgpic->ima, &vd->bgpic->iuser, B_REDR, B_REDR);
2418         }
2419 }
2420
2421
2422 static void view3d_panel_properties(short cntrl)        // VIEW3D_HANDLER_SETTINGS
2423 {
2424         uiBlock *block;
2425         View3D *vd;
2426         float *curs;
2427         
2428         vd= G.vd;
2429
2430         block= uiNewBlock(&curarea->uiblocks, "view3d_panel_properties", UI_EMBOSS, UI_HELV, curarea->win);
2431         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE  | cntrl);
2432         uiSetPanelHandler(VIEW3D_HANDLER_PROPERTIES);  // for close and esc
2433         if(uiNewPanel(curarea, block, "View Properties", "View3d", 340, 30, 318, 254)==0) return;
2434
2435         /* to force height */
2436         uiNewPanelHeight(block, 264);
2437
2438         if(G.f & (G_VERTEXPAINT|G_FACESELECT|G_TEXTUREPAINT|G_WEIGHTPAINT)) {
2439                 uiBlockSetFlag(block, UI_BLOCK_FRONTBUFFER);    // force old style frontbuffer draw
2440         }
2441
2442         uiDefBut(block, LABEL, 1, "Grid:",                                      10, 220, 150, 19, NULL, 0.0, 0.0, 0, 0, "");
2443         uiBlockBeginAlign(block);
2444         uiDefButF(block, NUM, REDRAWVIEW3D, "Spacing:",         10, 200, 140, 19, &vd->grid, 0.001, 100.0, 10, 0, "Set the distance between grid lines");
2445         uiDefButS(block, NUM, REDRAWVIEW3D, "Lines:",           10, 180, 140, 19, &vd->gridlines, 0.0, 100.0, 100, 0, "Set the number of grid lines in perspective view");
2446         uiDefButS(block, NUM, REDRAWVIEW3D, "Divisions:",               10, 160, 140, 19, &vd->gridsubdiv, 1.0, 100.0, 100, 0, "Set the number of grid lines");
2447         uiBlockEndAlign(block);
2448
2449         uiDefBut(block, LABEL, 1, "3D Display:",                                                        160, 220, 150, 19, NULL, 0.0, 0.0, 0, 0, "");
2450         uiDefButBitS(block, TOG, V3D_SHOW_FLOOR, REDRAWVIEW3D, "Grid Floor",160, 200, 150, 19, &vd->gridflag, 0, 0, 0, 0, "Show the grid floor in free camera mode");
2451         uiDefButBitS(block, TOG, V3D_SHOW_X, REDRAWVIEW3D, "X Axis",            160, 176, 48, 19, &vd->gridflag, 0, 0, 0, 0, "Show the X Axis line");
2452         uiDefButBitS(block, TOG, V3D_SHOW_Y, REDRAWVIEW3D, "Y Axis",            212, 176, 48, 19, &vd->gridflag, 0, 0, 0, 0, "Show the Y Axis line");
2453         uiDefButBitS(block, TOG, V3D_SHOW_Z, REDRAWVIEW3D, "Z Axis",            262, 176, 48, 19, &vd->gridflag, 0, 0, 0, 0, "Show the Z Axis line");
2454
2455         uiDefBut(block, LABEL, 1, "View Camera:",                       10, 140, 140, 19, NULL, 0.0, 0.0, 0, 0, "");
2456         
2457         uiDefButF(block, NUM, REDRAWVIEW3D, "Lens:",            10, 120, 140, 19, &vd->lens, 10.0, 120.0, 100, 0, "The lens angle in perspective view");
2458         uiBlockBeginAlign(block);
2459         uiDefButF(block, NUM, REDRAWVIEW3D, "Clip Start:",      10, 96, 140, 19, &vd->near, vd->grid/100.0, 100.0, 10, 0, "Set the beginning of the range in which 3D objects are displayed (perspective view)");
2460         uiDefButF(block, NUM, REDRAWVIEW3D, "Clip End:",        10, 76, 140, 19, &vd->far, 1.0, 10000.0*vd->grid, 100, 0, "Set the end of the range in which 3D objects are displayed (perspective view)");
2461         uiBlockEndAlign(block);
2462
2463         uiDefBut(block, LABEL, 1, "3D Cursor:",                         160, 150, 140, 19, NULL, 0.0, 0.0, 0, 0, "");
2464
2465         uiBlockBeginAlign(block);
2466         curs= give_cursor();
2467         uiDefButF(block, NUM, REDRAWVIEW3D, "X:",                       160, 130, 150, 22, curs, -10000.0*vd->grid, 10000.0*vd->grid, 10, 0, "X co-ordinate of the 3D cursor");
2468         uiDefButF(block, NUM, REDRAWVIEW3D, "Y:",                       160, 108, 150, 22, curs+1, -10000.0*vd->grid, 10000.0*vd->grid, 10, 0, "Y co-ordinate of the 3D cursor");
2469         uiDefButF(block, NUM, REDRAWVIEW3D, "Z:",                       160, 86, 150, 22, curs+2, -10000.0*vd->grid, 10000.0*vd->grid, 10, 0, "Z co-ordinate of the 3D cursor");
2470         uiBlockEndAlign(block);
2471
2472         uiDefBut(block, LABEL, 1, "Display:",                           10, 50, 150, 19, NULL, 0.0, 0.0, 0, 0, "");
2473         
2474         uiBlockBeginAlign(block);
2475         uiDefButBitS(block, TOG, V3D_SELECT_OUTLINE, REDRAWVIEW3D, "Outline Selected", 10, 30, 140, 19, &vd->flag, 0, 0, 0, 0, "Highlight selected objects with an outline, in Solid, Shaded or Textured viewport shading modes");
2476         uiDefButBitS(block, TOG, V3D_DRAW_CENTERS, REDRAWVIEW3D, "All Object Centers", 10, 10, 140, 19, &vd->flag, 0, 0, 0, 0, "Draw the center points on all objects");
2477         uiDefButBitS(block, TOGN, V3D_HIDE_HELPLINES, REDRAWVIEW3D, "Relationship Lines", 10, -10, 140, 19, &vd->flag, 0, 0, 0, 0, "Draw dashed lines indicating Parent, Constraint, or Hook relationships");
2478         uiDefButBitS(block, TOG, V3D_SOLID_TEX, REDRAWVIEW3D, "Solid Tex", 10, -30, 140, 19, &vd->flag2, 0, 0, 0, 0, "Display textures in Solid draw type (Shift T)");
2479         uiBlockEndAlign(block);
2480
2481         uiDefBut(block, LABEL, 1, "View Locking:",                              160, 50, 150, 19, NULL, 0.0, 0.0, 0, 0, "");
2482         uiBlockBeginAlign(block);
2483         uiDefIDPoinBut(block, test_obpoin_but, ID_OB, REDRAWVIEW3D, "Object:", 160, 30, 140, 19, &vd->ob_centre, "Lock view to center to this Object"); 
2484         uiDefBut(block, TEX, REDRAWVIEW3D, "Bone:",                                             160, 10, 140, 19, vd->ob_centre_bone, 1, 31, 0, 0, "If view locked to Object, use this Bone to lock to view to");
2485
2486 }
2487
2488 static void view3d_panel_preview(ScrArea *sa, short cntrl)      // VIEW3D_HANDLER_PREVIEW
2489 {
2490         uiBlock *block;
2491         View3D *v3d= sa->spacedata.first;
2492         int ofsx, ofsy;
2493         
2494         block= uiNewBlock(&sa->uiblocks, "view3d_panel_preview", UI_EMBOSS, UI_HELV, sa->win);
2495         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | UI_PNL_SCALE | cntrl);
2496         uiSetPanelHandler(VIEW3D_HANDLER_PREVIEW);  // for close and esc
2497         
2498         ofsx= -150+(sa->winx/2)/v3d->blockscale;
2499         ofsy= -100+(sa->winy/2)/v3d->blockscale;
2500         if(uiNewPanel(sa, block, "Preview", "View3d", ofsx, ofsy, 300, 200)==0) return;
2501
2502         uiBlockSetDrawExtraFunc(block, BIF_view3d_previewdraw);
2503         
2504         if(G.scene->recalc & SCE_PRV_CHANGED) {
2505                 G.scene->recalc &= ~SCE_PRV_CHANGED;
2506                 //printf("found recalc\n");
2507                 BIF_view3d_previewrender_free(sa->spacedata.first);
2508                 BIF_preview_changed(0);
2509         }
2510 }
2511
2512
2513 static void view3d_blockhandlers(ScrArea *sa)
2514 {
2515         View3D *v3d= sa->spacedata.first;
2516         short a;
2517         
2518         /* warning; blocks need to be freed each time, handlers dont remove */
2519         uiFreeBlocksWin(&sa->uiblocks, sa->win);
2520         
2521         /*uv face-sel and wp mode when mixed with wire leave depth enabled causing
2522         models to draw over the UI */
2523         glDisable(GL_DEPTH_TEST); 
2524         
2525         for(a=0; a<SPACE_MAXHANDLER; a+=2) {
2526         
2527                 switch(v3d->blockhandler[a]) {
2528
2529                 case VIEW3D_HANDLER_PROPERTIES:
2530                         view3d_panel_properties(v3d->blockhandler[a+1]);
2531                         break;
2532                 case VIEW3D_HANDLER_BACKGROUND:
2533                         view3d_panel_background(v3d->blockhandler[a+1]);
2534                         break;
2535                 case VIEW3D_HANDLER_OBJECT:
2536                         view3d_panel_object(v3d->blockhandler[a+1]);
2537                         break;
2538                 case VIEW3D_HANDLER_PREVIEW:
2539                         view3d_panel_preview(sa, v3d->blockhandler[a+1]);
2540                         break;                  
2541                 }
2542                 /* clear action value for event */
2543                 v3d->blockhandler[a+1]= 0;
2544         }
2545         uiDrawBlocksPanels(sa, 0);
2546
2547 }
2548
2549 /* ****************** View3d afterdraw *************** */
2550
2551 typedef struct View3DAfter {
2552         struct View3DAfter *next, *prev;
2553         struct Base *base;
2554         int type;
2555 } View3DAfter;
2556
2557 /* temp storage of Objects that need to be drawn as last */
2558 void add_view3d_after(View3D *v3d, Base *base, int type)
2559 {
2560         View3DAfter *v3da= MEM_callocN(sizeof(View3DAfter), "View 3d after");
2561
2562         BLI_addtail(&v3d->afterdraw, v3da);
2563         v3da->base= base;
2564         v3da->type= type;
2565 }
2566
2567 /* clears zbuffer and draws it over */
2568 static void view3d_draw_xray(View3D *v3d, int flag)
2569 {
2570         View3DAfter *v3da, *next;
2571         int doit= 0;
2572         
2573         for(v3da= v3d->afterdraw.first; v3da; v3da= v3da->next)
2574                 if(v3da->type==V3D_XRAY) doit= 1;
2575         
2576         if(doit) {
2577                 if(v3d->zbuf) glClear(GL_DEPTH_BUFFER_BIT);
2578                 v3d->xray= TRUE;
2579                 
2580                 for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
2581                         next= v3da->next;
2582                         if(v3da->type==V3D_XRAY) {
2583                                 draw_object(v3da->base, flag);
2584                                 BLI_remlink(&v3d->afterdraw, v3da);
2585                                 MEM_freeN(v3da);
2586                         }
2587                 }
2588                 v3d->xray= FALSE;
2589         }
2590 }
2591
2592 /* disables write in zbuffer and draws it over */
2593 static void view3d_draw_transp(View3D *v3d, int flag)
2594 {
2595         View3DAfter *v3da, *next;
2596
2597         glDepthMask(0);
2598         v3d->transp= TRUE;
2599                 
2600         for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
2601                 next= v3da->next;
2602                 if(v3da->type==V3D_TRANSP) {
2603                         draw_object(v3da->base, flag);
2604                         BLI_remlink(&v3d->afterdraw, v3da);
2605                         MEM_freeN(v3da);
2606                 }
2607         }
2608         v3d->transp= FALSE;
2609
2610         glDepthMask(1);
2611
2612 }
2613
2614 /* *********************** */
2615
2616 /*
2617         In most cases call draw_dupli_objects,
2618         draw_dupli_objects_color was added because when drawing set dupli's
2619         we need to force the color
2620 */
2621 static void draw_dupli_objects_color(View3D *v3d, Base *base, int color)
2622 {       
2623         ListBase *lb;
2624         DupliObject *dob;
2625         Base tbase;
2626         BoundBox *bb= NULL;
2627         GLuint displist=0;
2628         short transflag, use_displist= -1;      /* -1 is initialize */
2629         char dt, dtx;
2630         
2631         if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
2632         
2633         /* test if we can do a displist */
2634         if(base->object->transflag & OB_DUPLIGROUP)
2635                 use_displist= 0;
2636         
2637         tbase.flag= OB_FROMDUPLI|base->flag;
2638         lb= object_duplilist(G.scene, base->object);
2639
2640         for(dob= lb->first; dob; dob= dob->next) {
2641                 if(dob->no_draw);
2642                 else {
2643                         tbase.object= dob->ob;
2644                         
2645                         /* extra service: draw the duplicator in drawtype of parent */
2646                         dt= tbase.object->dt; tbase.object->dt= base->object->dt;
2647                         dtx= tbase.object->dtx; tbase.object->dtx= base->object->dtx;
2648                         
2649                         /* negative scale flag has to propagate */
2650                         transflag= tbase.object->transflag;
2651                         if(base->object->transflag & OB_NEG_SCALE)
2652                                 tbase.object->transflag ^= OB_NEG_SCALE;
2653                         
2654                         BIF_ThemeColorBlend(color, TH_BACK, 0.5);
2655                         
2656                         /* generate displist, test for new object */
2657                         if(use_displist==1 && dob->prev && dob->prev->ob!=dob->ob) {
2658                                 use_displist= -1;
2659                                 glDeleteLists(displist, 1);
2660                         }
2661                         /* generate displist */
2662                         if(use_displist == -1) {
2663                                 
2664                                 /* lamp drawing messes with matrices, could be handled smarter... but this works */
2665                                 if(dob->ob->type==OB_LAMP)
2666                                         use_displist= 0;
2667                                 else {
2668                                         /* disable boundbox check for list creation */
2669                                         object_boundbox_flag(dob->ob, OB_BB_DISABLED, 1);
2670                                         /* need this for next part of code */
2671                                         bb= object_get_boundbox(dob->ob);
2672                                         
2673                                         Mat4One(dob->ob->obmat);        /* obmat gets restored */
2674                                         
2675                                         displist= glGenLists(1);
2676                                         glNewList(displist, GL_COMPILE);
2677                                         draw_object(&tbase, DRAW_CONSTCOLOR);
2678                                         glEndList();
2679                                         
2680                                         use_displist= 1;
2681                                         object_boundbox_flag(dob->ob, OB_BB_DISABLED, 0);
2682                                 }
2683                         }
2684                         if(use_displist) {
2685                                 mymultmatrix(dob->mat);
2686                                 if(boundbox_clip(dob->mat, bb))
2687                                    glCallList(displist);
2688                                 myloadmatrix(G.vd->viewmat);
2689                         }
2690                         else {
2691                                 Mat4CpyMat4(dob->ob->obmat, dob->mat);
2692                                 draw_object(&tbase, DRAW_CONSTCOLOR);
2693                         }
2694                         
2695                         tbase.object->dt= dt;
2696                         tbase.object->dtx= dtx;
2697                         tbase.object->transflag= transflag;
2698                 }
2699         }
2700         
2701         /* Transp afterdraw disabled, afterdraw only stores base pointers, and duplis can be same obj */
2702         
2703         free_object_duplilist(lb);      /* does restore */
2704         
2705         if(use_displist)
2706                 glDeleteLists(displist, 1);
2707 }
2708
2709 static void draw_dupli_objects(View3D *v3d, Base *base)
2710 {
2711         /* define the color here so draw_dupli_objects_color can be called
2712          * from the set loop */
2713         
2714         int color= (base->flag & SELECT)?TH_SELECT:TH_WIRE;
2715         /* debug */
2716         if(base->object->dup_group && base->object->dup_group->id.us<1)
2717                 color= TH_REDALERT;
2718         
2719         draw_dupli_objects_color(v3d, base, color);
2720 }
2721
2722 void view3d_update_depths(View3D *v3d)
2723 {
2724         /* Create storage for, and, if necessary, copy depth buffer */
2725         if(!v3d->depths) v3d->depths= MEM_callocN(sizeof(ViewDepths),"ViewDepths");
2726         if(v3d->depths) {
2727                 ViewDepths *d= v3d->depths;
2728                 if(d->w != v3d->area->winx ||
2729                    d->h != v3d->area->winy ||
2730                    !d->depths) {
2731                         d->w= v3d->area->winx;
2732                         d->h= v3d->area->winy;
2733                         if(d->depths)
2734                                 MEM_freeN(d->depths);
2735                         d->depths= MEM_mallocN(sizeof(float)*d->w*d->h,"View depths");
2736                         d->damaged= 1;
2737                 }
2738                 
2739                 if(d->damaged) {
2740                         glReadPixels(v3d->area->winrct.xmin,v3d->area->winrct.ymin,d->w,d->h,
2741                                      GL_DEPTH_COMPONENT,GL_FLOAT, d->depths);
2742                         
2743                         glGetDoublev(GL_DEPTH_RANGE,d->depth_range);
2744                         
2745                         d->damaged= 0;
2746                 }
2747         }
2748 }
2749
2750 void drawview3dspace(ScrArea *sa, void *spacedata)
2751 {
2752         View3D *v3d= spacedata;
2753         Base *base;
2754         Object *ob;
2755         Scene *sce;
2756         char retopo, sculpt;
2757         Object *obact = OBACT;
2758         
2759         /* update all objects, ipos, matrices, displists, etc. Flags set by depgraph or manual, 
2760            no layer check here, gets correct flushed */
2761         /* sets first, we allow per definition current scene to have dependencies on sets */
2762         if(G.scene->set) {
2763                 for(SETLOOPER(G.scene->set, base))
2764                         object_handle_update(base->object);   // bke_object.h
2765         }
2766         for(base= G.scene->base.first; base; base= base->next)
2767                 object_handle_update(base->object);   // bke_object.h
2768         
2769         setwinmatrixview3d(sa->winx, sa->winy, NULL);   /* 0= no pick rect */
2770         setviewmatrixview3d();  /* note: calls where_is_object for camera... */
2771
2772         Mat4MulMat4(v3d->persmat, v3d->viewmat, sa->winmat);
2773         Mat4Invert(v3d->persinv, v3d->persmat);
2774         Mat4Invert(v3d->viewinv, v3d->viewmat);
2775
2776         /* calculate pixelsize factor once, is used for lamps and obcenters */
2777         {
2778                 float len1, len2, vec[3];
2779
2780                 VECCOPY(vec, v3d->persinv[0]);
2781                 len1= Normalize(vec);
2782                 VECCOPY(vec, v3d->persinv[1]);
2783                 len2= Normalize(vec);
2784                 
2785                 v3d->pixsize= 2.0f*(len1>len2?len1:len2);
2786                 
2787                 /* correct for window size */
2788                 if(sa->winx > sa->winy) v3d->pixsize/= (float)sa->winx;
2789                 else v3d->pixsize/= (float)sa->winy;
2790         }
2791         
2792         if(v3d->drawtype > OB_WIRE) {
2793                 if(G.f & G_SIMULATION)
2794                         glClearColor(0.0, 0.0, 0.0, 0.0); 
2795                 else {
2796                         float col[3];
2797                         BIF_GetThemeColor3fv(TH_BACK, col);
2798                         glClearColor(col[0], col[1], col[2], 0.0); 
2799                 }
2800                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2801                 
2802                 glLoadIdentity();
2803         }
2804         else {
2805                 float col[3];
2806                 BIF_GetThemeColor3fv(TH_BACK, col);
2807                 glClearColor(col[0], col[1], col[2], 0.0);
2808                 glClear(GL_COLOR_BUFFER_BIT);
2809         }
2810         
2811         myloadmatrix(v3d->viewmat);
2812         persp(PERSP_STORE);  // store correct view for persp(PERSP_VIEW) calls
2813
2814         if(v3d->flag & V3D_CLIPPING)
2815                 view3d_draw_clipping(v3d);
2816         
2817         /* set zbuffer after we draw clipping region */
2818         if(v3d->drawtype > OB_WIRE) {
2819                 v3d->zbuf= TRUE;
2820                 glEnable(GL_DEPTH_TEST);
2821         }
2822         
2823         // needs to be done always, gridview is adjusted in drawgrid() now
2824         v3d->gridview= v3d->grid;
2825         
2826         if(v3d->view==0 || v3d->persp!=0) {
2827                 drawfloor();
2828                 if(v3d->persp==2) {
2829                         if(G.scene->world) {
2830                                 if(G.scene->world->mode & WO_STARS) {
2831                                         RE_make_stars(NULL, star_stuff_init_func, star_stuff_vertex_func,
2832                                                                   star_stuff_term_func);
2833                                 }
2834                         }
2835                         if(v3d->flag & V3D_DISPBGPIC) draw_bgpic();
2836                 }
2837         }
2838         else {
2839                 drawgrid();
2840
2841                 if(v3d->flag & V3D_DISPBGPIC) {
2842                         draw_bgpic();
2843                 }
2844         }
2845         
2846         if(v3d->flag & V3D_CLIPPING)
2847                 view3d_set_clipping(v3d);
2848         
2849         /* draw set first */
2850         if(G.scene->set) {
2851                 for(SETLOOPER(G.scene->set, base)) {
2852                         
2853                         if(v3d->lay & base->lay) {
2854                                 
2855                                 BIF_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2856                                 draw_object(base, DRAW_CONSTCOLOR);
2857
2858                                 if(base->object->transflag & OB_DUPLI) {
2859                                         draw_dupli_objects_color(v3d, base, TH_WIRE);
2860                                 }
2861                         }
2862                 }
2863
2864                 /* Transp and X-ray afterdraw stuff */
2865                 view3d_draw_xray(v3d, DRAW_CONSTCOLOR); // clears zbuffer if it is used!
2866                 view3d_draw_transp(v3d, DRAW_CONSTCOLOR);
2867         }
2868         
2869         /* then draw not selected and the duplis, but skip editmode object */
2870         for(base= G.scene->base.first; base; base= base->next) {
2871                 if(v3d->lay & base->lay) {
2872                         
2873                         /* dupli drawing */
2874                         if(base->object->transflag & OB_DUPLI) {
2875                                 draw_dupli_objects(v3d, base);
2876                         }
2877                         if((base->flag & SELECT)==0) {
2878                                 if(base->object!=G.obedit) draw_object(base, 0);
2879                         }
2880                 }
2881         }
2882
2883         retopo= retopo_mesh_check() || retopo_curve_check();
2884         sculpt= (G.f & G_SCULPTMODE) && !G.obedit;
2885         if(retopo)
2886                 view3d_update_depths(v3d);
2887
2888         /* draw selected and editmode */
2889         for(base= G.scene->base.first; base; base= base->next) {
2890                 if(v3d->lay & base->lay) {
2891                         if (base->object==G.obedit || ( base->flag & SELECT) ) 
2892                                 draw_object(base, 0);
2893                 }
2894         }
2895
2896         if(!retopo && sculpt && !(obact && (obact->dtx & OB_DRAWXRAY)))
2897                 view3d_update_depths(v3d);
2898
2899         if(G.moving) {
2900                 BIF_drawConstraint();
2901                 if(G.obedit) BIF_drawPropCircle();      // only editmode has proportional edit
2902                 BIF_drawSnap();
2903         }
2904
2905         if(G.scene->radio) RAD_drawall(v3d->drawtype>=OB_SOLID);
2906         
2907         /* Transp and X-ray afterdraw stuff */
2908         view3d_draw_xray(v3d, 0);       // clears zbuffer if it is used!
2909         view3d_draw_transp(v3d, 0);
2910         
2911         if(!retopo && sculpt && (obact && (OBACT->dtx & OB_DRAWXRAY)))
2912                 view3d_update_depths(v3d);
2913         
2914         if(v3d->flag & V3D_CLIPPING)
2915                 view3d_clr_clipping();
2916         
2917         BIF_draw_manipulator(sa);
2918                 
2919         if(v3d->zbuf) {
2920                 v3d->zbuf= FALSE;
2921                 glDisable(GL_DEPTH_TEST);
2922         }
2923
2924         persp(PERSP_WIN);  // set ortho
2925
2926         /* Draw Sculpt Mode brush */
2927         if(!G.obedit && (G.f & G_SCULPTMODE) && area_is_active_area(v3d->area) && sculpt_session()) {
2928                 PropsetData *pd= sculpt_session()->propset;
2929                 short r1=100, r2=100, r3=100;
2930                 short mouse[2];
2931
2932                 if(sculpt_data()->flags & SCULPT_INPUT_SMOOTH)
2933                         sculpt_stroke_draw();
2934
2935                 if(pd) {
2936                         if(pd->mode == PropsetSize) {
2937                                 r1= sculptmode_brush()->size;
2938                                 r2= pd->origsize;
2939                                 r3= r1;
2940                         } else if(pd->mode == PropsetStrength) {
2941                                 r1= 200 - sculptmode_brush()->strength * 2;
2942                                 r2= 200;
2943                                 r3= 200;
2944                         } else if(pd->mode == PropsetTexRot) {
2945                                 r1= r2= 200;
2946                                 r3= 200;
2947                         }
2948                 
2949                         /* Draw brush with texture */
2950                         glEnable(GL_BLEND);
2951                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2952
2953                         glBindTexture(GL_TEXTURE_2D, pd->tex);
2954
2955                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2956                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2957                         
2958                         glPushMatrix();
2959                         glTranslatef(pd->origloc[0], pd->origloc[1], 0);
2960                         glRotatef(tex_angle(), 0, 0, 1);
2961
2962                         glEnable(GL_TEXTURE_2D);
2963                         glBegin(GL_QUADS);
2964                         glColor4f(0,0,0,1);
2965                         glTexCoord2f(0,0);
2966                         glVertex2f(-r3, -r3);
2967                         glTexCoord2f(1,0);
2968                         glVertex2f(r3, -r3);
2969                         glTexCoord2f(1,1);
2970                         glVertex2f(r3, r3);
2971                         glTexCoord2f(0,1);
2972                         glVertex2f(-r3, r3);
2973                         glEnd();
2974                         glDisable(GL_TEXTURE_2D);
2975                         
2976                         glPopMatrix();
2977
2978                         if(r1 != r2)
2979                                 fdrawXORcirc(pd->origloc[0], pd->origloc[1], r1);
2980                         fdrawXORcirc(pd->origloc[0], pd->origloc[1], r2);
2981                         
2982                         if(pd->mode == PropsetTexRot) {
2983                                 const float ang= pd->origtexrot * (M_PI/180.0f);
2984                                 getmouseco_areawin(mouse);
2985                                 sdrawXORline(pd->origloc[0], pd->origloc[1],
2986                                              pd->origloc[0]+200*cos(ang), pd->origloc[1]+200*sin(ang));
2987                                 sdrawXORline(pd->origloc[0], pd->origloc[1], mouse[0], mouse[1]);
2988                         }
2989                 }
2990                 else if(sculpt_data()->flags & SCULPT_DRAW_BRUSH) {
2991                         short csc[2], car[2];
2992                         getmouseco_sc(csc);
2993                         getmouseco_areawin(car);
2994                         if(csc[0] > v3d->area->winrct.xmin && 
2995                            csc[1] > v3d->area->winrct.ymin &&
2996                            csc[0] < v3d->area->winrct.xmax &&
2997                            csc[1] < v3d->area->winrct.ymax)
2998                                 fdrawXORcirc((float)car[0], (float)car[1], sculptmode_brush()->size);
2999                 }
3000         }
3001         retopo_draw_paint_lines();
3002
3003         if(v3d->persp>1) drawviewborder();
3004         if(v3d->flag2 & V3D_FLYMODE) drawviewborder_flymode();
3005         if(!(G.f & G_PLAYANIM)) drawcursor(v3d);
3006         if(U.uiflag & USER_SHOW_ROTVIEWICON)
3007                 draw_view_axis();
3008         else    
3009                 draw_view_icon();
3010         if(U.uiflag & USER_SHOW_VIEWPORTNAME)
3011                 draw_viewport_name(sa);
3012
3013         ob= OBACT;
3014         if(ob && (U.uiflag & USER_DRAWVIEWINFO)) 
3015                 draw_selected_name(ob);
3016         
3017         draw_area_emboss(sa);
3018         
3019         /* it is important to end a view in a transform compatible with buttons */
3020
3021         bwin_scalematrix(sa->win, v3d->blockscale, v3d->blockscale, v3d->blockscale);
3022         view3d_blockhandlers(sa);
3023
3024         sa->win_swap= WIN_BACK_OK;
3025         
3026         if(G.f & G_VERTEXPAINT || G.f & G_WEIGHTPAINT || G.f & G_TEXTUREPAINT) {
3027                 v3d->flag |= V3D_NEEDBACKBUFDRAW;
3028                 addafterqueue(sa->win, BACKBUFDRAW, 1);
3029         }
3030         // test for backbuf select
3031         if(G.obedit && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT)) {
3032                 extern int afterqtest(short win, unsigned short evt);   //editscreen.c
3033
3034                 v3d->flag |= V3D_NEEDBACKBUFDRAW;
3035                 if(afterqtest(sa->win, BACKBUFDRAW)==0) {
3036                         addafterqueue(sa->win, BACKBUFDRAW, 1);
3037                 }
3038         }
3039
3040         /* run any view3d draw handler script links */
3041         if (sa->scriptlink.totscript)
3042                 BPY_do_spacehandlers(sa, 0, SPACEHANDLER_VIEW3D_DRAW);
3043
3044         /* run scene redraw script links */
3045         if((G.f & G_DOSCRIPTLINKS) && G.scene->scriptlink.totscript &&
3046                         !during_script()) {
3047                 BPY_do_pyscript((ID *)G.scene, SCRIPT_REDRAW);
3048         }
3049         
3050 }
3051
3052
3053 void drawview3d_render(struct View3D *v3d, int winx, int winy)
3054 {
3055         Base *base;
3056         Scene *sce;
3057         float winmat[4][4];
3058         
3059         update_for_newframe_muted();    /* first, since camera can be animated */
3060
3061         setwinmatrixview3d(winx, winy, NULL);
3062         
3063         setviewmatrixview3d();
3064         myloadmatrix(v3d->viewmat);
3065         glMatrixMode(GL_PROJECTION);
3066         mygetmatrix(winmat);
3067         glMatrixMode(GL_MODELVIEW);
3068         Mat4MulMat4(v3d->persmat, v3d->viewmat, winmat);
3069         Mat4Invert(v3d->persinv, v3d->persmat);
3070         Mat4Invert(v3d->viewinv, v3d->viewmat);
3071
3072         free_all_realtime_images();
3073         reshadeall_displist();
3074         
3075         if(v3d->drawtype > OB_WIRE) {
3076                 v3d->zbuf= TRUE;
3077                 glEnable(GL_DEPTH_TEST);
3078         }
3079
3080         if(v3d->flag & V3D_CLIPPING)
3081                 view3d_set_clipping(v3d);
3082
3083         if (v3d->drawtype==OB_TEXTURE && G.scene->world) {
3084                 glClearColor(G.scene->world->horr, G.scene->world->horg, G.scene->world->horb, 0.0); 
3085         } else {
3086                 float col[3];
3087                 BIF_GetThemeColor3fv(TH_BACK, col);
3088                 glClearColor(col[0], col[1], col[2], 0.0); 
3089         }
3090         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
3091
3092         /* abuse! to make sure it doesnt draw the helpstuff */
3093         G.f |= G_SIMULATION;
3094
3095         /* first draw set */
3096         if(G.scene->set) {
3097         
3098                 for(SETLOOPER(G.scene->set, base)) {
3099                         if(v3d->lay & base->lay) {
3100                                 if ELEM3(base->object->type, OB_LAMP, OB_CAMERA, OB_LATTICE);
3101                                 else {
3102                                         where_is_object(base->object);
3103         
3104                                         BIF_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
3105                                         draw_object(base, DRAW_CONSTCOLOR);
3106         
3107                                         if(base->object->transflag & OB_DUPLI) {
3108                                                 draw_dupli_objects(v3d, base);
3109                                         }
3110                                 }
3111                         }
3112                 }
3113                 
3114                 /* Transp and X-ray afterdraw stuff */
3115                 view3d_draw_xray(v3d, DRAW_CONSTCOLOR); // clears zbuffer if it is used!
3116                 view3d_draw_transp(v3d, DRAW_CONSTCOLOR);
3117         }
3118
3119         /* first not selected and duplis */
3120         base= G.scene->base.first;
3121         while(base) {
3122                 
3123                 if(v3d->lay & base->lay) {
3124                         if ELEM3(base->object->type, OB_LAMP, OB_CAMERA, OB_LATTICE);
3125                         else {
3126         
3127                                 if(base->object->transflag & OB_DUPLI) {
3128                                         draw_dupli_objects(v3d, base);
3129                                 }
3130                                 else if((base->flag & SELECT)==0) {
3131                                         draw_object(base, 0);
3132                                 }
3133                         }
3134                 }
3135                 
3136                 base= base->next;
3137         }
3138
3139         /* draw selected */
3140         base= G.scene->base.first;
3141         while(base) {
3142                 
3143                 if ( ((base)->flag & SELECT) && ((base)->lay & v3d->lay) ) {
3144                         if ELEM3(base->object->type, OB_LAMP, OB_CAMERA, OB_LATTICE);
3145                         else draw_object(base, 0);
3146                 }
3147                 
3148                 base= base->next;
3149         }
3150
3151         if(G.scene->radio) RAD_drawall(v3d->drawtype>=OB_SOLID);
3152
3153         /* Transp and X-ray afterdraw stuff */
3154         view3d_draw_xray(v3d, 0);       // clears zbuffer if it is used!
3155         view3d_draw_transp(v3d, 0);
3156         
3157         if(v3d->flag & V3D_CLIPPING)
3158                 view3d_clr_clipping();
3159         
3160         if(v3d->zbuf) {
3161                 v3d->zbuf= FALSE;
3162                 glDisable(GL_DEPTH_TEST);
3163         }
3164         
3165         G.f &= ~G_SIMULATION;
3166
3167         glFlush();
3168
3169         glLoadIdentity();