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