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