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