]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/xywindow.cpp
m1 selector
[xonotic/netradiant.git] / radiant / xywindow.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 //
23 // XY Window
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 #include "xywindow.h"
29
30 #include "debugging/debugging.h"
31
32 #include "ientity.h"
33 #include "igl.h"
34 #include "ibrush.h"
35 #include "iundo.h"
36 #include "iimage.h"
37 #include "ifilesystem.h"
38 #include "os/path.h"
39 #include "image.h"
40 #include "gtkutil/messagebox.h"
41
42 #include <gtk/gtklabel.h>
43 #include <gtk/gtkmenuitem.h>
44
45 #include "generic/callback.h"
46 #include "string/string.h"
47 #include "stream/stringstream.h"
48
49 #include "scenelib.h"
50 #include "eclasslib.h"
51 #include "renderer.h"
52 #include "moduleobserver.h"
53
54 #include "gtkutil/menu.h"
55 #include "gtkutil/container.h"
56 #include "gtkutil/widget.h"
57 #include "gtkutil/glwidget.h"
58 #include "gtkutil/filechooser.h"
59 #include "gtkmisc.h"
60 #include "select.h"
61 #include "csg.h"
62 #include "brushmanip.h"
63 #include "selection.h"
64 #include "entity.h"
65 #include "camwindow.h"
66 #include "texwindow.h"
67 #include "mainframe.h"
68 #include "preferences.h"
69 #include "commands.h"
70 #include "feedback.h"
71 #include "grid.h"
72 #include "windowobservers.h"
73
74 void LoadTextureRGBA( qtexture_t* q, unsigned char* pPixels, int nWidth, int nHeight );
75
76 // d1223m
77 extern bool g_brush_always_caulk;
78
79 //!\todo Rewrite.
80 class ClipPoint
81 {
82 public:
83 Vector3 m_ptClip;        // the 3d point
84 bool m_bSet;
85
86 ClipPoint(){
87         Reset();
88 };
89 void Reset(){
90         m_ptClip[0] = m_ptClip[1] = m_ptClip[2] = 0.0;
91         m_bSet = false;
92 }
93 bool Set(){
94         return m_bSet;
95 }
96 void Set( bool b ){
97         m_bSet = b;
98 }
99 operator Vector3&()
100 {
101         return m_ptClip;
102 };
103
104 /*! Draw clip/path point with rasterized number label */
105 void Draw( int num, float scale );
106 /*! Draw clip/path point with rasterized string label */
107 void Draw( const char *label, float scale );
108 };
109
110 VIEWTYPE g_clip_viewtype;
111 bool g_bSwitch = true;
112 bool g_clip_useCaulk = false;
113 ClipPoint g_Clip1;
114 ClipPoint g_Clip2;
115 ClipPoint g_Clip3;
116 ClipPoint* g_pMovingClip = 0;
117
118 /* Drawing clip points */
119 void ClipPoint::Draw( int num, float scale ){
120         StringOutputStream label( 4 );
121         label << num;
122         Draw( label.c_str(), scale );
123 }
124
125 void ClipPoint::Draw( const char *label, float scale ){
126         // draw point
127         glPointSize( 4 );
128         glColor3fv( vector3_to_array( g_xywindow_globals.color_clipper ) );
129         glBegin( GL_POINTS );
130         glVertex3fv( vector3_to_array( m_ptClip ) );
131         glEnd();
132         glPointSize( 1 );
133
134         float offset = 2.0f / scale;
135
136         // draw label
137         glRasterPos3f( m_ptClip[0] + offset, m_ptClip[1] + offset, m_ptClip[2] + offset );
138         glCallLists( GLsizei( strlen( label ) ), GL_UNSIGNED_BYTE, label );
139 }
140
141 float fDiff( float f1, float f2 ){
142         if ( f1 > f2 ) {
143                 return f1 - f2;
144         }
145         else{
146                 return f2 - f1;
147         }
148 }
149
150 inline double ClipPoint_Intersect( const ClipPoint& clip, const Vector3& point, VIEWTYPE viewtype, float scale ){
151         int nDim1 = ( viewtype == YZ ) ? 1 : 0;
152         int nDim2 = ( viewtype == XY ) ? 1 : 2;
153         double screenDistanceSquared( vector2_length_squared( Vector2( fDiff( clip.m_ptClip[nDim1], point[nDim1] ) * scale, fDiff( clip.m_ptClip[nDim2], point[nDim2] )  * scale ) ) );
154         if ( screenDistanceSquared < 8 * 8 ) {
155                 return screenDistanceSquared;
156         }
157         return FLT_MAX;
158 }
159
160 inline void ClipPoint_testSelect( ClipPoint& clip, const Vector3& point, VIEWTYPE viewtype, float scale, double& bestDistance, ClipPoint*& bestClip ){
161         if ( clip.Set() ) {
162                 double distance = ClipPoint_Intersect( clip, point, viewtype, scale );
163                 if ( distance < bestDistance ) {
164                         bestDistance = distance;
165                         bestClip = &clip;
166                 }
167         }
168 }
169
170 inline ClipPoint* GlobalClipPoints_Find( const Vector3& point, VIEWTYPE viewtype, float scale ){
171         double bestDistance = FLT_MAX;
172         ClipPoint* bestClip = 0;
173         ClipPoint_testSelect( g_Clip1, point, viewtype, scale, bestDistance, bestClip );
174         ClipPoint_testSelect( g_Clip2, point, viewtype, scale, bestDistance, bestClip );
175         ClipPoint_testSelect( g_Clip3, point, viewtype, scale, bestDistance, bestClip );
176         return bestClip;
177 }
178
179 inline void GlobalClipPoints_Draw( float scale ){
180         // Draw clip points
181         if ( g_Clip1.Set() ) {
182                 g_Clip1.Draw( 1, scale );
183         }
184         if ( g_Clip2.Set() ) {
185                 g_Clip2.Draw( 2, scale );
186         }
187         if ( g_Clip3.Set() ) {
188                 g_Clip3.Draw( 3, scale );
189         }
190 }
191
192 inline bool GlobalClipPoints_valid(){
193         return g_Clip1.Set() && g_Clip2.Set();
194 }
195
196 void PlanePointsFromClipPoints( Vector3 planepts[3], const AABB& bounds, int viewtype ){
197         ASSERT_MESSAGE( GlobalClipPoints_valid(), "clipper points not initialised" );
198         planepts[0] = g_Clip1.m_ptClip;
199         planepts[1] = g_Clip2.m_ptClip;
200         planepts[2] = g_Clip3.m_ptClip;
201         Vector3 maxs( vector3_added( bounds.origin, bounds.extents ) );
202         Vector3 mins( vector3_subtracted( bounds.origin, bounds.extents ) );
203         if ( !g_Clip3.Set() ) {
204                 int n = ( viewtype == XY ) ? 2 : ( viewtype == YZ ) ? 0 : 1;
205                 int x = ( n == 0 ) ? 1 : 0;
206                 int y = ( n == 2 ) ? 1 : 2;
207
208                 if ( n == 1 ) { // on viewtype XZ, flip clip points
209                         planepts[0][n] = maxs[n];
210                         planepts[1][n] = maxs[n];
211                         planepts[2][x] = g_Clip1.m_ptClip[x];
212                         planepts[2][y] = g_Clip1.m_ptClip[y];
213                         planepts[2][n] = mins[n];
214                 }
215                 else
216                 {
217                         planepts[0][n] = mins[n];
218                         planepts[1][n] = mins[n];
219                         planepts[2][x] = g_Clip1.m_ptClip[x];
220                         planepts[2][y] = g_Clip1.m_ptClip[y];
221                         planepts[2][n] = maxs[n];
222                 }
223         }
224 }
225
226 void Clip_Update(){
227         Vector3 planepts[3];
228         if ( !GlobalClipPoints_valid() ) {
229                 planepts[0] = Vector3( 0, 0, 0 );
230                 planepts[1] = Vector3( 0, 0, 0 );
231                 planepts[2] = Vector3( 0, 0, 0 );
232                 Scene_BrushSetClipPlane( GlobalSceneGraph(), Plane3( 0, 0, 0, 0 ) );
233         }
234         else
235         {
236                 AABB bounds( Vector3( 0, 0, 0 ), Vector3( 64, 64, 64 ) );
237                 PlanePointsFromClipPoints( planepts, bounds, g_clip_viewtype );
238                 if ( g_bSwitch ) {
239                         std::swap( planepts[0], planepts[1] );
240                 }
241                 Scene_BrushSetClipPlane( GlobalSceneGraph(), plane3_for_points( planepts[0], planepts[1], planepts[2] ) );
242         }
243         ClipperChangeNotify();
244 }
245
246 const char* Clip_getShader(){
247         return g_clip_useCaulk ? "textures/common/caulk" : TextureBrowser_GetSelectedShader( GlobalTextureBrowser() );
248 }
249
250 void Clip(){
251         if ( ClipMode() && GlobalClipPoints_valid() ) {
252                 Vector3 planepts[3];
253                 AABB bounds( Vector3( 0, 0, 0 ), Vector3( 64, 64, 64 ) );
254                 PlanePointsFromClipPoints( planepts, bounds, g_clip_viewtype );
255                 Scene_BrushSplitByPlane( GlobalSceneGraph(), planepts[0], planepts[1], planepts[2], Clip_getShader(), ( !g_bSwitch ) ? eFront : eBack );
256                 g_Clip1.Reset();
257                 g_Clip2.Reset();
258                 g_Clip3.Reset();
259                 Clip_Update();
260                 ClipperChangeNotify();
261         }
262 }
263
264 void SplitClip(){
265         if ( ClipMode() && GlobalClipPoints_valid() ) {
266                 Vector3 planepts[3];
267                 AABB bounds( Vector3( 0, 0, 0 ), Vector3( 64, 64, 64 ) );
268                 PlanePointsFromClipPoints( planepts, bounds, g_clip_viewtype );
269                 Scene_BrushSplitByPlane( GlobalSceneGraph(), planepts[0], planepts[1], planepts[2], Clip_getShader(), eFrontAndBack );
270                 g_Clip1.Reset();
271                 g_Clip2.Reset();
272                 g_Clip3.Reset();
273                 Clip_Update();
274                 ClipperChangeNotify();
275         }
276 }
277
278 void FlipClip(){
279         g_bSwitch = !g_bSwitch;
280         Clip_Update();
281         ClipperChangeNotify();
282 }
283
284 void OnClipMode( bool enabled ){
285         g_Clip1.Reset();
286         g_Clip2.Reset();
287         g_Clip3.Reset();
288
289         if ( !enabled && g_pMovingClip ) {
290                 g_pMovingClip = 0;
291         }
292
293         Clip_Update();
294         ClipperChangeNotify();
295 }
296
297 bool ClipMode(){
298         return GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip;
299 }
300
301 void NewClipPoint( const Vector3& point ){
302         if ( g_Clip1.Set() == false ) {
303                 g_Clip1.m_ptClip = point;
304                 g_Clip1.Set( true );
305         }
306         else if ( g_Clip2.Set() == false ) {
307                 g_Clip2.m_ptClip = point;
308                 g_Clip2.Set( true );
309         }
310         else if ( g_Clip3.Set() == false ) {
311                 g_Clip3.m_ptClip = point;
312                 g_Clip3.Set( true );
313         }
314         else
315         {
316                 g_Clip1.Reset();
317                 g_Clip2.Reset();
318                 g_Clip3.Reset();
319                 g_Clip1.m_ptClip = point;
320                 g_Clip1.Set( true );
321         }
322
323         Clip_Update();
324         ClipperChangeNotify();
325 }
326
327
328
329 struct xywindow_globals_private_t
330 {
331         bool d_showgrid;
332
333         // these are in the View > Show menu with Show coordinates
334         bool show_names;
335         bool show_coordinates;
336         bool show_angles;
337         bool show_outline;
338         bool show_axis;
339
340         bool d_show_work;
341
342         bool show_blocks;
343         int blockSize;
344
345         bool m_bCamXYUpdate;
346         bool m_bChaseMouse;
347         bool m_bSizePaint;
348
349         xywindow_globals_private_t() :
350                 d_showgrid( true ),
351
352                 show_names( false ),
353                 show_coordinates( true ),
354                 show_angles( true ),
355                 show_outline( false ),
356                 show_axis( true ),
357
358                 d_show_work( false ),
359
360                 show_blocks( false ),
361
362                 m_bCamXYUpdate( true ),
363                 m_bChaseMouse( true ),
364                 m_bSizePaint( true ){
365         }
366
367 };
368
369 xywindow_globals_t g_xywindow_globals;
370 xywindow_globals_private_t g_xywindow_globals_private;
371
372 const unsigned int RAD_NONE =    0x00;
373 const unsigned int RAD_SHIFT =   0x01;
374 const unsigned int RAD_ALT =     0x02;
375 const unsigned int RAD_CONTROL = 0x04;
376 const unsigned int RAD_PRESS   = 0x08;
377 const unsigned int RAD_LBUTTON = 0x10;
378 const unsigned int RAD_MBUTTON = 0x20;
379 const unsigned int RAD_RBUTTON = 0x40;
380
381 inline ButtonIdentifier button_for_flags( unsigned int flags ){
382         if ( flags & RAD_LBUTTON ) {
383                 return c_buttonLeft;
384         }
385         if ( flags & RAD_RBUTTON ) {
386                 return c_buttonRight;
387         }
388         if ( flags & RAD_MBUTTON ) {
389                 return c_buttonMiddle;
390         }
391         return c_buttonInvalid;
392 }
393
394 inline ModifierFlags modifiers_for_flags( unsigned int flags ){
395         ModifierFlags modifiers = c_modifierNone;
396         if ( flags & RAD_SHIFT ) {
397                 modifiers |= c_modifierShift;
398         }
399         if ( flags & RAD_CONTROL ) {
400                 modifiers |= c_modifierControl;
401         }
402         if ( flags & RAD_ALT ) {
403                 modifiers |= c_modifierAlt;
404         }
405         return modifiers;
406 }
407
408 inline unsigned int buttons_for_button_and_modifiers( ButtonIdentifier button, ModifierFlags flags ){
409         unsigned int buttons = 0;
410
411         switch ( button.get() )
412         {
413         case ButtonEnumeration::LEFT: buttons |= RAD_LBUTTON; break;
414         case ButtonEnumeration::MIDDLE: buttons |= RAD_MBUTTON; break;
415         case ButtonEnumeration::RIGHT: buttons |= RAD_RBUTTON; break;
416         }
417
418         if ( bitfield_enabled( flags, c_modifierControl ) ) {
419                 buttons |= RAD_CONTROL;
420         }
421
422         if ( bitfield_enabled( flags, c_modifierShift ) ) {
423                 buttons |= RAD_SHIFT;
424         }
425
426         if ( bitfield_enabled( flags, c_modifierAlt ) ) {
427                 buttons |= RAD_ALT;
428         }
429
430         return buttons;
431 }
432
433 inline unsigned int buttons_for_event_button( GdkEventButton* event ){
434         unsigned int flags = 0;
435
436         switch ( event->button )
437         {
438         case 1: flags |= RAD_LBUTTON; break;
439         case 2: flags |= RAD_MBUTTON; break;
440         case 3: flags |= RAD_RBUTTON; break;
441         }
442
443         if ( ( event->state & GDK_CONTROL_MASK ) != 0 ) {
444                 flags |= RAD_CONTROL;
445         }
446
447         if ( ( event->state & GDK_SHIFT_MASK ) != 0 ) {
448                 flags |= RAD_SHIFT;
449         }
450
451         if ( ( event->state & GDK_MOD1_MASK ) != 0 ) {
452                 flags |= RAD_ALT;
453         }
454
455         return flags;
456 }
457
458 inline unsigned int buttons_for_state( guint state ){
459         unsigned int flags = 0;
460
461         if ( ( state & GDK_BUTTON1_MASK ) != 0 ) {
462                 flags |= RAD_LBUTTON;
463         }
464
465         if ( ( state & GDK_BUTTON2_MASK ) != 0 ) {
466                 flags |= RAD_MBUTTON;
467         }
468
469         if ( ( state & GDK_BUTTON3_MASK ) != 0 ) {
470                 flags |= RAD_RBUTTON;
471         }
472
473         if ( ( state & GDK_CONTROL_MASK ) != 0 ) {
474                 flags |= RAD_CONTROL;
475         }
476
477         if ( ( state & GDK_SHIFT_MASK ) != 0 ) {
478                 flags |= RAD_SHIFT;
479         }
480
481         if ( ( state & GDK_MOD1_MASK ) != 0 ) {
482                 flags |= RAD_ALT;
483         }
484
485         return flags;
486 }
487
488
489 void XYWnd::SetScale( float f ){
490         m_fScale = f;
491         updateProjection();
492         updateModelview();
493         XYWnd_Update( *this );
494 }
495
496 void XYWnd::ZoomIn(){
497         float max_scale = 64;
498         float scale = Scale() * 5.0f / 4.0f;
499         if ( scale > max_scale ) {
500                 if ( Scale() != max_scale ) {
501                         SetScale( max_scale );
502                 }
503         }
504         else
505         {
506                 SetScale( scale );
507         }
508 }
509
510
511 // NOTE: the zoom out factor is 4/5, we could think about customizing it
512 //  we don't go below a zoom factor corresponding to 10% of the max world size
513 //  (this has to be computed against the window size)
514 void XYWnd::ZoomOut(){
515         float min_scale = MIN( Width(), Height() ) / ( 1.1f * ( g_MaxWorldCoord - g_MinWorldCoord ) );
516         float scale = Scale() * 4.0f / 5.0f;
517         if ( scale < min_scale ) {
518                 if ( Scale() != min_scale ) {
519                         SetScale( min_scale );
520                 }
521         }
522         else
523         {
524                 SetScale( scale );
525         }
526 }
527
528 void XYWnd::ZoomInWithMouse( int pointx, int pointy ){
529         float old_scale = Scale();
530         ZoomIn();
531         if ( g_xywindow_globals.m_bImprovedWheelZoom ) {
532                 float scale_diff = 1.0 / old_scale - 1.0 / Scale();
533                 int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
534                 int nDim2 = ( m_viewType == XY ) ? 1 : 2;
535                 Vector3 origin = GetOrigin();
536                 origin[nDim1] += scale_diff * (pointx - 0.5 * Width());
537                 origin[nDim2] -= scale_diff * (pointy - 0.5 * Height());
538                 SetOrigin( origin );
539         }
540 }
541
542 VIEWTYPE GlobalXYWnd_getCurrentViewType(){
543         ASSERT_NOTNULL( g_pParentWnd );
544         ASSERT_NOTNULL( g_pParentWnd->ActiveXY() );
545         return g_pParentWnd->ActiveXY()->GetViewType();
546 }
547
548 // =============================================================================
549 // variables
550
551 bool g_bCrossHairs = false;
552
553 GtkMenu* XYWnd::m_mnuDrop = 0;
554
555 // this is disabled, and broken
556 // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=394
557 #if 0
558 void WXY_Print(){
559         long width, height;
560         width = g_pParentWnd->ActiveXY()->Width();
561         height = g_pParentWnd->ActiveXY()->Height();
562         unsigned char* img;
563         const char* filename;
564
565         filename = file_dialog( GTK_WIDGET( MainFrame_getWindow() ), FALSE, "Save Image", 0, FILTER_BMP );
566         if ( !filename ) {
567                 return;
568         }
569
570         g_pParentWnd->ActiveXY()->MakeCurrent();
571         img = (unsigned char*)malloc( width * height * 3 );
572         glReadPixels( 0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,img );
573
574         FILE *fp;
575         fp = fopen( filename, "wb" );
576         if ( fp ) {
577                 unsigned short bits;
578                 unsigned long cmap, bfSize;
579
580                 bits = 24;
581                 cmap = 0;
582                 bfSize = 54 + width * height * 3;
583
584                 long byteswritten = 0;
585                 long pixoff = 54 + cmap * 4;
586                 short res = 0;
587                 char m1 = 'B', m2 = 'M';
588                 fwrite( &m1, 1, 1, fp );      byteswritten++; // B
589                 fwrite( &m2, 1, 1, fp );      byteswritten++; // M
590                 fwrite( &bfSize, 4, 1, fp );  byteswritten += 4; // bfSize
591                 fwrite( &res, 2, 1, fp );     byteswritten += 2; // bfReserved1
592                 fwrite( &res, 2, 1, fp );     byteswritten += 2; // bfReserved2
593                 fwrite( &pixoff, 4, 1, fp );  byteswritten += 4; // bfOffBits
594
595                 unsigned long biSize = 40, compress = 0, size = 0;
596                 long pixels = 0;
597                 unsigned short planes = 1;
598                 fwrite( &biSize, 4, 1, fp );  byteswritten += 4; // biSize
599                 fwrite( &width, 4, 1, fp );   byteswritten += 4; // biWidth
600                 fwrite( &height, 4, 1, fp );  byteswritten += 4; // biHeight
601                 fwrite( &planes, 2, 1, fp );  byteswritten += 2; // biPlanes
602                 fwrite( &bits, 2, 1, fp );    byteswritten += 2; // biBitCount
603                 fwrite( &compress, 4, 1, fp ); byteswritten += 4; // biCompression
604                 fwrite( &size, 4, 1, fp );    byteswritten += 4; // biSizeImage
605                 fwrite( &pixels, 4, 1, fp );  byteswritten += 4; // biXPelsPerMeter
606                 fwrite( &pixels, 4, 1, fp );  byteswritten += 4; // biYPelsPerMeter
607                 fwrite( &cmap, 4, 1, fp );    byteswritten += 4; // biClrUsed
608                 fwrite( &cmap, 4, 1, fp );    byteswritten += 4; // biClrImportant
609
610                 unsigned long widthDW = ( ( ( width * 24 ) + 31 ) / 32 * 4 );
611                 long row, row_size = width * 3;
612                 for ( row = 0; row < height; row++ )
613                 {
614                         unsigned char* buf = img + row * row_size;
615
616                         // write a row
617                         int col;
618                         for ( col = 0; col < row_size; col += 3 )
619                         {
620                                 putc( buf[col + 2], fp );
621                                 putc( buf[col + 1], fp );
622                                 putc( buf[col], fp );
623                         }
624                         byteswritten += row_size;
625
626                         unsigned long count;
627                         for ( count = row_size; count < widthDW; count++ )
628                         {
629                                 putc( 0, fp ); // dummy
630                                 byteswritten++;
631                         }
632                 }
633
634                 fclose( fp );
635         }
636
637         free( img );
638 }
639 #endif
640
641
642 #include "timer.h"
643
644 Timer g_chasemouse_timer;
645
646 void XYWnd::ChaseMouse(){
647         float multiplier = g_chasemouse_timer.elapsed_msec() / 10.0f;
648         Scroll( float_to_integer( multiplier * m_chasemouse_delta_x ), float_to_integer( multiplier * -m_chasemouse_delta_y ) );
649
650         //globalOutputStream() << "chasemouse: multiplier=" << multiplier << " x=" << m_chasemouse_delta_x << " y=" << m_chasemouse_delta_y << '\n';
651
652         XY_MouseMoved( m_chasemouse_current_x, m_chasemouse_current_y, getButtonState() );
653         g_chasemouse_timer.start();
654 }
655
656 gboolean xywnd_chasemouse( gpointer data ){
657         reinterpret_cast<XYWnd*>( data )->ChaseMouse();
658         return TRUE;
659 }
660
661 inline const int& min_int( const int& left, const int& right ){
662         return std::min( left, right );
663 }
664
665 bool XYWnd::chaseMouseMotion( int pointx, int pointy ){
666         m_chasemouse_delta_x = 0;
667         m_chasemouse_delta_y = 0;
668
669         if ( g_xywindow_globals_private.m_bChaseMouse && getButtonState() == RAD_LBUTTON ) {
670                 const int epsilon = 16;
671
672                 if ( pointx < epsilon ) {
673                         m_chasemouse_delta_x = std::max( pointx, 0 ) - epsilon;
674                 }
675                 else if ( ( pointx - m_nWidth ) > -epsilon ) {
676                         m_chasemouse_delta_x = min_int( ( pointx - m_nWidth ), 0 ) + epsilon;
677                 }
678
679                 if ( pointy < epsilon ) {
680                         m_chasemouse_delta_y = std::max( pointy, 0 ) - epsilon;
681                 }
682                 else if ( ( pointy - m_nHeight ) > -epsilon ) {
683                         m_chasemouse_delta_y = min_int( ( pointy - m_nHeight ), 0 ) + epsilon;
684                 }
685
686                 if ( m_chasemouse_delta_y != 0 || m_chasemouse_delta_x != 0 ) {
687                         //globalOutputStream() << "chasemouse motion: x=" << pointx << " y=" << pointy << "... ";
688                         m_chasemouse_current_x = pointx;
689                         m_chasemouse_current_y = pointy;
690                         if ( m_chasemouse_handler == 0 ) {
691                                 //globalOutputStream() << "chasemouse timer start... ";
692                                 g_chasemouse_timer.start();
693                                 m_chasemouse_handler = g_idle_add( xywnd_chasemouse, this );
694                         }
695                         return true;
696                 }
697                 else
698                 {
699                         if ( m_chasemouse_handler != 0 ) {
700                                 //globalOutputStream() << "chasemouse cancel\n";
701                                 g_source_remove( m_chasemouse_handler );
702                                 m_chasemouse_handler = 0;
703                         }
704                 }
705         }
706         else
707         {
708                 if ( m_chasemouse_handler != 0 ) {
709                         //globalOutputStream() << "chasemouse cancel\n";
710                         g_source_remove( m_chasemouse_handler );
711                         m_chasemouse_handler = 0;
712                 }
713         }
714         return false;
715 }
716
717 // =============================================================================
718 // XYWnd class
719 Shader* XYWnd::m_state_selected = 0;
720
721 void xy_update_xor_rectangle( XYWnd& self, rect_t area ){
722         if ( GTK_WIDGET_VISIBLE( self.GetWidget() ) ) {
723                 rectangle_t rect = rectangle_from_area( area.min, area.max, self.Width(), self.Height() );
724                 int nDim1 = ( self.GetViewType() == YZ ) ? 1 : 0;
725                 int nDim2 = ( self.GetViewType() == XY ) ? 1 : 2;
726                 rect.x /= self.Scale();
727                 rect.y /= self.Scale();
728                 rect.w /= self.Scale();
729                 rect.h /= self.Scale();
730                 rect.x += self.GetOrigin()[nDim1];
731                 rect.y += self.GetOrigin()[nDim2];
732                 self.m_XORRectangle.set( rect );
733         }
734 }
735
736 gboolean xywnd_button_press( GtkWidget* widget, GdkEventButton* event, XYWnd* xywnd ){
737         if ( event->type == GDK_BUTTON_PRESS ) {
738                 g_pParentWnd->SetActiveXY( xywnd );
739
740                 xywnd->ButtonState_onMouseDown( buttons_for_event_button( event ) );
741
742                 xywnd->onMouseDown( WindowVector( event->x, event->y ), button_for_button( event->button ), modifiers_for_state( event->state ) );
743         }
744         return FALSE;
745 }
746
747 gboolean xywnd_button_release( GtkWidget* widget, GdkEventButton* event, XYWnd* xywnd ){
748         if ( event->type == GDK_BUTTON_RELEASE ) {
749                 xywnd->XY_MouseUp( static_cast<int>( event->x ), static_cast<int>( event->y ), buttons_for_event_button( event ) );
750
751                 xywnd->ButtonState_onMouseUp( buttons_for_event_button( event ) );
752         }
753         return FALSE;
754 }
755
756 gboolean xywnd_focus_in( GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd ){
757         if ( event->type == GDK_FOCUS_CHANGE ) {
758                 if ( event->in ) {
759                         g_pParentWnd->SetActiveXY( xywnd );
760                 }
761         }
762         return FALSE;
763 }
764
765 void xywnd_motion( gdouble x, gdouble y, guint state, void* data ){
766         if ( reinterpret_cast<XYWnd*>( data )->chaseMouseMotion( static_cast<int>( x ), static_cast<int>( y ) ) ) {
767                 return;
768         }
769         reinterpret_cast<XYWnd*>( data )->XY_MouseMoved( static_cast<int>( x ), static_cast<int>( y ), buttons_for_state( state ) );
770 }
771
772 gboolean xywnd_wheel_scroll( GtkWidget* widget, GdkEventScroll* event, XYWnd* xywnd ){
773         if ( event->direction == GDK_SCROLL_UP ) {
774                 xywnd->ZoomInWithMouse( (int)event->x, (int)event->y );
775         }
776         else if ( event->direction == GDK_SCROLL_DOWN ) {
777                 xywnd->ZoomOut();
778         }
779         return FALSE;
780 }
781
782 gboolean xywnd_size_allocate( GtkWidget* widget, GtkAllocation* allocation, XYWnd* xywnd ){
783         xywnd->m_nWidth = allocation->width;
784         xywnd->m_nHeight = allocation->height;
785         xywnd->updateProjection();
786         xywnd->m_window_observer->onSizeChanged( xywnd->Width(), xywnd->Height() );
787         return FALSE;
788 }
789
790 gboolean xywnd_expose( GtkWidget* widget, GdkEventExpose* event, XYWnd* xywnd ){
791         if ( glwidget_make_current( xywnd->GetWidget() ) != FALSE ) {
792                 if ( Map_Valid( g_map ) && ScreenUpdates_Enabled() ) {
793                         GlobalOpenGL_debugAssertNoErrors();
794                         xywnd->XY_Draw();
795                         GlobalOpenGL_debugAssertNoErrors();
796
797                         xywnd->m_XORRectangle.set( rectangle_t() );
798                 }
799                 glwidget_swap_buffers( xywnd->GetWidget() );
800         }
801         return FALSE;
802 }
803
804
805 void XYWnd_CameraMoved( XYWnd& xywnd ){
806         if ( g_xywindow_globals_private.m_bCamXYUpdate ) {
807                 XYWnd_Update( xywnd );
808         }
809 }
810
811 XYWnd::XYWnd() :
812         m_gl_widget( glwidget_new( FALSE ) ),
813         m_deferredDraw( WidgetQueueDrawCaller( *m_gl_widget ) ),
814         m_deferred_motion( xywnd_motion, this ),
815         m_parent( 0 ),
816         m_window_observer( NewWindowObserver() ),
817         m_XORRectangle( m_gl_widget ),
818         m_chasemouse_handler( 0 ){
819         m_bActive = false;
820         m_buttonstate = 0;
821
822         m_bNewBrushDrag = false;
823         m_move_started = false;
824         m_zoom_started = false;
825
826         m_nWidth = 0;
827         m_nHeight = 0;
828
829         m_vOrigin[0] = 0;
830         m_vOrigin[1] = 20;
831         m_vOrigin[2] = 46;
832         m_fScale = 1;
833         m_viewType = XY;
834
835         m_backgroundActivated = false;
836         m_alpha = 1.0f;
837         m_xmin = 0.0f;
838         m_ymin = 0.0f;
839         m_xmax = 0.0f;
840         m_ymax = 0.0f;
841
842         m_entityCreate = false;
843
844         m_mnuDrop = 0;
845
846         GlobalWindowObservers_add( m_window_observer );
847         GlobalWindowObservers_connectWidget( m_gl_widget );
848
849         m_window_observer->setRectangleDrawCallback( ReferenceCaller1<XYWnd, rect_t, xy_update_xor_rectangle>( *this ) );
850         m_window_observer->setView( m_view );
851
852         gtk_widget_ref( m_gl_widget );
853
854         gtk_widget_set_events( m_gl_widget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK );
855         GTK_WIDGET_SET_FLAGS( m_gl_widget, GTK_CAN_FOCUS );
856
857         m_sizeHandler = g_signal_connect( G_OBJECT( m_gl_widget ), "size_allocate", G_CALLBACK( xywnd_size_allocate ), this );
858         m_exposeHandler = g_signal_connect( G_OBJECT( m_gl_widget ), "expose_event", G_CALLBACK( xywnd_expose ), this );
859
860         g_signal_connect( G_OBJECT( m_gl_widget ), "button_press_event", G_CALLBACK( xywnd_button_press ), this );
861         g_signal_connect( G_OBJECT( m_gl_widget ), "button_release_event", G_CALLBACK( xywnd_button_release ), this );
862         g_signal_connect( G_OBJECT( m_gl_widget ), "focus_in_event", G_CALLBACK( xywnd_focus_in ), this );
863         g_signal_connect( G_OBJECT( m_gl_widget ), "motion_notify_event", G_CALLBACK( DeferredMotion::gtk_motion ), &m_deferred_motion );
864
865         g_signal_connect( G_OBJECT( m_gl_widget ), "scroll_event", G_CALLBACK( xywnd_wheel_scroll ), this );
866
867         Map_addValidCallback( g_map, DeferredDrawOnMapValidChangedCaller( m_deferredDraw ) );
868
869         updateProjection();
870         updateModelview();
871
872         AddSceneChangeCallback( ReferenceCaller<XYWnd, &XYWnd_Update>( *this ) );
873         AddCameraMovedCallback( ReferenceCaller<XYWnd, &XYWnd_CameraMoved>( *this ) );
874
875         PressedButtons_connect( g_pressedButtons, m_gl_widget );
876
877         onMouseDown.connectLast( makeSignalHandler3( MouseDownCaller(), *this ) );
878 }
879
880 XYWnd::~XYWnd(){
881         onDestroyed();
882
883         if ( m_mnuDrop != 0 ) {
884                 gtk_widget_destroy( GTK_WIDGET( m_mnuDrop ) );
885                 m_mnuDrop = 0;
886         }
887
888         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_sizeHandler );
889         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_exposeHandler );
890
891         gtk_widget_unref( m_gl_widget );
892
893         m_window_observer->release();
894 }
895
896 void XYWnd::captureStates(){
897         m_state_selected = GlobalShaderCache().capture( "$XY_OVERLAY" );
898 }
899
900 void XYWnd::releaseStates(){
901         GlobalShaderCache().release( "$XY_OVERLAY" );
902 }
903
904 const Vector3& XYWnd::GetOrigin(){
905         return m_vOrigin;
906 }
907
908 void XYWnd::SetOrigin( const Vector3& origin ){
909         m_vOrigin = origin;
910         updateModelview();
911 }
912
913 void XYWnd::Scroll( int x, int y ){
914         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
915         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
916         m_vOrigin[nDim1] += x / m_fScale;
917         m_vOrigin[nDim2] += y / m_fScale;
918         updateModelview();
919         queueDraw();
920 }
921
922 unsigned int Clipper_buttons(){
923         return RAD_LBUTTON;
924 }
925
926 void XYWnd::DropClipPoint( int pointx, int pointy ){
927         Vector3 point;
928
929         XY_ToPoint( pointx, pointy, point );
930
931         Vector3 mid;
932         Select_GetMid( mid );
933         g_clip_viewtype = static_cast<VIEWTYPE>( GetViewType() );
934         const int nDim = ( g_clip_viewtype == YZ ) ? 0 : ( ( g_clip_viewtype == XZ ) ? 1 : 2 );
935         point[nDim] = mid[nDim];
936         vector3_snap( point, GetSnapGridSize() );
937         NewClipPoint( point );
938 }
939
940 void XYWnd::Clipper_OnLButtonDown( int x, int y ){
941         Vector3 mousePosition;
942         XY_ToPoint( x, y, mousePosition );
943         g_pMovingClip = GlobalClipPoints_Find( mousePosition, (VIEWTYPE)m_viewType, m_fScale );
944         if ( !g_pMovingClip ) {
945                 DropClipPoint( x, y );
946         }
947 }
948
949 void XYWnd::Clipper_OnLButtonUp( int x, int y ){
950         if ( g_pMovingClip ) {
951                 g_pMovingClip = 0;
952         }
953 }
954
955 void XYWnd::Clipper_OnMouseMoved( int x, int y ){
956         if ( g_pMovingClip ) {
957                 XY_ToPoint( x, y, g_pMovingClip->m_ptClip );
958                 XY_SnapToGrid( g_pMovingClip->m_ptClip );
959                 Clip_Update();
960                 ClipperChangeNotify();
961         }
962 }
963
964 void XYWnd::Clipper_Crosshair_OnMouseMoved( int x, int y ){
965         Vector3 mousePosition;
966         XY_ToPoint( x, y, mousePosition );
967         if ( ClipMode() && GlobalClipPoints_Find( mousePosition, (VIEWTYPE)m_viewType, m_fScale ) != 0 ) {
968                 GdkCursor *cursor;
969                 cursor = gdk_cursor_new( GDK_CROSSHAIR );
970                 gdk_window_set_cursor( m_gl_widget->window, cursor );
971                 gdk_cursor_unref( cursor );
972         }
973         else
974         {
975                 gdk_window_set_cursor( m_gl_widget->window, 0 );
976         }
977 }
978
979 unsigned int MoveCamera_buttons(){
980         return RAD_CONTROL | ( g_glwindow_globals.m_nMouseType == ETwoButton ? RAD_RBUTTON : RAD_MBUTTON );
981 }
982
983 void XYWnd_PositionCamera( XYWnd* xywnd, int x, int y, CamWnd& camwnd ){
984         Vector3 origin( Camera_getOrigin( camwnd ) );
985         xywnd->XY_ToPoint( x, y, origin );
986         xywnd->XY_SnapToGrid( origin );
987         Camera_setOrigin( camwnd, origin );
988 }
989
990 unsigned int OrientCamera_buttons(){
991         if ( g_glwindow_globals.m_nMouseType == ETwoButton ) {
992                 return RAD_RBUTTON | RAD_SHIFT | RAD_CONTROL;
993         }
994         return RAD_MBUTTON;
995 }
996
997 void XYWnd_OrientCamera( XYWnd* xywnd, int x, int y, CamWnd& camwnd ){
998         Vector3 point = g_vector3_identity;
999         xywnd->XY_ToPoint( x, y, point );
1000         xywnd->XY_SnapToGrid( point );
1001         vector3_subtract( point, Camera_getOrigin( camwnd ) );
1002
1003         int n1 = ( xywnd->GetViewType() == XY ) ? 1 : 2;
1004         int n2 = ( xywnd->GetViewType() == YZ ) ? 1 : 0;
1005         int nAngle = ( xywnd->GetViewType() == XY ) ? CAMERA_YAW : CAMERA_PITCH;
1006         if ( point[n1] || point[n2] ) {
1007                 Vector3 angles( Camera_getAngles( camwnd ) );
1008                 angles[nAngle] = static_cast<float>( radians_to_degrees( atan2( point[n1], point[n2] ) ) );
1009                 Camera_setAngles( camwnd, angles );
1010         }
1011 }
1012
1013 /*
1014    ==============
1015    NewBrushDrag
1016    ==============
1017  */
1018 unsigned int NewBrushDrag_buttons(){
1019         return RAD_LBUTTON;
1020 }
1021
1022 void XYWnd::NewBrushDrag_Begin( int x, int y ){
1023         m_NewBrushDrag = 0;
1024         m_nNewBrushPressx = x;
1025         m_nNewBrushPressy = y;
1026
1027         m_bNewBrushDrag = true;
1028         GlobalUndoSystem().start();
1029 }
1030
1031 void XYWnd::NewBrushDrag_End( int x, int y ){
1032         if ( m_NewBrushDrag != 0 ) {
1033                 GlobalUndoSystem().finish( "brushDragNew" );
1034         }
1035 }
1036
1037 void XYWnd::NewBrushDrag( int x, int y ){
1038         Vector3 mins, maxs;
1039         XY_ToPoint( m_nNewBrushPressx, m_nNewBrushPressy, mins );
1040         XY_SnapToGrid( mins );
1041         XY_ToPoint( x, y, maxs );
1042         XY_SnapToGrid( maxs );
1043
1044         int nDim = ( m_viewType == XY ) ? 2 : ( m_viewType == YZ ) ? 0 : 1;
1045
1046         mins[nDim] = float_snapped( Select_getWorkZone().d_work_min[nDim], GetSnapGridSize() );
1047         maxs[nDim] = float_snapped( Select_getWorkZone().d_work_max[nDim], GetSnapGridSize() );
1048
1049         if ( maxs[nDim] <= mins[nDim] ) {
1050                 maxs[nDim] = mins[nDim] + GetGridSize();
1051         }
1052
1053         for ( int i = 0 ; i < 3 ; i++ )
1054         {
1055                 if ( mins[i] == maxs[i] ) {
1056                         return; // don't create a degenerate brush
1057                 }
1058                 if ( mins[i] > maxs[i] ) {
1059                         float temp = mins[i];
1060                         mins[i] = maxs[i];
1061                         maxs[i] = temp;
1062                 }
1063         }
1064
1065         if ( m_NewBrushDrag == 0 ) {
1066                 NodeSmartReference node( GlobalBrushCreator().createBrush() );
1067                 Node_getTraversable( Map_FindOrInsertWorldspawn( g_map ) )->insert( node );
1068
1069                 scene::Path brushpath( makeReference( GlobalSceneGraph().root() ) );
1070                 brushpath.push( makeReference( *Map_GetWorldspawn( g_map ) ) );
1071                 brushpath.push( makeReference( node.get() ) );
1072                 selectPath( brushpath, true );
1073
1074                 m_NewBrushDrag = node.get_pointer();
1075         }
1076
1077         // d1223m
1078         //Scene_BrushResize_Selected(GlobalSceneGraph(), aabb_for_minmax(mins, maxs), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()));
1079         Scene_BrushResize_Selected( GlobalSceneGraph(), aabb_for_minmax( mins, maxs ),
1080                                                                 g_brush_always_caulk ?
1081                                                                 "textures/common/caulk" : TextureBrowser_GetSelectedShader( GlobalTextureBrowser() ) );
1082 }
1083
1084 void entitycreate_activated( GtkWidget* item ){
1085         scene::Node* world_node = Map_FindWorldspawn( g_map );
1086         const char* entity_name = gtk_label_get_text( GTK_LABEL( GTK_BIN( item )->child ) );
1087
1088         if ( !( world_node && string_equal( entity_name, "worldspawn" ) ) ) {
1089                 g_pParentWnd->ActiveXY()->OnEntityCreate( entity_name );
1090         }
1091         else {
1092                 GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( MainFrame_getWindow() ), "There's already a worldspawn in your map!"
1093                                                                                                                                                           "",
1094                                                                                  "Info",
1095                                                                                  eMB_OK,
1096                                                                                  eMB_ICONDEFAULT );
1097         }
1098 }
1099
1100 void EntityClassMenu_addItem( GtkMenu* menu, const char* name ){
1101         GtkMenuItem* item = GTK_MENU_ITEM( gtk_menu_item_new_with_label( name ) );
1102         g_signal_connect( G_OBJECT( item ), "activate", G_CALLBACK( entitycreate_activated ), item );
1103         gtk_widget_show( GTK_WIDGET( item ) );
1104         menu_add_item( menu, item );
1105 }
1106
1107 class EntityClassMenuInserter : public EntityClassVisitor
1108 {
1109 typedef std::pair<GtkMenu*, CopiedString> MenuPair;
1110 typedef std::vector<MenuPair> MenuStack;
1111 MenuStack m_stack;
1112 CopiedString m_previous;
1113 public:
1114 EntityClassMenuInserter( GtkMenu* menu ){
1115         m_stack.reserve( 2 );
1116         m_stack.push_back( MenuPair( menu, "" ) );
1117 }
1118 ~EntityClassMenuInserter(){
1119         if ( !string_empty( m_previous.c_str() ) ) {
1120                 addItem( m_previous.c_str(), "" );
1121         }
1122 }
1123 void visit( EntityClass* e ){
1124         ASSERT_MESSAGE( !string_empty( e->name() ), "entity-class has no name" );
1125         if ( !string_empty( m_previous.c_str() ) ) {
1126                 addItem( m_previous.c_str(), e->name() );
1127         }
1128         m_previous = e->name();
1129 }
1130 void pushMenu( const CopiedString& name ){
1131         GtkMenuItem* item = GTK_MENU_ITEM( gtk_menu_item_new_with_label( name.c_str() ) );
1132         gtk_widget_show( GTK_WIDGET( item ) );
1133         container_add_widget( GTK_CONTAINER( m_stack.back().first ), GTK_WIDGET( item ) );
1134
1135         GtkMenu* submenu = GTK_MENU( gtk_menu_new() );
1136         gtk_menu_item_set_submenu( item, GTK_WIDGET( submenu ) );
1137
1138         m_stack.push_back( MenuPair( submenu, name ) );
1139 }
1140 void popMenu(){
1141         m_stack.pop_back();
1142 }
1143 void addItem( const char* name, const char* next ){
1144         const char* underscore = strchr( name, '_' );
1145
1146         if ( underscore != 0 && underscore != name ) {
1147                 bool nextEqual = string_equal_n( name, next, ( underscore + 1 ) - name );
1148                 const char* parent = m_stack.back().second.c_str();
1149
1150                 if ( !string_empty( parent )
1151                          && string_length( parent ) == std::size_t( underscore - name )
1152                          && string_equal_n( name, parent, underscore - name ) ) { // this is a child
1153                 }
1154                 else if ( nextEqual ) {
1155                         if ( m_stack.size() == 2 ) {
1156                                 popMenu();
1157                         }
1158                         pushMenu( CopiedString( StringRange( name, underscore ) ) );
1159                 }
1160                 else if ( m_stack.size() == 2 ) {
1161                         popMenu();
1162                 }
1163         }
1164         else if ( m_stack.size() == 2 ) {
1165                 popMenu();
1166         }
1167
1168         EntityClassMenu_addItem( m_stack.back().first, name );
1169 }
1170 };
1171
1172 void XYWnd::OnContextMenu(){
1173         if ( g_xywindow_globals.m_bRightClick == false ) {
1174                 return;
1175         }
1176
1177         if ( m_mnuDrop == 0 ) { // first time, load it up
1178                 GtkMenu* menu = m_mnuDrop = GTK_MENU( gtk_menu_new() );
1179
1180                 EntityClassMenuInserter inserter( menu );
1181                 GlobalEntityClassManager().forEach( inserter );
1182         }
1183
1184         gtk_menu_popup( m_mnuDrop, 0, 0, 0, 0, 1, GDK_CURRENT_TIME );
1185 }
1186
1187 FreezePointer g_xywnd_freezePointer;
1188
1189 unsigned int Move_buttons(){
1190         return RAD_RBUTTON;
1191 }
1192
1193 void XYWnd_moveDelta( int x, int y, unsigned int state, void* data ){
1194         reinterpret_cast<XYWnd*>( data )->EntityCreate_MouseMove( x, y );
1195         reinterpret_cast<XYWnd*>( data )->Scroll( -x, y );
1196 }
1197
1198 gboolean XYWnd_Move_focusOut( GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd ){
1199         xywnd->Move_End();
1200         return FALSE;
1201 }
1202
1203 void XYWnd::Move_Begin(){
1204         if ( m_move_started ) {
1205                 Move_End();
1206         }
1207         m_move_started = true;
1208         g_xywnd_freezePointer.freeze_pointer( m_parent != 0 ? m_parent : MainFrame_getWindow(), m_gl_widget, XYWnd_moveDelta, this );
1209         m_move_focusOut = g_signal_connect( G_OBJECT( m_gl_widget ), "focus_out_event", G_CALLBACK( XYWnd_Move_focusOut ), this );
1210 }
1211
1212 void XYWnd::Move_End(){
1213         m_move_started = false;
1214         g_xywnd_freezePointer.unfreeze_pointer( m_parent != 0 ? m_parent : MainFrame_getWindow() );
1215         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_move_focusOut );
1216 }
1217
1218 unsigned int Zoom_buttons(){
1219         return RAD_RBUTTON | RAD_SHIFT;
1220 }
1221
1222 int g_dragZoom = 0;
1223
1224 void XYWnd_zoomDelta( int x, int y, unsigned int state, void* data ){
1225         if ( y != 0 ) {
1226                 g_dragZoom += y;
1227                 while ( abs( g_dragZoom ) > 8 )
1228                 {
1229                         if ( g_dragZoom > 0 ) {
1230                                 reinterpret_cast<XYWnd*>( data )->ZoomOut();
1231                                 g_dragZoom -= 8;
1232                         }
1233                         else
1234                         {
1235                                 reinterpret_cast<XYWnd*>( data )->ZoomIn();
1236                                 g_dragZoom += 8;
1237                         }
1238                 }
1239         }
1240 }
1241
1242 gboolean XYWnd_Zoom_focusOut( GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd ){
1243         xywnd->Zoom_End();
1244         return FALSE;
1245 }
1246
1247 void XYWnd::Zoom_Begin(){
1248         if ( m_zoom_started ) {
1249                 Zoom_End();
1250         }
1251         m_zoom_started = true;
1252         g_dragZoom = 0;
1253         g_xywnd_freezePointer.freeze_pointer( m_parent != 0 ? m_parent : MainFrame_getWindow(), m_gl_widget, XYWnd_zoomDelta, this );
1254         m_zoom_focusOut = g_signal_connect( G_OBJECT( m_gl_widget ), "focus_out_event", G_CALLBACK( XYWnd_Zoom_focusOut ), this );
1255 }
1256
1257 void XYWnd::Zoom_End(){
1258         m_zoom_started = false;
1259         g_xywnd_freezePointer.unfreeze_pointer( m_parent != 0 ? m_parent : MainFrame_getWindow() );
1260         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_zoom_focusOut );
1261 }
1262
1263 // makes sure the selected brush or camera is in view
1264 void XYWnd::PositionView( const Vector3& position ){
1265         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
1266         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
1267
1268         m_vOrigin[nDim1] = position[nDim1];
1269         m_vOrigin[nDim2] = position[nDim2];
1270
1271         updateModelview();
1272
1273         XYWnd_Update( *this );
1274 }
1275
1276 void XYWnd::SetViewType( VIEWTYPE viewType ){
1277         m_viewType = viewType;
1278         updateModelview();
1279
1280         if ( m_parent != 0 ) {
1281                 gtk_window_set_title( m_parent, ViewType_getTitle( m_viewType ) );
1282         }
1283 }
1284
1285
1286 inline WindowVector WindowVector_forInteger( int x, int y ){
1287         return WindowVector( static_cast<float>( x ), static_cast<float>( y ) );
1288 }
1289
1290 void XYWnd::mouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ){
1291         XY_MouseDown( static_cast<int>( position.x() ), static_cast<int>( position.y() ), buttons_for_button_and_modifiers( button, modifiers ) );
1292 }
1293 void XYWnd::XY_MouseDown( int x, int y, unsigned int buttons ){
1294         if ( buttons == Move_buttons() ) {
1295                 Move_Begin();
1296                 EntityCreate_MouseDown( x, y );
1297         }
1298         else if ( buttons == Zoom_buttons() ) {
1299                 Zoom_Begin();
1300         }
1301         else if ( ClipMode() && buttons == Clipper_buttons() ) {
1302                 Clipper_OnLButtonDown( x, y );
1303         }
1304         else if ( buttons == NewBrushDrag_buttons() && GlobalSelectionSystem().countSelected() == 0 ) {
1305                 NewBrushDrag_Begin( x, y );
1306         }
1307         // control mbutton = move camera
1308         else if ( buttons == MoveCamera_buttons() ) {
1309                 XYWnd_PositionCamera( this, x, y, *g_pParentWnd->GetCamWnd() );
1310         }
1311         // mbutton = angle camera
1312         else if ( buttons == OrientCamera_buttons() ) {
1313                 XYWnd_OrientCamera( this, x, y, *g_pParentWnd->GetCamWnd() );
1314         }
1315         else
1316         {
1317                 m_window_observer->onMouseDown( WindowVector_forInteger( x, y ), button_for_flags( buttons ), modifiers_for_flags( buttons ) );
1318         }
1319 }
1320
1321 void XYWnd::XY_MouseUp( int x, int y, unsigned int buttons ){
1322         if ( m_move_started ) {
1323                 Move_End();
1324                 EntityCreate_MouseUp( x, y );
1325         }
1326         else if ( m_zoom_started ) {
1327                 Zoom_End();
1328         }
1329         else if ( ClipMode() && buttons == Clipper_buttons() ) {
1330                 Clipper_OnLButtonUp( x, y );
1331         }
1332         else if ( m_bNewBrushDrag ) {
1333                 m_bNewBrushDrag = false;
1334                 NewBrushDrag_End( x, y );
1335                 if ( m_NewBrushDrag == 0 ) {
1336                         //L button w/o created brush = tunnel selection
1337                         m_window_observer->onMouseUp( WindowVector_forInteger( x, y ), button_for_flags( buttons ), modifiers_for_flags( buttons ) );
1338                 }
1339         }
1340         else
1341         {
1342                 m_window_observer->onMouseUp( WindowVector_forInteger( x, y ), button_for_flags( buttons ), modifiers_for_flags( buttons ) );
1343         }
1344 }
1345
1346 void XYWnd::XY_MouseMoved( int x, int y, unsigned int buttons ){
1347         // rbutton = drag xy origin
1348         if ( m_move_started ) {
1349         }
1350         // zoom in/out
1351         else if ( m_zoom_started ) {
1352         }
1353
1354         else if ( ClipMode() && g_pMovingClip != 0 ) {
1355                 Clipper_OnMouseMoved( x, y );
1356         }
1357         // lbutton without selection = drag new brush
1358         else if ( m_bNewBrushDrag ) {
1359                 NewBrushDrag( x, y );
1360         }
1361
1362         // control mbutton = move camera
1363         else if ( getButtonState() == MoveCamera_buttons() ) {
1364                 XYWnd_PositionCamera( this, x, y, *g_pParentWnd->GetCamWnd() );
1365         }
1366
1367         // mbutton = angle camera
1368         else if ( getButtonState() == OrientCamera_buttons() ) {
1369                 XYWnd_OrientCamera( this, x, y, *g_pParentWnd->GetCamWnd() );
1370         }
1371
1372         else
1373         {
1374                 m_window_observer->onMouseMotion( WindowVector_forInteger( x, y ), modifiers_for_flags( buttons ) );
1375
1376                 m_mousePosition[0] = m_mousePosition[1] = m_mousePosition[2] = 0.0;
1377                 XY_ToPoint( x, y, m_mousePosition );
1378                 XY_SnapToGrid( m_mousePosition );
1379
1380                 StringOutputStream status( 64 );
1381                 status << "x:: " << FloatFormat( m_mousePosition[0], 6, 1 )
1382                            << "  y:: " << FloatFormat( m_mousePosition[1], 6, 1 )
1383                            << "  z:: " << FloatFormat( m_mousePosition[2], 6, 1 );
1384                 g_pParentWnd->SetStatusText( g_pParentWnd->m_position_status, status.c_str() );
1385
1386                 if ( g_bCrossHairs ) {
1387                         XYWnd_Update( *this );
1388                 }
1389
1390                 Clipper_Crosshair_OnMouseMoved( x, y );
1391         }
1392 }
1393
1394 void XYWnd::EntityCreate_MouseDown( int x, int y ){
1395         m_entityCreate = true;
1396         m_entityCreate_x = x;
1397         m_entityCreate_y = y;
1398 }
1399
1400 void XYWnd::EntityCreate_MouseMove( int x, int y ){
1401         if ( m_entityCreate && ( m_entityCreate_x != x || m_entityCreate_y != y ) ) {
1402                 m_entityCreate = false;
1403         }
1404 }
1405
1406 void XYWnd::EntityCreate_MouseUp( int x, int y ){
1407         if ( m_entityCreate ) {
1408                 m_entityCreate = false;
1409                 OnContextMenu();
1410         }
1411 }
1412
1413 inline float screen_normalised( int pos, unsigned int size ){
1414         return ( ( 2.0f * pos ) / size ) - 1.0f;
1415 }
1416
1417 inline float normalised_to_world( float normalised, float world_origin, float normalised2world_scale ){
1418         return world_origin + normalised * normalised2world_scale;
1419 }
1420
1421
1422 // TTimo: watch it, this doesn't init one of the 3 coords
1423 void XYWnd::XY_ToPoint( int x, int y, Vector3& point ){
1424         float normalised2world_scale_x = m_nWidth / 2 / m_fScale;
1425         float normalised2world_scale_y = m_nHeight / 2 / m_fScale;
1426         if ( m_viewType == XY ) {
1427                 point[0] = normalised_to_world( screen_normalised( x, m_nWidth ), m_vOrigin[0], normalised2world_scale_x );
1428                 point[1] = normalised_to_world( -screen_normalised( y, m_nHeight ), m_vOrigin[1], normalised2world_scale_y );
1429         }
1430         else if ( m_viewType == YZ ) {
1431                 point[1] = normalised_to_world( screen_normalised( x, m_nWidth ), m_vOrigin[1], normalised2world_scale_x );
1432                 point[2] = normalised_to_world( -screen_normalised( y, m_nHeight ), m_vOrigin[2], normalised2world_scale_y );
1433         }
1434         else
1435         {
1436                 point[0] = normalised_to_world( screen_normalised( x, m_nWidth ), m_vOrigin[0], normalised2world_scale_x );
1437                 point[2] = normalised_to_world( -screen_normalised( y, m_nHeight ), m_vOrigin[2], normalised2world_scale_y );
1438         }
1439 }
1440
1441 void XYWnd::XY_SnapToGrid( Vector3& point ){
1442         if ( m_viewType == XY ) {
1443                 point[0] = float_snapped( point[0], GetSnapGridSize() );
1444                 point[1] = float_snapped( point[1], GetSnapGridSize() );
1445         }
1446         else if ( m_viewType == YZ ) {
1447                 point[1] = float_snapped( point[1], GetSnapGridSize() );
1448                 point[2] = float_snapped( point[2], GetSnapGridSize() );
1449         }
1450         else
1451         {
1452                 point[0] = float_snapped( point[0], GetSnapGridSize() );
1453                 point[2] = float_snapped( point[2], GetSnapGridSize() );
1454         }
1455 }
1456
1457 void XYWnd::XY_LoadBackgroundImage( const char *name ){
1458         const char* relative = path_make_relative( name, GlobalFileSystem().findRoot( name ) );
1459         if ( relative == name ) {
1460                 globalOutputStream() << "WARNING: could not extract the relative path, using full path instead\n";
1461         }
1462
1463         char fileNameWithoutExt[512];
1464         strncpy( fileNameWithoutExt, relative, sizeof( fileNameWithoutExt ) - 1 );
1465         fileNameWithoutExt[512 - 1] = '\0';
1466         fileNameWithoutExt[strlen( fileNameWithoutExt ) - 4] = '\0';
1467
1468         Image *image = QERApp_LoadImage( 0, fileNameWithoutExt );
1469         if ( !image ) {
1470                 globalOutputStream() << "Could not load texture " << fileNameWithoutExt << "\n";
1471                 return;
1472         }
1473         g_pParentWnd->ActiveXY()->m_tex = (qtexture_t*)malloc( sizeof( qtexture_t ) );
1474         LoadTextureRGBA( g_pParentWnd->ActiveXY()->XYWnd::m_tex, image->getRGBAPixels(), image->getWidth(), image->getHeight() );
1475         globalOutputStream() << "Loaded background texture " << relative << "\n";
1476         g_pParentWnd->ActiveXY()->m_backgroundActivated = true;
1477
1478         int m_ix, m_iy;
1479         switch ( g_pParentWnd->ActiveXY()->m_viewType )
1480         {
1481         case XY:
1482                 m_ix = 0;
1483                 m_iy = 1;
1484                 break;
1485         case XZ:
1486                 m_ix = 0;
1487                 m_iy = 2;
1488                 break;
1489         case YZ:
1490                 m_ix = 1;
1491                 m_iy = 2;
1492                 break;
1493         }
1494
1495         Vector3 min, max;
1496         Select_GetBounds( min, max );
1497         g_pParentWnd->ActiveXY()->m_xmin = min[m_ix];
1498         g_pParentWnd->ActiveXY()->m_ymin = min[m_iy];
1499         g_pParentWnd->ActiveXY()->m_xmax = max[m_ix];
1500         g_pParentWnd->ActiveXY()->m_ymax = max[m_iy];
1501 }
1502
1503 void XYWnd::XY_DisableBackground( void ){
1504         g_pParentWnd->ActiveXY()->m_backgroundActivated = false;
1505         if ( g_pParentWnd->ActiveXY()->m_tex ) {
1506                 free( g_pParentWnd->ActiveXY()->m_tex );
1507         }
1508         g_pParentWnd->ActiveXY()->m_tex = NULL;
1509 }
1510
1511 void WXY_BackgroundSelect( void ){
1512         bool brushesSelected = Scene_countSelectedBrushes( GlobalSceneGraph() ) != 0;
1513         if ( !brushesSelected ) {
1514                 gtk_MessageBox( 0, "You have to select some brushes to get the bounding box for.\n",
1515                                                 "No selection", eMB_OK, eMB_ICONERROR );
1516                 return;
1517         }
1518
1519         const char *filename = file_dialog( GTK_WIDGET( MainFrame_getWindow() ), TRUE, "Background Image", NULL, NULL );
1520         g_pParentWnd->ActiveXY()->XY_DisableBackground();
1521         if ( filename ) {
1522                 g_pParentWnd->ActiveXY()->XY_LoadBackgroundImage( filename );
1523         }
1524 }
1525
1526 /*
1527    ============================================================================
1528
1529    DRAWING
1530
1531    ============================================================================
1532  */
1533
1534 /*
1535    ==============
1536    XY_DrawGrid
1537    ==============
1538  */
1539
1540 double two_to_the_power( int power ){
1541         return pow( 2.0f, power );
1542 }
1543
1544 void XYWnd::XY_DrawAxis( void ){
1545         if ( g_xywindow_globals_private.show_axis ) {
1546                 const char g_AxisName[3] = { 'X', 'Y', 'Z' };
1547                 const int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
1548                 const int nDim2 = ( m_viewType == XY ) ? 1 : 2;
1549                 const int w = ( m_nWidth / 2 / m_fScale );
1550                 const int h = ( m_nHeight / 2 / m_fScale );
1551
1552                 const Vector3& colourX = ( m_viewType == YZ ) ? g_xywindow_globals.AxisColorY : g_xywindow_globals.AxisColorX;
1553                 const Vector3& colourY = ( m_viewType == XY ) ? g_xywindow_globals.AxisColorY : g_xywindow_globals.AxisColorZ;
1554
1555                 // draw two lines with corresponding axis colors to highlight current view
1556                 // horizontal line: nDim1 color
1557                 glLineWidth( 2 );
1558                 glBegin( GL_LINES );
1559                 glColor3fv( vector3_to_array( colourX ) );
1560                 glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale );
1561                 glVertex2f( m_vOrigin[nDim1] - w + 65 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale );
1562                 glVertex2f( 0, 0 );
1563                 glVertex2f( 32 / m_fScale, 0 );
1564                 glColor3fv( vector3_to_array( colourY ) );
1565                 glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale );
1566                 glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 20 / m_fScale );
1567                 glVertex2f( 0, 0 );
1568                 glVertex2f( 0, 32 / m_fScale );
1569                 glEnd();
1570                 glLineWidth( 1 );
1571                 // now print axis symbols
1572                 glColor3fv( vector3_to_array( colourX ) );
1573                 glRasterPos2f( m_vOrigin[nDim1] - w + 55 / m_fScale, m_vOrigin[nDim2] + h - 55 / m_fScale );
1574                 GlobalOpenGL().drawChar( g_AxisName[nDim1] );
1575                 glRasterPos2f( 28 / m_fScale, -10 / m_fScale );
1576                 GlobalOpenGL().drawChar( g_AxisName[nDim1] );
1577                 glColor3fv( vector3_to_array( colourY ) );
1578                 glRasterPos2f( m_vOrigin[nDim1] - w + 25 / m_fScale, m_vOrigin[nDim2] + h - 30 / m_fScale );
1579                 GlobalOpenGL().drawChar( g_AxisName[nDim2] );
1580                 glRasterPos2f( -10 / m_fScale, 28 / m_fScale );
1581                 GlobalOpenGL().drawChar( g_AxisName[nDim2] );
1582         }
1583 }
1584
1585 void XYWnd::XY_DrawBackground( void ){
1586         glPushAttrib( GL_ALL_ATTRIB_BITS );
1587
1588         glEnable( GL_TEXTURE_2D );
1589         glEnable( GL_BLEND );
1590         glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
1591         glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
1592         glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
1593         glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
1594
1595         glPolygonMode( GL_FRONT, GL_FILL );
1596
1597         glBindTexture( GL_TEXTURE_2D, m_tex->texture_number );
1598         glBegin( GL_QUADS );
1599
1600         glColor4f( 1.0, 1.0, 1.0, m_alpha );
1601         glTexCoord2f( 0.0, 1.0 );
1602         glVertex2f( m_xmin, m_ymin );
1603
1604         glTexCoord2f( 1.0, 1.0 );
1605         glVertex2f( m_xmax, m_ymin );
1606
1607         glTexCoord2f( 1.0, 0.0 );
1608         glVertex2f( m_xmax, m_ymax );
1609
1610         glTexCoord2f( 0.0, 0.0 );
1611         glVertex2f( m_xmin, m_ymax );
1612
1613         glEnd();
1614         glBindTexture( GL_TEXTURE_2D, 0 );
1615
1616         glPopAttrib();
1617 }
1618
1619 void XYWnd::XY_DrawGrid( void ) {
1620         float x, y, xb, xe, yb, ye;
1621         float w, h, a;
1622         char text[32];
1623         float step, minor_step, stepx, stepy;
1624         step = minor_step = stepx = stepy = GetGridSize();
1625
1626         int minor_power = Grid_getPower();
1627         int mask;
1628
1629         while ( ( minor_step * m_fScale ) <= 4.0f ) { // make sure minor grid spacing is at least 4 pixels on the screen
1630                 ++minor_power;
1631                 minor_step *= 2;
1632         }
1633         int power = minor_power;
1634         while ( ( power % 3 ) != 0 || ( step * m_fScale ) <= 32.0f ) { // make sure major grid spacing is at least 32 pixels on the screen
1635                 ++power;
1636                 step = float(two_to_the_power( power ) );
1637         }
1638         mask = ( 1 << ( power - minor_power ) ) - 1;
1639         while ( ( stepx * m_fScale ) <= 32.0f ) // text step x must be at least 32
1640                 stepx *= 2;
1641         while ( ( stepy * m_fScale ) <= 32.0f ) // text step y must be at least 32
1642                 stepy *= 2;
1643
1644         a = ( ( GetSnapGridSize() > 0.0f ) ? 1.0f : 0.3f );
1645
1646         glDisable( GL_TEXTURE_2D );
1647         glDisable( GL_TEXTURE_1D );
1648         glDisable( GL_DEPTH_TEST );
1649         glDisable( GL_BLEND );
1650         glLineWidth( 1 );
1651
1652         w = ( m_nWidth / 2 / m_fScale );
1653         h = ( m_nHeight / 2 / m_fScale );
1654
1655         const int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
1656         const int nDim2 = ( m_viewType == XY ) ? 1 : 2;
1657
1658         xb = m_vOrigin[nDim1] - w;
1659         if ( xb < region_mins[nDim1] ) {
1660                 xb = region_mins[nDim1];
1661         }
1662         xb = step * floor( xb / step );
1663
1664         xe = m_vOrigin[nDim1] + w;
1665         if ( xe > region_maxs[nDim1] ) {
1666                 xe = region_maxs[nDim1];
1667         }
1668         xe = step * ceil( xe / step );
1669
1670         yb = m_vOrigin[nDim2] - h;
1671         if ( yb < region_mins[nDim2] ) {
1672                 yb = region_mins[nDim2];
1673         }
1674         yb = step * floor( yb / step );
1675
1676         ye = m_vOrigin[nDim2] + h;
1677         if ( ye > region_maxs[nDim2] ) {
1678                 ye = region_maxs[nDim2];
1679         }
1680         ye = step * ceil( ye / step );
1681
1682 #define COLORS_DIFFER( a,b ) \
1683         ( ( a )[0] != ( b )[0] || \
1684           ( a )[1] != ( b )[1] || \
1685           ( a )[2] != ( b )[2] )
1686
1687         // djbob
1688         // draw minor blocks
1689         if ( g_xywindow_globals_private.d_showgrid || a < 1.0f ) {
1690                 if ( a < 1.0f ) {
1691                         glEnable( GL_BLEND );
1692                 }
1693
1694                 if ( COLORS_DIFFER( g_xywindow_globals.color_gridminor, g_xywindow_globals.color_gridback ) ) {
1695                         glColor4fv( vector4_to_array( Vector4( g_xywindow_globals.color_gridminor, a ) ) );
1696
1697                         glBegin( GL_LINES );
1698                         int i = 0;
1699                         for ( x = xb ; x < xe ; x += minor_step, ++i ) {
1700                                 if ( ( i & mask ) != 0 ) {
1701                                         glVertex2f( x, yb );
1702                                         glVertex2f( x, ye );
1703                                 }
1704                         }
1705                         i = 0;
1706                         for ( y = yb ; y < ye ; y += minor_step, ++i ) {
1707                                 if ( ( i & mask ) != 0 ) {
1708                                         glVertex2f( xb, y );
1709                                         glVertex2f( xe, y );
1710                                 }
1711                         }
1712                         glEnd();
1713                 }
1714
1715                 // draw major blocks
1716                 if ( COLORS_DIFFER( g_xywindow_globals.color_gridmajor, g_xywindow_globals.color_gridminor ) ) {
1717                         glColor4fv( vector4_to_array( Vector4( g_xywindow_globals.color_gridmajor, a ) ) );
1718
1719                         glBegin( GL_LINES );
1720                         for ( x = xb ; x <= xe ; x += step ) {
1721                                 glVertex2f( x, yb );
1722                                 glVertex2f( x, ye );
1723                         }
1724                         for ( y = yb ; y <= ye ; y += step ) {
1725                                 glVertex2f( xb, y );
1726                                 glVertex2f( xe, y );
1727                         }
1728                         glEnd();
1729                 }
1730
1731                 if ( a < 1.0f ) {
1732                         glDisable( GL_BLEND );
1733                 }
1734         }
1735
1736         // draw coordinate text if needed
1737         if ( g_xywindow_globals_private.show_coordinates ) {
1738                 glColor4fv( vector4_to_array( Vector4( g_xywindow_globals.color_gridtext, 1.0f ) ) );
1739                 float offx = m_vOrigin[nDim2] + h - ( 4 + GlobalOpenGL().m_font->getPixelAscent() ) / m_fScale;
1740                 float offy = m_vOrigin[nDim1] - w +  4                                            / m_fScale;
1741                 for ( x = xb - fmod( xb, stepx ); x <= xe ; x += stepx ) {
1742                         glRasterPos2f( x, offx );
1743                         sprintf( text, "%g", x );
1744                         GlobalOpenGL().drawString( text );
1745                 }
1746                 for ( y = yb - fmod( yb, stepy ); y <= ye ; y += stepy ) {
1747                         glRasterPos2f( offy, y );
1748                         sprintf( text, "%g", y );
1749                         GlobalOpenGL().drawString( text );
1750                 }
1751
1752                 if ( Active() ) {
1753                         glColor3fv( vector3_to_array( g_xywindow_globals.color_viewname ) );
1754                 }
1755
1756                 // we do this part (the old way) only if show_axis is disabled
1757                 if ( !g_xywindow_globals_private.show_axis ) {
1758                         glRasterPos2f( m_vOrigin[nDim1] - w + 35 / m_fScale, m_vOrigin[nDim2] + h - 20 / m_fScale );
1759
1760                         GlobalOpenGL().drawString( ViewType_getTitle( m_viewType ) );
1761                 }
1762         }
1763
1764         XYWnd::XY_DrawAxis();
1765
1766         // show current work zone?
1767         // the work zone is used to place dropped points and brushes
1768         if ( g_xywindow_globals_private.d_show_work ) {
1769                 glColor4f( 1.0f, 0.0f, 0.0f, 1.0f );
1770                 glBegin( GL_LINES );
1771                 glVertex2f( xb, Select_getWorkZone().d_work_min[nDim2] );
1772                 glVertex2f( xe, Select_getWorkZone().d_work_min[nDim2] );
1773                 glVertex2f( xb, Select_getWorkZone().d_work_max[nDim2] );
1774                 glVertex2f( xe, Select_getWorkZone().d_work_max[nDim2] );
1775                 glVertex2f( Select_getWorkZone().d_work_min[nDim1], yb );
1776                 glVertex2f( Select_getWorkZone().d_work_min[nDim1], ye );
1777                 glVertex2f( Select_getWorkZone().d_work_max[nDim1], yb );
1778                 glVertex2f( Select_getWorkZone().d_work_max[nDim1], ye );
1779                 glEnd();
1780         }
1781 }
1782
1783 /*
1784    ==============
1785    XY_DrawBlockGrid
1786    ==============
1787  */
1788 void XYWnd::XY_DrawBlockGrid(){
1789         if ( Map_FindWorldspawn( g_map ) == 0 ) {
1790                 return;
1791         }
1792         const char *value = Node_getEntity( *Map_GetWorldspawn( g_map ) )->getKeyValue( "_blocksize" );
1793         if ( strlen( value ) ) {
1794                 sscanf( value, "%i", &g_xywindow_globals_private.blockSize );
1795         }
1796
1797         if ( !g_xywindow_globals_private.blockSize || g_xywindow_globals_private.blockSize > 65536 || g_xywindow_globals_private.blockSize < 1024 ) {
1798                 // don't use custom blocksize if it is less than the default, or greater than the maximum world coordinate
1799                 g_xywindow_globals_private.blockSize = 1024;
1800         }
1801
1802         float x, y, xb, xe, yb, ye;
1803         float w, h;
1804         char text[32];
1805
1806         glDisable( GL_TEXTURE_2D );
1807         glDisable( GL_TEXTURE_1D );
1808         glDisable( GL_DEPTH_TEST );
1809         glDisable( GL_BLEND );
1810
1811         w = ( m_nWidth / 2 / m_fScale );
1812         h = ( m_nHeight / 2 / m_fScale );
1813
1814         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
1815         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
1816
1817         xb = m_vOrigin[nDim1] - w;
1818         if ( xb < region_mins[nDim1] ) {
1819                 xb = region_mins[nDim1];
1820         }
1821         xb = static_cast<float>( g_xywindow_globals_private.blockSize * floor( xb / g_xywindow_globals_private.blockSize ) );
1822
1823         xe = m_vOrigin[nDim1] + w;
1824         if ( xe > region_maxs[nDim1] ) {
1825                 xe = region_maxs[nDim1];
1826         }
1827         xe = static_cast<float>( g_xywindow_globals_private.blockSize * ceil( xe / g_xywindow_globals_private.blockSize ) );
1828
1829         yb = m_vOrigin[nDim2] - h;
1830         if ( yb < region_mins[nDim2] ) {
1831                 yb = region_mins[nDim2];
1832         }
1833         yb = static_cast<float>( g_xywindow_globals_private.blockSize * floor( yb / g_xywindow_globals_private.blockSize ) );
1834
1835         ye = m_vOrigin[nDim2] + h;
1836         if ( ye > region_maxs[nDim2] ) {
1837                 ye = region_maxs[nDim2];
1838         }
1839         ye = static_cast<float>( g_xywindow_globals_private.blockSize * ceil( ye / g_xywindow_globals_private.blockSize ) );
1840
1841         // draw major blocks
1842
1843         glColor3fv( vector3_to_array( g_xywindow_globals.color_gridblock ) );
1844         glLineWidth( 2 );
1845
1846         glBegin( GL_LINES );
1847
1848         for ( x = xb ; x <= xe ; x += g_xywindow_globals_private.blockSize )
1849         {
1850                 glVertex2f( x, yb );
1851                 glVertex2f( x, ye );
1852         }
1853
1854         if ( m_viewType == XY ) {
1855                 for ( y = yb ; y <= ye ; y += g_xywindow_globals_private.blockSize )
1856                 {
1857                         glVertex2f( xb, y );
1858                         glVertex2f( xe, y );
1859                 }
1860         }
1861
1862         glEnd();
1863         glLineWidth( 1 );
1864
1865         // draw coordinate text if needed
1866
1867         if ( m_viewType == XY && m_fScale > .1 ) {
1868                 for ( x = xb ; x < xe ; x += g_xywindow_globals_private.blockSize )
1869                         for ( y = yb ; y < ye ; y += g_xywindow_globals_private.blockSize )
1870                         {
1871                                 glRasterPos2f( x + ( g_xywindow_globals_private.blockSize / 2 ), y + ( g_xywindow_globals_private.blockSize / 2 ) );
1872                                 sprintf( text, "%i,%i",(int)floor( x / g_xywindow_globals_private.blockSize ), (int)floor( y / g_xywindow_globals_private.blockSize ) );
1873                                 GlobalOpenGL().drawString( text );
1874                         }
1875         }
1876
1877         glColor4f( 0, 0, 0, 0 );
1878 }
1879
1880 void XYWnd::DrawCameraIcon( const Vector3& origin, const Vector3& angles ){
1881         float x, y, fov, box;
1882         double a;
1883
1884         fov = 48 / m_fScale;
1885         box = 16 / m_fScale;
1886
1887         if ( m_viewType == XY ) {
1888                 x = origin[0];
1889                 y = origin[1];
1890                 a = degrees_to_radians( angles[CAMERA_YAW] );
1891         }
1892         else if ( m_viewType == YZ ) {
1893                 x = origin[1];
1894                 y = origin[2];
1895                 a = degrees_to_radians( angles[CAMERA_PITCH] );
1896         }
1897         else
1898         {
1899                 x = origin[0];
1900                 y = origin[2];
1901                 a = degrees_to_radians( angles[CAMERA_PITCH] );
1902         }
1903
1904         glColor3f( 0.0, 0.0, 1.0 );
1905         glBegin( GL_LINE_STRIP );
1906         glVertex3f( x - box,y,0 );
1907         glVertex3f( x,y + ( box / 2 ),0 );
1908         glVertex3f( x + box,y,0 );
1909         glVertex3f( x,y - ( box / 2 ),0 );
1910         glVertex3f( x - box,y,0 );
1911         glVertex3f( x + box,y,0 );
1912         glEnd();
1913
1914         glBegin( GL_LINE_STRIP );
1915         glVertex3f( x + static_cast<float>( fov * cos( a + c_pi / 4 ) ), y + static_cast<float>( fov * sin( a + c_pi / 4 ) ), 0 );
1916         glVertex3f( x, y, 0 );
1917         glVertex3f( x + static_cast<float>( fov * cos( a - c_pi / 4 ) ), y + static_cast<float>( fov * sin( a - c_pi / 4 ) ), 0 );
1918         glEnd();
1919
1920 }
1921
1922
1923 float Betwixt( float f1, float f2 ){
1924         if ( f1 > f2 ) {
1925                 return f2 + ( ( f1 - f2 ) / 2 );
1926         }
1927         else{
1928                 return f1 + ( ( f2 - f1 ) / 2 );
1929         }
1930 }
1931
1932
1933 // can be greatly simplified but per usual i am in a hurry
1934 // which is not an excuse, just a fact
1935 void XYWnd::PaintSizeInfo( int nDim1, int nDim2, Vector3& vMinBounds, Vector3& vMaxBounds ){
1936         if ( vector3_equal( vMinBounds, vMaxBounds ) ) {
1937                 return;
1938         }
1939         const char* g_pDimStrings[] = {"x:", "y:", "z:"};
1940         typedef const char* OrgStrings[2];
1941         const OrgStrings g_pOrgStrings[] = { { "x:", "y:", }, { "x:", "z:", }, { "y:", "z:", } };
1942
1943         Vector3 vSize( vector3_subtracted( vMaxBounds, vMinBounds ) );
1944
1945         glColor3f( g_xywindow_globals.color_selbrushes[0] * .65f,
1946                            g_xywindow_globals.color_selbrushes[1] * .65f,
1947                            g_xywindow_globals.color_selbrushes[2] * .65f );
1948
1949         StringOutputStream dimensions( 16 );
1950
1951         if ( m_viewType == XY ) {
1952                 glBegin( GL_LINES );
1953
1954                 glVertex3f( vMinBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale, 0.0f );
1955                 glVertex3f( vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f );
1956
1957                 glVertex3f( vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale, 0.0f );
1958                 glVertex3f( vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale, 0.0f );
1959
1960                 glVertex3f( vMaxBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale, 0.0f );
1961                 glVertex3f( vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f );
1962
1963
1964                 glVertex3f( vMaxBounds[nDim1] + 6.0f  / m_fScale, vMinBounds[nDim2], 0.0f );
1965                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2], 0.0f );
1966
1967                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2], 0.0f );
1968                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2], 0.0f );
1969
1970                 glVertex3f( vMaxBounds[nDim1] + 6.0f  / m_fScale, vMaxBounds[nDim2], 0.0f );
1971                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2], 0.0f );
1972
1973                 glEnd();
1974
1975                 glRasterPos3f( Betwixt( vMinBounds[nDim1], vMaxBounds[nDim1] ),  vMinBounds[nDim2] - 20.0f  / m_fScale, 0.0f );
1976                 dimensions << g_pDimStrings[nDim1] << vSize[nDim1];
1977                 GlobalOpenGL().drawString( dimensions.c_str() );
1978                 dimensions.clear();
1979
1980                 glRasterPos3f( vMaxBounds[nDim1] + 16.0f  / m_fScale, Betwixt( vMinBounds[nDim2], vMaxBounds[nDim2] ), 0.0f );
1981                 dimensions << g_pDimStrings[nDim2] << vSize[nDim2];
1982                 GlobalOpenGL().drawString( dimensions.c_str() );
1983                 dimensions.clear();
1984
1985                 glRasterPos3f( vMinBounds[nDim1] + 4, vMaxBounds[nDim2] + 8 / m_fScale, 0.0f );
1986                 dimensions << "(" << g_pOrgStrings[0][0] << vMinBounds[nDim1] << "  " << g_pOrgStrings[0][1] << vMaxBounds[nDim2] << ")";
1987                 GlobalOpenGL().drawString( dimensions.c_str() );
1988         }
1989         else if ( m_viewType == XZ ) {
1990                 glBegin( GL_LINES );
1991
1992                 glVertex3f( vMinBounds[nDim1], 0, vMinBounds[nDim2] - 6.0f  / m_fScale );
1993                 glVertex3f( vMinBounds[nDim1], 0, vMinBounds[nDim2] - 10.0f / m_fScale );
1994
1995                 glVertex3f( vMinBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f  / m_fScale );
1996                 glVertex3f( vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f  / m_fScale );
1997
1998                 glVertex3f( vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 6.0f  / m_fScale );
1999                 glVertex3f( vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f / m_fScale );
2000
2001
2002                 glVertex3f( vMaxBounds[nDim1] + 6.0f  / m_fScale, 0,vMinBounds[nDim2] );
2003                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMinBounds[nDim2] );
2004
2005                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMinBounds[nDim2] );
2006                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMaxBounds[nDim2] );
2007
2008                 glVertex3f( vMaxBounds[nDim1] + 6.0f  / m_fScale, 0,vMaxBounds[nDim2] );
2009                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMaxBounds[nDim2] );
2010
2011                 glEnd();
2012
2013                 glRasterPos3f( Betwixt( vMinBounds[nDim1], vMaxBounds[nDim1] ), 0, vMinBounds[nDim2] - 20.0f  / m_fScale );
2014                 dimensions << g_pDimStrings[nDim1] << vSize[nDim1];
2015                 GlobalOpenGL().drawString( dimensions.c_str() );
2016                 dimensions.clear();
2017
2018                 glRasterPos3f( vMaxBounds[nDim1] + 16.0f  / m_fScale, 0, Betwixt( vMinBounds[nDim2], vMaxBounds[nDim2] ) );
2019                 dimensions << g_pDimStrings[nDim2] << vSize[nDim2];
2020                 GlobalOpenGL().drawString( dimensions.c_str() );
2021                 dimensions.clear();
2022
2023                 glRasterPos3f( vMinBounds[nDim1] + 4, 0, vMaxBounds[nDim2] + 8 / m_fScale );
2024                 dimensions << "(" << g_pOrgStrings[1][0] << vMinBounds[nDim1] << "  " << g_pOrgStrings[1][1] << vMaxBounds[nDim2] << ")";
2025                 GlobalOpenGL().drawString( dimensions.c_str() );
2026         }
2027         else
2028         {
2029                 glBegin( GL_LINES );
2030
2031                 glVertex3f( 0, vMinBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale );
2032                 glVertex3f( 0, vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale );
2033
2034                 glVertex3f( 0, vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale );
2035                 glVertex3f( 0, vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale );
2036
2037                 glVertex3f( 0, vMaxBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale );
2038                 glVertex3f( 0, vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale );
2039
2040
2041                 glVertex3f( 0, vMaxBounds[nDim1] + 6.0f  / m_fScale, vMinBounds[nDim2] );
2042                 glVertex3f( 0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2] );
2043
2044                 glVertex3f( 0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2] );
2045                 glVertex3f( 0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2] );
2046
2047                 glVertex3f( 0, vMaxBounds[nDim1] + 6.0f  / m_fScale, vMaxBounds[nDim2] );
2048                 glVertex3f( 0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2] );
2049
2050                 glEnd();
2051
2052                 glRasterPos3f( 0, Betwixt( vMinBounds[nDim1], vMaxBounds[nDim1] ),  vMinBounds[nDim2] - 20.0f  / m_fScale );
2053                 dimensions << g_pDimStrings[nDim1] << vSize[nDim1];
2054                 GlobalOpenGL().drawString( dimensions.c_str() );
2055                 dimensions.clear();
2056
2057                 glRasterPos3f( 0, vMaxBounds[nDim1] + 16.0f  / m_fScale, Betwixt( vMinBounds[nDim2], vMaxBounds[nDim2] ) );
2058                 dimensions << g_pDimStrings[nDim2] << vSize[nDim2];
2059                 GlobalOpenGL().drawString( dimensions.c_str() );
2060                 dimensions.clear();
2061
2062                 glRasterPos3f( 0, vMinBounds[nDim1] + 4.0f, vMaxBounds[nDim2] + 8 / m_fScale );
2063                 dimensions << "(" << g_pOrgStrings[2][0] << vMinBounds[nDim1] << "  " << g_pOrgStrings[2][1] << vMaxBounds[nDim2] << ")";
2064                 GlobalOpenGL().drawString( dimensions.c_str() );
2065         }
2066 }
2067
2068 class XYRenderer : public Renderer
2069 {
2070 struct state_type
2071 {
2072         state_type() :
2073                 m_highlight( 0 ),
2074                 m_state( 0 ){
2075         }
2076         unsigned int m_highlight;
2077         Shader* m_state;
2078 };
2079 public:
2080 XYRenderer( RenderStateFlags globalstate, Shader* selected ) :
2081         m_globalstate( globalstate ),
2082         m_state_selected( selected ){
2083         ASSERT_NOTNULL( selected );
2084         m_state_stack.push_back( state_type() );
2085 }
2086
2087 void SetState( Shader* state, EStyle style ){
2088         ASSERT_NOTNULL( state );
2089         if ( style == eWireframeOnly ) {
2090                 m_state_stack.back().m_state = state;
2091         }
2092 }
2093 const EStyle getStyle() const {
2094         return eWireframeOnly;
2095 }
2096 void PushState(){
2097         m_state_stack.push_back( m_state_stack.back() );
2098 }
2099 void PopState(){
2100         ASSERT_MESSAGE( !m_state_stack.empty(), "popping empty stack" );
2101         m_state_stack.pop_back();
2102 }
2103 void Highlight( EHighlightMode mode, bool bEnable = true ){
2104         ( bEnable )
2105         ? m_state_stack.back().m_highlight |= mode
2106                                                                                   : m_state_stack.back().m_highlight &= ~mode;
2107 }
2108 void addRenderable( const OpenGLRenderable& renderable, const Matrix4& localToWorld ){
2109         if ( m_state_stack.back().m_highlight & ePrimitive ) {
2110                 m_state_selected->addRenderable( renderable, localToWorld );
2111         }
2112         else
2113         {
2114                 m_state_stack.back().m_state->addRenderable( renderable, localToWorld );
2115         }
2116 }
2117
2118 void render( const Matrix4& modelview, const Matrix4& projection ){
2119         GlobalShaderCache().render( m_globalstate, modelview, projection );
2120 }
2121 private:
2122 std::vector<state_type> m_state_stack;
2123 RenderStateFlags m_globalstate;
2124 Shader* m_state_selected;
2125 };
2126
2127 void XYWnd::updateProjection(){
2128         m_projection[0] = 1.0f / static_cast<float>( m_nWidth / 2 );
2129         m_projection[5] = 1.0f / static_cast<float>( m_nHeight / 2 );
2130         m_projection[10] = 1.0f / ( g_MaxWorldCoord * m_fScale );
2131
2132         m_projection[12] = 0.0f;
2133         m_projection[13] = 0.0f;
2134         m_projection[14] = -1.0f;
2135
2136         m_projection[1] =
2137                 m_projection[2] =
2138                         m_projection[3] =
2139
2140                                 m_projection[4] =
2141                                         m_projection[6] =
2142                                                 m_projection[7] =
2143
2144                                                         m_projection[8] =
2145                                                                 m_projection[9] =
2146                                                                         m_projection[11] = 0.0f;
2147
2148         m_projection[15] = 1.0f;
2149
2150         m_view.Construct( m_projection, m_modelview, m_nWidth, m_nHeight );
2151 }
2152
2153 // note: modelview matrix must have a uniform scale, otherwise strange things happen when rendering the rotation manipulator.
2154 void XYWnd::updateModelview(){
2155         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
2156         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
2157
2158         // translation
2159         m_modelview[12] = -m_vOrigin[nDim1] * m_fScale;
2160         m_modelview[13] = -m_vOrigin[nDim2] * m_fScale;
2161         m_modelview[14] = g_MaxWorldCoord * m_fScale;
2162
2163         // axis base
2164         switch ( m_viewType )
2165         {
2166         case XY:
2167                 m_modelview[0]  =  m_fScale;
2168                 m_modelview[1]  =  0;
2169                 m_modelview[2]  =  0;
2170
2171                 m_modelview[4]  =  0;
2172                 m_modelview[5]  =  m_fScale;
2173                 m_modelview[6]  =  0;
2174
2175                 m_modelview[8]  =  0;
2176                 m_modelview[9]  =  0;
2177                 m_modelview[10] = -m_fScale;
2178                 break;
2179         case XZ:
2180                 m_modelview[0]  =  m_fScale;
2181                 m_modelview[1]  =  0;
2182                 m_modelview[2]  =  0;
2183
2184                 m_modelview[4]  =  0;
2185                 m_modelview[5]  =  0;
2186                 m_modelview[6]  =  m_fScale;
2187
2188                 m_modelview[8]  =  0;
2189                 m_modelview[9]  =  m_fScale;
2190                 m_modelview[10] =  0;
2191                 break;
2192         case YZ:
2193                 m_modelview[0]  =  0;
2194                 m_modelview[1]  =  0;
2195                 m_modelview[2]  = -m_fScale;
2196
2197                 m_modelview[4]  =  m_fScale;
2198                 m_modelview[5]  =  0;
2199                 m_modelview[6]  =  0;
2200
2201                 m_modelview[8]  =  0;
2202                 m_modelview[9]  =  m_fScale;
2203                 m_modelview[10] =  0;
2204                 break;
2205         }
2206
2207         m_modelview[3] = m_modelview[7] = m_modelview[11] = 0;
2208         m_modelview[15] = 1;
2209
2210         m_view.Construct( m_projection, m_modelview, m_nWidth, m_nHeight );
2211 }
2212
2213 /*
2214    ==============
2215    XY_Draw
2216    ==============
2217  */
2218
2219 //#define DBG_SCENEDUMP
2220
2221 void XYWnd::XY_Draw(){
2222         //
2223         // clear
2224         //
2225         glViewport( 0, 0, m_nWidth, m_nHeight );
2226         glClearColor( g_xywindow_globals.color_gridback[0],
2227                                   g_xywindow_globals.color_gridback[1],
2228                                   g_xywindow_globals.color_gridback[2],0 );
2229
2230         glClear( GL_COLOR_BUFFER_BIT );
2231
2232         //
2233         // set up viewpoint
2234         //
2235
2236         glMatrixMode( GL_PROJECTION );
2237         glLoadMatrixf( reinterpret_cast<const float*>( &m_projection ) );
2238
2239         glMatrixMode( GL_MODELVIEW );
2240         glLoadIdentity();
2241         glScalef( m_fScale, m_fScale, 1 );
2242         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
2243         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
2244         glTranslatef( -m_vOrigin[nDim1], -m_vOrigin[nDim2], 0 );
2245
2246         glDisable( GL_LINE_STIPPLE );
2247         glLineWidth( 1 );
2248         glDisableClientState( GL_TEXTURE_COORD_ARRAY );
2249         glDisableClientState( GL_NORMAL_ARRAY );
2250         glDisableClientState( GL_COLOR_ARRAY );
2251         glDisable( GL_TEXTURE_2D );
2252         glDisable( GL_LIGHTING );
2253         glDisable( GL_COLOR_MATERIAL );
2254         glDisable( GL_DEPTH_TEST );
2255
2256         if ( m_backgroundActivated ) {
2257                 XY_DrawBackground();
2258         }
2259         XY_DrawGrid();
2260
2261         if ( g_xywindow_globals_private.show_blocks ) {
2262                 XY_DrawBlockGrid();
2263         }
2264
2265         glLoadMatrixf( reinterpret_cast<const float*>( &m_modelview ) );
2266
2267         unsigned int globalstate = RENDER_COLOURARRAY | RENDER_COLOURWRITE | RENDER_POLYGONSMOOTH | RENDER_LINESMOOTH;
2268         if ( !g_xywindow_globals.m_bNoStipple ) {
2269                 globalstate |= RENDER_LINESTIPPLE;
2270         }
2271
2272         {
2273                 XYRenderer renderer( globalstate, m_state_selected );
2274
2275                 Scene_Render( renderer, m_view );
2276
2277                 GlobalOpenGL_debugAssertNoErrors();
2278                 renderer.render( m_modelview, m_projection );
2279                 GlobalOpenGL_debugAssertNoErrors();
2280         }
2281
2282         glDepthMask( GL_FALSE );
2283
2284         GlobalOpenGL_debugAssertNoErrors();
2285
2286         glLoadMatrixf( reinterpret_cast<const float*>( &m_modelview ) );
2287
2288         GlobalOpenGL_debugAssertNoErrors();
2289         glDisable( GL_LINE_STIPPLE );
2290         GlobalOpenGL_debugAssertNoErrors();
2291         glLineWidth( 1 );
2292         GlobalOpenGL_debugAssertNoErrors();
2293         if ( GlobalOpenGL().GL_1_3() ) {
2294                 glActiveTexture( GL_TEXTURE0 );
2295                 glClientActiveTexture( GL_TEXTURE0 );
2296         }
2297         glDisableClientState( GL_TEXTURE_COORD_ARRAY );
2298         GlobalOpenGL_debugAssertNoErrors();
2299         glDisableClientState( GL_NORMAL_ARRAY );
2300         GlobalOpenGL_debugAssertNoErrors();
2301         glDisableClientState( GL_COLOR_ARRAY );
2302         GlobalOpenGL_debugAssertNoErrors();
2303         glDisable( GL_TEXTURE_2D );
2304         GlobalOpenGL_debugAssertNoErrors();
2305         glDisable( GL_LIGHTING );
2306         GlobalOpenGL_debugAssertNoErrors();
2307         glDisable( GL_COLOR_MATERIAL );
2308         GlobalOpenGL_debugAssertNoErrors();
2309
2310         GlobalOpenGL_debugAssertNoErrors();
2311
2312
2313         // size info
2314         if ( g_xywindow_globals_private.m_bSizePaint && GlobalSelectionSystem().countSelected() != 0 ) {
2315                 Vector3 min, max;
2316                 Select_GetBounds( min, max );
2317                 PaintSizeInfo( nDim1, nDim2, min, max );
2318         }
2319
2320         if ( g_bCrossHairs ) {
2321                 glColor4f( 0.2f, 0.9f, 0.2f, 0.8f );
2322                 glBegin( GL_LINES );
2323                 if ( m_viewType == XY ) {
2324                         glVertex2f( 2.0f * g_MinWorldCoord, m_mousePosition[1] );
2325                         glVertex2f( 2.0f * g_MaxWorldCoord, m_mousePosition[1] );
2326                         glVertex2f( m_mousePosition[0], 2.0f * g_MinWorldCoord );
2327                         glVertex2f( m_mousePosition[0], 2.0f * g_MaxWorldCoord );
2328                 }
2329                 else if ( m_viewType == YZ ) {
2330                         glVertex3f( m_mousePosition[0], 2.0f * g_MinWorldCoord, m_mousePosition[2] );
2331                         glVertex3f( m_mousePosition[0], 2.0f * g_MaxWorldCoord, m_mousePosition[2] );
2332                         glVertex3f( m_mousePosition[0], m_mousePosition[1], 2.0f * g_MinWorldCoord );
2333                         glVertex3f( m_mousePosition[0], m_mousePosition[1], 2.0f * g_MaxWorldCoord );
2334                 }
2335                 else
2336                 {
2337                         glVertex3f( 2.0f * g_MinWorldCoord, m_mousePosition[1], m_mousePosition[2] );
2338                         glVertex3f( 2.0f * g_MaxWorldCoord, m_mousePosition[1], m_mousePosition[2] );
2339                         glVertex3f( m_mousePosition[0], m_mousePosition[1], 2.0f * g_MinWorldCoord );
2340                         glVertex3f( m_mousePosition[0], m_mousePosition[1], 2.0f * g_MaxWorldCoord );
2341                 }
2342                 glEnd();
2343         }
2344
2345         if ( ClipMode() ) {
2346                 GlobalClipPoints_Draw( m_fScale );
2347         }
2348
2349         GlobalOpenGL_debugAssertNoErrors();
2350
2351         // reset modelview
2352         glLoadIdentity();
2353         glScalef( m_fScale, m_fScale, 1 );
2354         glTranslatef( -m_vOrigin[nDim1], -m_vOrigin[nDim2], 0 );
2355
2356         DrawCameraIcon( Camera_getOrigin( *g_pParentWnd->GetCamWnd() ), Camera_getAngles( *g_pParentWnd->GetCamWnd() ) );
2357
2358         Feedback_draw2D( m_viewType );
2359
2360         if ( g_xywindow_globals_private.show_outline ) {
2361                 if ( Active() ) {
2362                         glMatrixMode( GL_PROJECTION );
2363                         glLoadIdentity();
2364                         glOrtho( 0, m_nWidth, 0, m_nHeight, 0, 1 );
2365
2366                         glMatrixMode( GL_MODELVIEW );
2367                         glLoadIdentity();
2368
2369                         // four view mode doesn't colorize
2370                         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit ) {
2371                                 glColor3fv( vector3_to_array( g_xywindow_globals.color_viewname ) );
2372                         }
2373                         else
2374                         {
2375                                 switch ( m_viewType )
2376                                 {
2377                                 case YZ:
2378                                         glColor3fv( vector3_to_array( g_xywindow_globals.AxisColorX ) );
2379                                         break;
2380                                 case XZ:
2381                                         glColor3fv( vector3_to_array( g_xywindow_globals.AxisColorY ) );
2382                                         break;
2383                                 case XY:
2384                                         glColor3fv( vector3_to_array( g_xywindow_globals.AxisColorZ ) );
2385                                         break;
2386                                 }
2387                         }
2388                         glBegin( GL_LINE_LOOP );
2389                         glVertex2f( 0.5, 0.5 );
2390                         glVertex2f( m_nWidth - 0.5, 1 );
2391                         glVertex2f( m_nWidth - 0.5, m_nHeight - 0.5 );
2392                         glVertex2f( 0.5, m_nHeight - 0.5 );
2393                         glEnd();
2394                 }
2395         }
2396
2397         GlobalOpenGL_debugAssertNoErrors();
2398
2399         glFinish();
2400 }
2401
2402 void XYWnd_MouseToPoint( XYWnd* xywnd, int x, int y, Vector3& point ){
2403         xywnd->XY_ToPoint( x, y, point );
2404         xywnd->XY_SnapToGrid( point );
2405
2406         int nDim = ( xywnd->GetViewType() == XY ) ? 2 : ( xywnd->GetViewType() == YZ ) ? 0 : 1;
2407         float fWorkMid = float_mid( Select_getWorkZone().d_work_min[nDim], Select_getWorkZone().d_work_max[nDim] );
2408         point[nDim] = float_snapped( fWorkMid, GetGridSize() );
2409 }
2410
2411 void XYWnd::OnEntityCreate( const char* item ){
2412         StringOutputStream command;
2413         command << "entityCreate -class " << item;
2414         UndoableCommand undo( command.c_str() );
2415         Vector3 point;
2416         XYWnd_MouseToPoint( this, m_entityCreate_x, m_entityCreate_y, point );
2417         Entity_createFromSelection( item, point );
2418 }
2419
2420
2421
2422 void GetFocusPosition( Vector3& position ){
2423         if ( GlobalSelectionSystem().countSelected() != 0 ) {
2424                 Select_GetMid( position );
2425         }
2426         else
2427         {
2428                 position = Camera_getOrigin( *g_pParentWnd->GetCamWnd() );
2429         }
2430 }
2431
2432 void XYWnd_Focus( XYWnd* xywnd ){
2433         Vector3 position;
2434         GetFocusPosition( position );
2435         xywnd->PositionView( position );
2436 }
2437
2438 void XY_Split_Focus(){
2439         Vector3 position;
2440         GetFocusPosition( position );
2441         if ( g_pParentWnd->GetXYWnd() ) {
2442                 g_pParentWnd->GetXYWnd()->PositionView( position );
2443         }
2444         if ( g_pParentWnd->GetXZWnd() ) {
2445                 g_pParentWnd->GetXZWnd()->PositionView( position );
2446         }
2447         if ( g_pParentWnd->GetYZWnd() ) {
2448                 g_pParentWnd->GetYZWnd()->PositionView( position );
2449         }
2450 }
2451
2452 void XY_Focus(){
2453         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit ) {
2454                 // cannot do this in a split window
2455                 // do something else that the user may want here
2456                 XY_Split_Focus();
2457                 return;
2458         }
2459
2460         XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2461         XYWnd_Focus( xywnd );
2462 }
2463
2464 void XY_Top(){
2465         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating ) {
2466                 // cannot do this in a split window
2467                 // do something else that the user may want here
2468                 XY_Split_Focus();
2469                 return;
2470         }
2471
2472         XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2473         xywnd->SetViewType( XY );
2474         XYWnd_Focus( xywnd );
2475 }
2476
2477 void XY_Side(){
2478         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating ) {
2479                 // cannot do this in a split window
2480                 // do something else that the user may want here
2481                 XY_Split_Focus();
2482                 return;
2483         }
2484
2485         XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2486         xywnd->SetViewType( XZ );
2487         XYWnd_Focus( xywnd );
2488 }
2489
2490 void XY_Front(){
2491         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating ) {
2492                 // cannot do this in a split window
2493                 // do something else that the user may want here
2494                 XY_Split_Focus();
2495                 return;
2496         }
2497
2498         XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2499         xywnd->SetViewType( YZ );
2500         XYWnd_Focus( xywnd );
2501 }
2502
2503 void XY_Next(){
2504         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating ) {
2505                 // cannot do this in a split window
2506                 // do something else that the user may want here
2507                 XY_Split_Focus();
2508                 return;
2509         }
2510
2511         XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2512         if ( xywnd->GetViewType() == XY ) {
2513                 xywnd->SetViewType( XZ );
2514         }
2515         else if ( xywnd->GetViewType() ==  XZ ) {
2516                 xywnd->SetViewType( YZ );
2517         }
2518         else{
2519                 xywnd->SetViewType( XY );
2520         }
2521         XYWnd_Focus( xywnd );
2522 }
2523
2524 void XY_Zoom100(){
2525         if ( g_pParentWnd->GetXYWnd() ) {
2526                 g_pParentWnd->GetXYWnd()->SetScale( 1 );
2527         }
2528         if ( g_pParentWnd->GetXZWnd() ) {
2529                 g_pParentWnd->GetXZWnd()->SetScale( 1 );
2530         }
2531         if ( g_pParentWnd->GetYZWnd() ) {
2532                 g_pParentWnd->GetYZWnd()->SetScale( 1 );
2533         }
2534 }
2535
2536 void XY_ZoomIn(){
2537         g_pParentWnd->ActiveXY()->ZoomIn();
2538 }
2539
2540 // NOTE: the zoom out factor is 4/5, we could think about customizing it
2541 //  we don't go below a zoom factor corresponding to 10% of the max world size
2542 //  (this has to be computed against the window size)
2543 void XY_ZoomOut(){
2544         g_pParentWnd->ActiveXY()->ZoomOut();
2545 }
2546
2547
2548
2549 void ToggleShowCrosshair(){
2550         g_bCrossHairs ^= 1;
2551         XY_UpdateAllWindows();
2552 }
2553
2554 void ToggleShowSizeInfo(){
2555         g_xywindow_globals_private.m_bSizePaint = !g_xywindow_globals_private.m_bSizePaint;
2556         XY_UpdateAllWindows();
2557 }
2558
2559 void ToggleShowGrid(){
2560         g_xywindow_globals_private.d_showgrid = !g_xywindow_globals_private.d_showgrid;
2561         XY_UpdateAllWindows();
2562 }
2563
2564 ToggleShown g_xy_top_shown( true );
2565
2566 void XY_Top_Shown_Construct( GtkWindow* parent ){
2567         g_xy_top_shown.connect( GTK_WIDGET( parent ) );
2568 }
2569
2570 ToggleShown g_yz_side_shown( false );
2571
2572 void YZ_Side_Shown_Construct( GtkWindow* parent ){
2573         g_yz_side_shown.connect( GTK_WIDGET( parent ) );
2574 }
2575
2576 ToggleShown g_xz_front_shown( false );
2577
2578 void XZ_Front_Shown_Construct( GtkWindow* parent ){
2579         g_xz_front_shown.connect( GTK_WIDGET( parent ) );
2580 }
2581
2582
2583 class EntityClassMenu : public ModuleObserver
2584 {
2585 std::size_t m_unrealised;
2586 public:
2587 EntityClassMenu() : m_unrealised( 1 ){
2588 }
2589 void realise(){
2590         if ( --m_unrealised == 0 ) {
2591         }
2592 }
2593 void unrealise(){
2594         if ( ++m_unrealised == 1 ) {
2595                 if ( XYWnd::m_mnuDrop != 0 ) {
2596                         gtk_widget_destroy( GTK_WIDGET( XYWnd::m_mnuDrop ) );
2597                         XYWnd::m_mnuDrop = 0;
2598                 }
2599         }
2600 }
2601 };
2602
2603 EntityClassMenu g_EntityClassMenu;
2604
2605
2606
2607
2608 void ShowNamesToggle(){
2609         GlobalEntityCreator().setShowNames( !GlobalEntityCreator().getShowNames() );
2610         XY_UpdateAllWindows();
2611 }
2612 typedef FreeCaller<ShowNamesToggle> ShowNamesToggleCaller;
2613 void ShowNamesExport( const BoolImportCallback& importer ){
2614         importer( GlobalEntityCreator().getShowNames() );
2615 }
2616 typedef FreeCaller1<const BoolImportCallback&, ShowNamesExport> ShowNamesExportCaller;
2617
2618 void ShowAnglesToggle(){
2619         GlobalEntityCreator().setShowAngles( !GlobalEntityCreator().getShowAngles() );
2620         XY_UpdateAllWindows();
2621 }
2622 typedef FreeCaller<ShowAnglesToggle> ShowAnglesToggleCaller;
2623 void ShowAnglesExport( const BoolImportCallback& importer ){
2624         importer( GlobalEntityCreator().getShowAngles() );
2625 }
2626 typedef FreeCaller1<const BoolImportCallback&, ShowAnglesExport> ShowAnglesExportCaller;
2627
2628 void ShowBlocksToggle(){
2629         g_xywindow_globals_private.show_blocks ^= 1;
2630         XY_UpdateAllWindows();
2631 }
2632 typedef FreeCaller<ShowBlocksToggle> ShowBlocksToggleCaller;
2633 void ShowBlocksExport( const BoolImportCallback& importer ){
2634         importer( g_xywindow_globals_private.show_blocks );
2635 }
2636 typedef FreeCaller1<const BoolImportCallback&, ShowBlocksExport> ShowBlocksExportCaller;
2637
2638 void ShowCoordinatesToggle(){
2639         g_xywindow_globals_private.show_coordinates ^= 1;
2640         XY_UpdateAllWindows();
2641 }
2642 typedef FreeCaller<ShowCoordinatesToggle> ShowCoordinatesToggleCaller;
2643 void ShowCoordinatesExport( const BoolImportCallback& importer ){
2644         importer( g_xywindow_globals_private.show_coordinates );
2645 }
2646 typedef FreeCaller1<const BoolImportCallback&, ShowCoordinatesExport> ShowCoordinatesExportCaller;
2647
2648 void ShowOutlineToggle(){
2649         g_xywindow_globals_private.show_outline ^= 1;
2650         XY_UpdateAllWindows();
2651 }
2652 typedef FreeCaller<ShowOutlineToggle> ShowOutlineToggleCaller;
2653 void ShowOutlineExport( const BoolImportCallback& importer ){
2654         importer( g_xywindow_globals_private.show_outline );
2655 }
2656 typedef FreeCaller1<const BoolImportCallback&, ShowOutlineExport> ShowOutlineExportCaller;
2657
2658 void ShowAxesToggle(){
2659         g_xywindow_globals_private.show_axis ^= 1;
2660         XY_UpdateAllWindows();
2661 }
2662 typedef FreeCaller<ShowAxesToggle> ShowAxesToggleCaller;
2663 void ShowAxesExport( const BoolImportCallback& importer ){
2664         importer( g_xywindow_globals_private.show_axis );
2665 }
2666 typedef FreeCaller1<const BoolImportCallback&, ShowAxesExport> ShowAxesExportCaller;
2667
2668 void ShowWorkzoneToggle(){
2669         g_xywindow_globals_private.d_show_work ^= 1;
2670         XY_UpdateAllWindows();
2671 }
2672 typedef FreeCaller<ShowWorkzoneToggle> ShowWorkzoneToggleCaller;
2673 void ShowWorkzoneExport( const BoolImportCallback& importer ){
2674         importer( g_xywindow_globals_private.d_show_work );
2675 }
2676 typedef FreeCaller1<const BoolImportCallback&, ShowWorkzoneExport> ShowWorkzoneExportCaller;
2677
2678 ShowNamesExportCaller g_show_names_caller;
2679 BoolExportCallback g_show_names_callback( g_show_names_caller );
2680 ToggleItem g_show_names( g_show_names_callback );
2681
2682 ShowAnglesExportCaller g_show_angles_caller;
2683 BoolExportCallback g_show_angles_callback( g_show_angles_caller );
2684 ToggleItem g_show_angles( g_show_angles_callback );
2685
2686 ShowBlocksExportCaller g_show_blocks_caller;
2687 BoolExportCallback g_show_blocks_callback( g_show_blocks_caller );
2688 ToggleItem g_show_blocks( g_show_blocks_callback );
2689
2690 ShowCoordinatesExportCaller g_show_coordinates_caller;
2691 BoolExportCallback g_show_coordinates_callback( g_show_coordinates_caller );
2692 ToggleItem g_show_coordinates( g_show_coordinates_callback );
2693
2694 ShowOutlineExportCaller g_show_outline_caller;
2695 BoolExportCallback g_show_outline_callback( g_show_outline_caller );
2696 ToggleItem g_show_outline( g_show_outline_callback );
2697
2698 ShowAxesExportCaller g_show_axes_caller;
2699 BoolExportCallback g_show_axes_callback( g_show_axes_caller );
2700 ToggleItem g_show_axes( g_show_axes_callback );
2701
2702 ShowWorkzoneExportCaller g_show_workzone_caller;
2703 BoolExportCallback g_show_workzone_callback( g_show_workzone_caller );
2704 ToggleItem g_show_workzone( g_show_workzone_callback );
2705
2706 void XYShow_registerCommands(){
2707         GlobalToggles_insert( "ShowAngles", ShowAnglesToggleCaller(), ToggleItem::AddCallbackCaller( g_show_angles ) );
2708         GlobalToggles_insert( "ShowNames", ShowNamesToggleCaller(), ToggleItem::AddCallbackCaller( g_show_names ) );
2709         GlobalToggles_insert( "ShowBlocks", ShowBlocksToggleCaller(), ToggleItem::AddCallbackCaller( g_show_blocks ) );
2710         GlobalToggles_insert( "ShowCoordinates", ShowCoordinatesToggleCaller(), ToggleItem::AddCallbackCaller( g_show_coordinates ) );
2711         GlobalToggles_insert( "ShowWindowOutline", ShowOutlineToggleCaller(), ToggleItem::AddCallbackCaller( g_show_outline ) );
2712         GlobalToggles_insert( "ShowAxes", ShowAxesToggleCaller(), ToggleItem::AddCallbackCaller( g_show_axes ) );
2713         GlobalToggles_insert( "ShowWorkzone", ShowWorkzoneToggleCaller(), ToggleItem::AddCallbackCaller( g_show_workzone ) );
2714 }
2715
2716 void XYWnd_registerShortcuts(){
2717         command_connect_accelerator( "ToggleCrosshairs" );
2718         command_connect_accelerator( "ToggleSizePaint" );
2719 }
2720
2721
2722
2723 void Orthographic_constructPreferences( PreferencesPage& page ){
2724         page.appendCheckBox( "", "Solid selection boxes", g_xywindow_globals.m_bNoStipple );
2725         page.appendCheckBox( "", "Display size info", g_xywindow_globals_private.m_bSizePaint );
2726         page.appendCheckBox( "", "Chase mouse during drags", g_xywindow_globals_private.m_bChaseMouse );
2727         page.appendCheckBox( "", "Update views on camera move", g_xywindow_globals_private.m_bCamXYUpdate );
2728 }
2729 void Orthographic_constructPage( PreferenceGroup& group ){
2730         PreferencesPage page( group.createPage( "Orthographic", "Orthographic View Preferences" ) );
2731         Orthographic_constructPreferences( page );
2732 }
2733 void Orthographic_registerPreferencesPage(){
2734         PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, Orthographic_constructPage>() );
2735 }
2736
2737 void Clipper_constructPreferences( PreferencesPage& page ){
2738         page.appendCheckBox( "", "Clipper tool uses caulk", g_clip_useCaulk );
2739 }
2740 void Clipper_constructPage( PreferenceGroup& group ){
2741         PreferencesPage page( group.createPage( "Clipper", "Clipper Tool Settings" ) );
2742         Clipper_constructPreferences( page );
2743 }
2744 void Clipper_registerPreferencesPage(){
2745         PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, Clipper_constructPage>() );
2746 }
2747
2748
2749 #include "preferencesystem.h"
2750 #include "stringio.h"
2751
2752
2753
2754
2755 void ToggleShown_importBool( ToggleShown& self, bool value ){
2756         self.set( value );
2757 }
2758 typedef ReferenceCaller1<ToggleShown, bool, ToggleShown_importBool> ToggleShownImportBoolCaller;
2759 void ToggleShown_exportBool( const ToggleShown& self, const BoolImportCallback& importer ){
2760         importer( self.active() );
2761 }
2762 typedef ConstReferenceCaller1<ToggleShown, const BoolImportCallback&, ToggleShown_exportBool> ToggleShownExportBoolCaller;
2763
2764
2765 void XYWindow_Construct(){
2766         GlobalCommands_insert( "ToggleCrosshairs", FreeCaller<ToggleShowCrosshair>(), Accelerator( 'X', (GdkModifierType)GDK_SHIFT_MASK ) );
2767         GlobalCommands_insert( "ToggleSizePaint", FreeCaller<ToggleShowSizeInfo>(), Accelerator( 'J' ) );
2768         GlobalCommands_insert( "ToggleGrid", FreeCaller<ToggleShowGrid>(), Accelerator( '0' ) );
2769
2770         GlobalToggles_insert( "ToggleView", ToggleShown::ToggleCaller( g_xy_top_shown ), ToggleItem::AddCallbackCaller( g_xy_top_shown.m_item ), Accelerator( 'V', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
2771         GlobalToggles_insert( "ToggleSideView", ToggleShown::ToggleCaller( g_yz_side_shown ), ToggleItem::AddCallbackCaller( g_yz_side_shown.m_item ) );
2772         GlobalToggles_insert( "ToggleFrontView", ToggleShown::ToggleCaller( g_xz_front_shown ), ToggleItem::AddCallbackCaller( g_xz_front_shown.m_item ) );
2773         GlobalCommands_insert( "NextView", FreeCaller<XY_Next>(), Accelerator( GDK_Tab, (GdkModifierType)GDK_CONTROL_MASK ) );
2774         GlobalCommands_insert( "ZoomIn", FreeCaller<XY_ZoomIn>(), Accelerator( GDK_Delete ) );
2775         GlobalCommands_insert( "ZoomOut", FreeCaller<XY_ZoomOut>(), Accelerator( GDK_Insert ) );
2776         GlobalCommands_insert( "ViewTop", FreeCaller<XY_Top>(), Accelerator( GDK_KP_Home ) );
2777         GlobalCommands_insert( "ViewSide", FreeCaller<XY_Side>(), Accelerator( GDK_KP_Page_Down ) );
2778         GlobalCommands_insert( "ViewFront", FreeCaller<XY_Front>(), Accelerator( GDK_KP_End ) );
2779         GlobalCommands_insert( "Zoom100", FreeCaller<XY_Zoom100>() );
2780         GlobalCommands_insert( "CenterXYView", FreeCaller<XY_Focus>(), Accelerator( GDK_Tab, (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
2781
2782         GlobalPreferenceSystem().registerPreference( "ClipCaulk", BoolImportStringCaller( g_clip_useCaulk ), BoolExportStringCaller( g_clip_useCaulk ) );
2783
2784         GlobalPreferenceSystem().registerPreference( "NewRightClick", BoolImportStringCaller( g_xywindow_globals.m_bRightClick ), BoolExportStringCaller( g_xywindow_globals.m_bRightClick ) );
2785         GlobalPreferenceSystem().registerPreference( "ImprovedWheelZoom", BoolImportStringCaller( g_xywindow_globals.m_bImprovedWheelZoom ), BoolExportStringCaller( g_xywindow_globals.m_bImprovedWheelZoom ) );
2786         GlobalPreferenceSystem().registerPreference( "ChaseMouse", BoolImportStringCaller( g_xywindow_globals_private.m_bChaseMouse ), BoolExportStringCaller( g_xywindow_globals_private.m_bChaseMouse ) );
2787         GlobalPreferenceSystem().registerPreference( "SizePainting", BoolImportStringCaller( g_xywindow_globals_private.m_bSizePaint ), BoolExportStringCaller( g_xywindow_globals_private.m_bSizePaint ) );
2788         GlobalPreferenceSystem().registerPreference( "ShowCrosshair", BoolImportStringCaller( g_bCrossHairs ), BoolExportStringCaller( g_bCrossHairs ) );
2789         GlobalPreferenceSystem().registerPreference( "NoStipple", BoolImportStringCaller( g_xywindow_globals.m_bNoStipple ), BoolExportStringCaller( g_xywindow_globals.m_bNoStipple ) );
2790         GlobalPreferenceSystem().registerPreference( "SI_ShowCoords", BoolImportStringCaller( g_xywindow_globals_private.show_coordinates ), BoolExportStringCaller( g_xywindow_globals_private.show_coordinates ) );
2791         GlobalPreferenceSystem().registerPreference( "SI_ShowOutlines", BoolImportStringCaller( g_xywindow_globals_private.show_outline ), BoolExportStringCaller( g_xywindow_globals_private.show_outline ) );
2792         GlobalPreferenceSystem().registerPreference( "SI_ShowAxis", BoolImportStringCaller( g_xywindow_globals_private.show_axis ), BoolExportStringCaller( g_xywindow_globals_private.show_axis ) );
2793         GlobalPreferenceSystem().registerPreference( "CamXYUpdate", BoolImportStringCaller( g_xywindow_globals_private.m_bCamXYUpdate ), BoolExportStringCaller( g_xywindow_globals_private.m_bCamXYUpdate ) );
2794         GlobalPreferenceSystem().registerPreference( "ShowWorkzone", BoolImportStringCaller( g_xywindow_globals_private.d_show_work ), BoolExportStringCaller( g_xywindow_globals_private.d_show_work ) );
2795
2796         GlobalPreferenceSystem().registerPreference( "SI_AxisColors0", Vector3ImportStringCaller( g_xywindow_globals.AxisColorX ), Vector3ExportStringCaller( g_xywindow_globals.AxisColorX ) );
2797         GlobalPreferenceSystem().registerPreference( "SI_AxisColors1", Vector3ImportStringCaller( g_xywindow_globals.AxisColorY ), Vector3ExportStringCaller( g_xywindow_globals.AxisColorY ) );
2798         GlobalPreferenceSystem().registerPreference( "SI_AxisColors2", Vector3ImportStringCaller( g_xywindow_globals.AxisColorZ ), Vector3ExportStringCaller( g_xywindow_globals.AxisColorZ ) );
2799         GlobalPreferenceSystem().registerPreference( "SI_Colors1", Vector3ImportStringCaller( g_xywindow_globals.color_gridback ), Vector3ExportStringCaller( g_xywindow_globals.color_gridback ) );
2800         GlobalPreferenceSystem().registerPreference( "SI_Colors2", Vector3ImportStringCaller( g_xywindow_globals.color_gridminor ), Vector3ExportStringCaller( g_xywindow_globals.color_gridminor ) );
2801         GlobalPreferenceSystem().registerPreference( "SI_Colors3", Vector3ImportStringCaller( g_xywindow_globals.color_gridmajor ), Vector3ExportStringCaller( g_xywindow_globals.color_gridmajor ) );
2802         GlobalPreferenceSystem().registerPreference( "SI_Colors6", Vector3ImportStringCaller( g_xywindow_globals.color_gridblock ), Vector3ExportStringCaller( g_xywindow_globals.color_gridblock ) );
2803         GlobalPreferenceSystem().registerPreference( "SI_Colors7", Vector3ImportStringCaller( g_xywindow_globals.color_gridtext ), Vector3ExportStringCaller( g_xywindow_globals.color_gridtext ) );
2804         GlobalPreferenceSystem().registerPreference( "SI_Colors8", Vector3ImportStringCaller( g_xywindow_globals.color_brushes ), Vector3ExportStringCaller( g_xywindow_globals.color_brushes ) );
2805         GlobalPreferenceSystem().registerPreference( "SI_Colors14", Vector3ImportStringCaller( g_xywindow_globals.color_gridmajor_alt ), Vector3ExportStringCaller( g_xywindow_globals.color_gridmajor_alt ) );
2806
2807
2808         GlobalPreferenceSystem().registerPreference( "XZVIS", makeBoolStringImportCallback( ToggleShownImportBoolCaller( g_xz_front_shown ) ), makeBoolStringExportCallback( ToggleShownExportBoolCaller( g_xz_front_shown ) ) );
2809         GlobalPreferenceSystem().registerPreference( "YZVIS", makeBoolStringImportCallback( ToggleShownImportBoolCaller( g_yz_side_shown ) ), makeBoolStringExportCallback( ToggleShownExportBoolCaller( g_yz_side_shown ) ) );
2810
2811         Orthographic_registerPreferencesPage();
2812         Clipper_registerPreferencesPage();
2813
2814         XYWnd::captureStates();
2815         GlobalEntityClassManager().attach( g_EntityClassMenu );
2816 }
2817
2818 void XYWindow_Destroy(){
2819         GlobalEntityClassManager().detach( g_EntityClassMenu );
2820         XYWnd::releaseStates();
2821 }