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