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