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