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