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