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