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