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