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