]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/xywindow.cpp
- Updated UFA:Plugin (mattn2)
[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   onDestroyed();
892
893   if(m_mnuDrop != 0)
894   {
895     gtk_widget_destroy(GTK_WIDGET(m_mnuDrop));
896     m_mnuDrop = 0;
897   }
898
899   g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_sizeHandler);
900   g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_exposeHandler);
901
902   gtk_widget_unref(m_gl_widget);
903
904   m_window_observer->release();
905 }
906
907 void XYWnd::captureStates()
908 {
909   m_state_selected = GlobalShaderCache().capture("$XY_OVERLAY");
910 }
911
912 void XYWnd::releaseStates()
913 {
914   GlobalShaderCache().release("$XY_OVERLAY");
915 }
916
917 const Vector3& XYWnd::GetOrigin()
918 {
919   return m_vOrigin;
920 }
921
922 void XYWnd::SetOrigin(const Vector3& origin)
923 {
924   m_vOrigin = origin;
925   updateModelview();
926 }
927
928 void XYWnd::Scroll(int x, int y)
929 {
930   int nDim1 = (m_viewType == YZ) ? 1 : 0;
931   int nDim2 = (m_viewType == XY) ? 1 : 2;
932   m_vOrigin[nDim1] += x / m_fScale;
933   m_vOrigin[nDim2] += y / m_fScale;
934   updateModelview();
935   queueDraw();
936 }
937
938 unsigned int Clipper_buttons()
939 {
940   return RAD_LBUTTON;
941 }
942
943 void XYWnd::DropClipPoint(int pointx, int pointy)
944 {
945   Vector3 point;
946
947   XY_ToPoint(pointx, pointy, point);
948
949   Vector3 mid;
950   Select_GetMid(mid);
951   g_clip_viewtype = static_cast<VIEWTYPE>(GetViewType());
952   int nDim = (g_clip_viewtype == YZ ) ? nDim = 0 : ( (g_clip_viewtype == XZ) ? nDim = 1 : nDim = 2 );
953   point[nDim] = mid[nDim];
954   vector3_snap(point, GetGridSize());
955   NewClipPoint(point);
956 }
957
958 void XYWnd::Clipper_OnLButtonDown(int x, int y)
959 {
960   Vector3 mousePosition;
961   XY_ToPoint(x, y , mousePosition);
962   g_pMovingClip = GlobalClipPoints_Find(mousePosition, (VIEWTYPE)m_viewType, m_fScale);
963   if(!g_pMovingClip)
964   {
965     DropClipPoint(x, y);
966   }
967 }
968
969 void XYWnd::Clipper_OnLButtonUp(int x, int y)
970 {
971   if (g_pMovingClip)
972   {
973     g_pMovingClip = 0;
974   }
975 }
976
977 void XYWnd::Clipper_OnMouseMoved(int x, int y)
978 {
979   if (g_pMovingClip)
980   {
981     XY_ToPoint(x, y , g_pMovingClip->m_ptClip);
982     XY_SnapToGrid(g_pMovingClip->m_ptClip);
983     Clip_Update();
984     ClipperChangeNotify();
985   }
986 }
987
988 void XYWnd::Clipper_Crosshair_OnMouseMoved(int x, int y)
989 {
990   Vector3 mousePosition;
991   XY_ToPoint(x, y , mousePosition);
992   if(ClipMode() && GlobalClipPoints_Find(mousePosition, (VIEWTYPE)m_viewType, m_fScale) != 0)
993   {
994     GdkCursor *cursor;
995     cursor = gdk_cursor_new (GDK_CROSSHAIR);
996     gdk_window_set_cursor (m_gl_widget->window, cursor);
997     gdk_cursor_unref (cursor);
998   }
999   else
1000   {
1001     gdk_window_set_cursor (m_gl_widget->window, 0);
1002   }
1003 }
1004
1005 unsigned int MoveCamera_buttons()
1006 {
1007   return RAD_CONTROL | (g_glwindow_globals.m_nMouseType == ETwoButton ? RAD_RBUTTON : RAD_MBUTTON);
1008 }
1009
1010 void XYWnd_PositionCamera(XYWnd* xywnd, int x, int y, CamWnd& camwnd)
1011 {
1012   Vector3 origin(Camera_getOrigin(camwnd));
1013   xywnd->XY_ToPoint(x, y, origin);
1014   xywnd->XY_SnapToGrid(origin);
1015   Camera_setOrigin(camwnd, origin);
1016 }
1017
1018 unsigned int OrientCamera_buttons()
1019 {
1020   if(g_glwindow_globals.m_nMouseType == ETwoButton)
1021     return RAD_RBUTTON | RAD_SHIFT | RAD_CONTROL;
1022   return RAD_MBUTTON;
1023 }
1024
1025 void XYWnd_OrientCamera(XYWnd* xywnd, int x, int y, CamWnd& camwnd)
1026 {
1027   Vector3       point = g_vector3_identity;
1028   xywnd->XY_ToPoint(x, y, point);
1029   xywnd->XY_SnapToGrid(point);
1030   vector3_subtract(point, Camera_getOrigin(camwnd));
1031
1032   int n1 = (xywnd->GetViewType() == XY) ? 1 : 2;
1033   int n2 = (xywnd->GetViewType() == YZ) ? 1 : 0;
1034   int nAngle = (xywnd->GetViewType() == XY) ? CAMERA_YAW : CAMERA_PITCH;
1035   if (point[n1] || point[n2])
1036   {
1037     Vector3 angles(Camera_getAngles(camwnd));
1038     angles[nAngle] = static_cast<float>(radians_to_degrees(atan2 (point[n1], point[n2])));
1039     Camera_setAngles(camwnd, angles);
1040   }
1041 }
1042
1043 /*
1044 ==============
1045 NewBrushDrag
1046 ==============
1047 */
1048 unsigned int NewBrushDrag_buttons()
1049 {
1050   return RAD_LBUTTON;
1051 }
1052
1053 void XYWnd::NewBrushDrag_Begin(int x, int y)
1054 {
1055   m_NewBrushDrag = 0;
1056   m_nNewBrushPressx = x;
1057   m_nNewBrushPressy = y;
1058
1059   m_bNewBrushDrag = true;
1060   GlobalUndoSystem().start();
1061 }
1062
1063 void XYWnd::NewBrushDrag_End(int x, int y)
1064 {
1065   if(m_NewBrushDrag != 0)
1066   {
1067     GlobalUndoSystem().finish("brushDragNew");
1068   }
1069 }
1070
1071 void XYWnd::NewBrushDrag(int x, int y)
1072 {
1073   Vector3       mins, maxs;
1074   XY_ToPoint(m_nNewBrushPressx, m_nNewBrushPressy, mins);
1075   XY_SnapToGrid(mins);
1076         XY_ToPoint(x, y, maxs);
1077   XY_SnapToGrid(maxs);
1078
1079   int nDim = (m_viewType == XY) ? 2 : (m_viewType == YZ) ? 0 : 1;
1080
1081   mins[nDim] = float_snapped(Select_getWorkZone().d_work_min[nDim], GetGridSize());
1082   maxs[nDim] = float_snapped(Select_getWorkZone().d_work_max[nDim], GetGridSize());
1083
1084   if (maxs[nDim] <= mins[nDim])
1085     maxs[nDim] = mins[nDim] + GetGridSize();
1086
1087   for(int i=0 ; i<3 ; i++)
1088   {
1089     if (mins[i] == maxs[i])
1090       return;   // don't create a degenerate brush
1091     if (mins[i] > maxs[i])
1092     {
1093       float     temp = mins[i];
1094       mins[i] = maxs[i];
1095       maxs[i] = temp;
1096     }
1097   }
1098
1099   if(m_NewBrushDrag == 0)
1100   {
1101     NodeSmartReference node(GlobalBrushCreator().createBrush());
1102     Node_getTraversable(Map_FindOrInsertWorldspawn(g_map))->insert(node);
1103
1104     scene::Path brushpath(makeReference(GlobalSceneGraph().root()));
1105     brushpath.push(makeReference(*Map_GetWorldspawn(g_map)));
1106     brushpath.push(makeReference(node.get()));
1107     selectPath(brushpath, true);
1108
1109     m_NewBrushDrag = node.get_pointer();
1110   }
1111
1112   Scene_BrushResize_Selected(GlobalSceneGraph(), aabb_for_minmax(mins, maxs), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()));
1113 }
1114
1115 void entitycreate_activated(GtkWidget* item)
1116 {
1117   scene::Node* world_node = Map_FindWorldspawn(g_map);
1118   const char* entity_name = gtk_label_get_text(GTK_LABEL(GTK_BIN(item)->child));
1119
1120   if(!(world_node && string_equal(entity_name, "worldspawn")))
1121   {
1122     g_pParentWnd->ActiveXY()->OnEntityCreate(entity_name);
1123   } else {
1124     GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(MainFrame_getWindow()), "There's already a worldspawn in your map!"
1125                                         "",
1126                                         "Info",
1127                                         eMB_OK,
1128                                         eMB_ICONDEFAULT);
1129   }
1130 }
1131
1132 void EntityClassMenu_addItem(GtkMenu* menu, const char* name)
1133 {
1134   GtkMenuItem* item = GTK_MENU_ITEM(gtk_menu_item_new_with_label(name));
1135   g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(entitycreate_activated), item);
1136   gtk_widget_show(GTK_WIDGET(item));
1137   menu_add_item(menu, item);
1138 }
1139
1140 class EntityClassMenuInserter : public EntityClassVisitor
1141 {
1142   typedef std::pair<GtkMenu*, CopiedString> MenuPair;
1143   typedef std::vector<MenuPair> MenuStack;
1144   MenuStack m_stack;
1145   CopiedString m_previous;
1146 public:
1147   EntityClassMenuInserter(GtkMenu* menu)
1148   {
1149     m_stack.reserve(2);
1150     m_stack.push_back(MenuPair(menu, ""));
1151   }
1152   ~EntityClassMenuInserter()
1153   {
1154     if(!string_empty(m_previous.c_str()))
1155     {
1156       addItem(m_previous.c_str(), "");
1157     }
1158   }
1159   void visit(EntityClass* e)
1160   {
1161     ASSERT_MESSAGE(!string_empty(e->name()), "entity-class has no name");
1162     if(!string_empty(m_previous.c_str()))
1163     {
1164       addItem(m_previous.c_str(), e->name());
1165     }
1166     m_previous = e->name();
1167   }
1168   void pushMenu(const CopiedString& name)
1169   {
1170     GtkMenuItem* item = GTK_MENU_ITEM(gtk_menu_item_new_with_label(name.c_str()));
1171     gtk_widget_show(GTK_WIDGET(item));
1172     container_add_widget(GTK_CONTAINER(m_stack.back().first), GTK_WIDGET(item));
1173
1174     GtkMenu* submenu = GTK_MENU(gtk_menu_new());
1175     gtk_menu_item_set_submenu(item, GTK_WIDGET(submenu));
1176
1177     m_stack.push_back(MenuPair(submenu, name));
1178   }
1179   void popMenu()
1180   {
1181     m_stack.pop_back();
1182   }
1183   void addItem(const char* name, const char* next)
1184   {
1185     const char* underscore = strchr(name, '_');
1186
1187     if(underscore != 0 && underscore != name)
1188     {
1189       bool nextEqual = string_equal_n(name, next, (underscore + 1) - name);
1190       const char* parent = m_stack.back().second.c_str();
1191
1192       if(!string_empty(parent)
1193         && string_length(parent) == std::size_t(underscore - name)
1194         && string_equal_n(name, parent, underscore - name)) // this is a child
1195       {
1196       }
1197       else if(nextEqual)
1198       {
1199         if(m_stack.size() == 2)
1200         {
1201           popMenu();
1202         }
1203         pushMenu(CopiedString(StringRange(name, underscore)));
1204       }
1205       else if(m_stack.size() == 2)
1206       {
1207         popMenu();
1208       }
1209     }
1210     else if(m_stack.size() == 2)
1211     {
1212       popMenu();
1213     }
1214
1215     EntityClassMenu_addItem(m_stack.back().first, name);
1216   }
1217 };
1218
1219 void XYWnd::OnContextMenu()
1220 {
1221   if (g_xywindow_globals.m_bRightClick == false)
1222     return;
1223
1224   if (m_mnuDrop == 0) // first time, load it up
1225   {
1226     GtkMenu* menu = m_mnuDrop = GTK_MENU(gtk_menu_new());
1227
1228     EntityClassMenuInserter inserter(menu);
1229     GlobalEntityClassManager().forEach(inserter);
1230   }
1231
1232   gtk_menu_popup(m_mnuDrop, 0, 0, 0, 0, 1, GDK_CURRENT_TIME);
1233 }
1234
1235 FreezePointer g_xywnd_freezePointer;
1236
1237 unsigned int Move_buttons()
1238 {
1239   return RAD_RBUTTON;
1240 }
1241
1242 void XYWnd_moveDelta(int x, int y, unsigned int state, void* data)
1243 {
1244   reinterpret_cast<XYWnd*>(data)->EntityCreate_MouseMove(x, y);
1245   reinterpret_cast<XYWnd*>(data)->Scroll(-x, y);
1246 }
1247
1248 gboolean XYWnd_Move_focusOut(GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd)
1249 {
1250   xywnd->Move_End();
1251   return FALSE;
1252 }
1253
1254 void XYWnd::Move_Begin()
1255 {
1256   if(m_move_started)
1257   {
1258     Move_End();
1259   }
1260   m_move_started = true;
1261   g_xywnd_freezePointer.freeze_pointer(m_parent != 0 ? m_parent : MainFrame_getWindow(), XYWnd_moveDelta, this);
1262   m_move_focusOut = g_signal_connect(G_OBJECT(m_gl_widget), "focus_out_event", G_CALLBACK(XYWnd_Move_focusOut), this);
1263 }
1264
1265 void XYWnd::Move_End()
1266 {
1267   m_move_started = false;
1268   g_xywnd_freezePointer.unfreeze_pointer(m_parent != 0 ? m_parent : MainFrame_getWindow());
1269   g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_move_focusOut);
1270 }
1271
1272 unsigned int Zoom_buttons()
1273 {
1274   return RAD_RBUTTON | RAD_SHIFT;
1275 }
1276
1277 int g_dragZoom = 0;
1278
1279 void XYWnd_zoomDelta(int x, int y, unsigned int state, void* data)
1280 {
1281   if(y != 0)
1282   {
1283     g_dragZoom += y;
1284
1285     while(abs(g_dragZoom) > 8)
1286     {
1287       if(g_dragZoom > 0)
1288       {
1289         XYWnd_ZoomOut(reinterpret_cast<XYWnd*>(data));
1290         g_dragZoom -= 8;
1291       }
1292       else
1293       {
1294         XYWnd_ZoomIn(reinterpret_cast<XYWnd*>(data));
1295         g_dragZoom += 8;
1296       }
1297     }
1298   }
1299 }
1300
1301 gboolean XYWnd_Zoom_focusOut(GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd)
1302 {
1303   xywnd->Zoom_End();
1304   return FALSE;
1305 }
1306
1307 void XYWnd::Zoom_Begin()
1308 {
1309   if(m_zoom_started)
1310   {
1311     Zoom_End();
1312   }
1313   m_zoom_started = true;
1314   g_dragZoom = 0;
1315   g_xywnd_freezePointer.freeze_pointer(m_parent != 0 ? m_parent : MainFrame_getWindow(), XYWnd_zoomDelta, this);
1316   m_zoom_focusOut = g_signal_connect(G_OBJECT(m_gl_widget), "focus_out_event", G_CALLBACK(XYWnd_Zoom_focusOut), this);
1317 }
1318
1319 void XYWnd::Zoom_End()
1320 {
1321   m_zoom_started = false;
1322   g_xywnd_freezePointer.unfreeze_pointer(m_parent != 0 ? m_parent : MainFrame_getWindow());
1323   g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_zoom_focusOut);
1324 }
1325
1326 // makes sure the selected brush or camera is in view
1327 void XYWnd::PositionView(const Vector3& position)
1328 {
1329   int nDim1 = (m_viewType == YZ) ? 1 : 0;
1330   int nDim2 = (m_viewType == XY) ? 1 : 2;
1331
1332   m_vOrigin[nDim1] = position[nDim1];
1333   m_vOrigin[nDim2] = position[nDim2];
1334
1335   updateModelview();
1336
1337   XYWnd_Update(*this);
1338 }
1339
1340 void XYWnd::SetViewType(VIEWTYPE viewType)
1341 {
1342   m_viewType = viewType; 
1343   updateModelview();
1344
1345   if(m_parent != 0)
1346   {
1347     gtk_window_set_title(m_parent, ViewType_getTitle(m_viewType));
1348   }
1349 }
1350
1351
1352 inline WindowVector WindowVector_forInteger(int x, int y)
1353 {
1354   return WindowVector(static_cast<float>(x), static_cast<float>(y));
1355 }
1356
1357 void XYWnd::mouseDown(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers)
1358 {
1359   XY_MouseDown(static_cast<int>(position.x()), static_cast<int>(position.y()), buttons_for_button_and_modifiers(button, modifiers));
1360 }
1361 void XYWnd::XY_MouseDown (int x, int y, unsigned int buttons)
1362 {
1363   if(buttons == Move_buttons())
1364   {
1365     Move_Begin();
1366     EntityCreate_MouseDown(x, y);
1367   }
1368   else if(buttons == Zoom_buttons())
1369   {
1370     Zoom_Begin();
1371   }
1372   else if(ClipMode() && buttons == Clipper_buttons())
1373   {
1374     Clipper_OnLButtonDown(x, y);
1375   }
1376   else if(buttons == NewBrushDrag_buttons() && GlobalSelectionSystem().countSelected() == 0)
1377   {
1378     NewBrushDrag_Begin(x, y);
1379   }
1380   // control mbutton = move camera
1381   else if (buttons == MoveCamera_buttons())
1382   {
1383     XYWnd_PositionCamera(this, x, y, *g_pParentWnd->GetCamWnd());
1384   }
1385   // mbutton = angle camera
1386   else if(buttons == OrientCamera_buttons())
1387   {     
1388     XYWnd_OrientCamera(this, x, y, *g_pParentWnd->GetCamWnd());
1389   }
1390   else
1391   {
1392     m_window_observer->onMouseDown(WindowVector_forInteger(x, y), button_for_flags(buttons), modifiers_for_flags(buttons));
1393   }
1394 }
1395
1396 void XYWnd::XY_MouseUp(int x, int y, unsigned int buttons)
1397 {
1398   if(m_move_started)
1399   {
1400     Move_End();
1401     EntityCreate_MouseUp(x, y);
1402   }
1403   else if(m_zoom_started)
1404   {
1405     Zoom_End();
1406   }
1407   else if (ClipMode() && buttons == Clipper_buttons())
1408   {
1409     Clipper_OnLButtonUp(x, y);
1410   }
1411   else if (m_bNewBrushDrag)
1412   {
1413     m_bNewBrushDrag = false;
1414     NewBrushDrag_End(x, y);
1415   }
1416   else
1417   {
1418     m_window_observer->onMouseUp(WindowVector_forInteger(x, y), button_for_flags(buttons), modifiers_for_flags(buttons));
1419   }
1420 }
1421
1422 void XYWnd::XY_MouseMoved (int x, int y, unsigned int buttons)
1423 {
1424   // rbutton = drag xy origin
1425   if(m_move_started)
1426   {
1427   }
1428   // zoom in/out
1429   else if(m_zoom_started)
1430   {
1431   }
1432
1433   else if (ClipMode() && g_pMovingClip != 0)
1434   {
1435     Clipper_OnMouseMoved(x, y);
1436   }
1437   // lbutton without selection = drag new brush
1438   else if (m_bNewBrushDrag)
1439   {
1440     NewBrushDrag(x, y);
1441   }
1442
1443   // control mbutton = move camera
1444   else if (getButtonState() == MoveCamera_buttons())
1445   {
1446     XYWnd_PositionCamera(this, x, y, *g_pParentWnd->GetCamWnd());
1447   }
1448
1449   // mbutton = angle camera
1450   else if (getButtonState() == OrientCamera_buttons())
1451   {     
1452     XYWnd_OrientCamera(this, x, y, *g_pParentWnd->GetCamWnd());
1453   }
1454
1455   else
1456   {
1457     m_window_observer->onMouseMotion(WindowVector_forInteger(x, y), modifiers_for_flags(buttons));
1458
1459     m_mousePosition[0] = m_mousePosition[1] = m_mousePosition[2] = 0.0;
1460     XY_ToPoint(x, y , m_mousePosition);
1461     XY_SnapToGrid(m_mousePosition);
1462
1463     StringOutputStream status(64);
1464     status << "x:: " << FloatFormat(m_mousePosition[0], 6, 1)
1465       << "  y:: " << FloatFormat(m_mousePosition[1], 6, 1)
1466       << "  z:: " << FloatFormat(m_mousePosition[2], 6, 1);
1467     g_pParentWnd->SetStatusText(g_pParentWnd->m_position_status, status.c_str());
1468
1469     if (g_bCrossHairs)
1470     {
1471       XYWnd_Update(*this);
1472     }
1473
1474     Clipper_Crosshair_OnMouseMoved(x, y);
1475   }
1476 }
1477
1478 void XYWnd::EntityCreate_MouseDown(int x, int y)
1479 {
1480   m_entityCreate = true;
1481   m_entityCreate_x = x;
1482   m_entityCreate_y = y;
1483 }
1484
1485 void XYWnd::EntityCreate_MouseMove(int x, int y)
1486 {
1487   if(m_entityCreate && (m_entityCreate_x != x || m_entityCreate_y != y))
1488   {
1489     m_entityCreate = false;
1490   }
1491 }
1492
1493 void XYWnd::EntityCreate_MouseUp(int x, int y)
1494 {
1495   if(m_entityCreate)
1496   {
1497     m_entityCreate = false;
1498     OnContextMenu();
1499   }
1500 }
1501
1502 inline float screen_normalised(int pos, unsigned int size)
1503 {
1504   return ((2.0f * pos) / size) - 1.0f;
1505 }
1506
1507 inline float normalised_to_world(float normalised, float world_origin, float normalised2world_scale)
1508 {
1509   return world_origin + normalised * normalised2world_scale;
1510 }
1511
1512
1513 // TTimo: watch it, this doesn't init one of the 3 coords
1514 void XYWnd::XY_ToPoint (int x, int y, Vector3& point)
1515 {
1516   float normalised2world_scale_x = m_nWidth / 2 / m_fScale;
1517   float normalised2world_scale_y = m_nHeight / 2 / m_fScale;
1518   if (m_viewType == XY)
1519   {
1520     point[0] = normalised_to_world(screen_normalised(x, m_nWidth), m_vOrigin[0], normalised2world_scale_x);
1521     point[1] = normalised_to_world(-screen_normalised(y, m_nHeight), m_vOrigin[1], normalised2world_scale_y);
1522   }
1523   else if (m_viewType == YZ)
1524   {
1525     point[1] = normalised_to_world(screen_normalised(x, m_nWidth), m_vOrigin[1], normalised2world_scale_x);
1526     point[2] = normalised_to_world(-screen_normalised(y, m_nHeight), m_vOrigin[2], normalised2world_scale_y);
1527   }
1528   else
1529   {
1530     point[0] = normalised_to_world(screen_normalised(x, m_nWidth), m_vOrigin[0], normalised2world_scale_x);
1531     point[2] = normalised_to_world(-screen_normalised(y, m_nHeight), m_vOrigin[2], normalised2world_scale_y);
1532   }
1533 }
1534
1535 void XYWnd::XY_SnapToGrid(Vector3& point)
1536 {
1537   if (m_viewType == XY)
1538   {
1539     point[0] = float_snapped(point[0], GetGridSize());
1540     point[1] = float_snapped(point[1], GetGridSize());
1541   }
1542   else if (m_viewType == YZ)
1543   {
1544     point[1] = float_snapped(point[1], GetGridSize());
1545     point[2] = float_snapped(point[2], GetGridSize());
1546   }
1547   else
1548   {
1549     point[0] = float_snapped(point[0], GetGridSize());
1550     point[2] = float_snapped(point[2], GetGridSize());
1551   }
1552 }
1553
1554 /*
1555 ============================================================================
1556
1557 DRAWING
1558
1559 ============================================================================
1560 */
1561
1562 /*
1563 ==============
1564 XY_DrawGrid
1565 ==============
1566 */
1567
1568 double two_to_the_power(int power)
1569 {
1570   return pow(2.0f, power);
1571 }
1572
1573 void XYWnd::XY_DrawGrid()
1574 {
1575   float x, y, xb, xe, yb, ye;
1576   float         w, h;
1577   char  text[32];
1578   float step, minor_step, stepx, stepy;
1579   step = minor_step = stepx = stepy = GetGridSize();
1580   
1581   int minor_power = Grid_getPower();
1582   int mask;
1583
1584   while((minor_step * m_fScale) <= 4.0f) // make sure minor grid spacing is at least 4 pixels on the screen
1585   {
1586     ++minor_power;
1587     minor_step *= 2;
1588   }
1589   int power = minor_power;
1590   while((power % 3) != 0 || (step * m_fScale) <= 32.0f) // make sure major grid spacing is at least 32 pixels on the screen
1591   {
1592     ++power;
1593     step = float(two_to_the_power(power));
1594   }
1595   mask = (1 << (power - minor_power)) - 1;
1596   while ((stepx * m_fScale) <= 32.0f) // text step x must be at least 32
1597     stepx *= 2;
1598   while ((stepy * m_fScale) <= 32.0f) // text step y must be at least 32
1599     stepy *= 2;
1600   
1601
1602   glDisable(GL_TEXTURE_2D);
1603   glDisable(GL_TEXTURE_1D);
1604   glDisable(GL_DEPTH_TEST);
1605   glDisable(GL_BLEND);
1606   glLineWidth(1);
1607
1608   w = (m_nWidth / 2 / m_fScale);
1609   h = (m_nHeight / 2 / m_fScale);
1610
1611   int nDim1 = (m_viewType == YZ) ? 1 : 0;
1612   int nDim2 = (m_viewType == XY) ? 1 : 2;
1613
1614   xb = m_vOrigin[nDim1] - w;
1615   if (xb < region_mins[nDim1])
1616     xb = region_mins[nDim1];
1617   xb = step * floor (xb/step);
1618
1619   xe = m_vOrigin[nDim1] + w;
1620   if (xe > region_maxs[nDim1])
1621     xe = region_maxs[nDim1];
1622   xe = step * ceil (xe/step);
1623
1624   yb = m_vOrigin[nDim2] - h;
1625   if (yb < region_mins[nDim2])
1626     yb = region_mins[nDim2];
1627   yb = step * floor (yb/step);
1628
1629   ye = m_vOrigin[nDim2] + h;
1630   if (ye > region_maxs[nDim2])
1631     ye = region_maxs[nDim2];
1632   ye = step * ceil (ye/step);
1633
1634 #define COLORS_DIFFER(a,b) \
1635   ((a)[0] != (b)[0] || \
1636    (a)[1] != (b)[1] || \
1637    (a)[2] != (b)[2])
1638
1639   // djbob
1640   // draw minor blocks
1641   if (g_xywindow_globals_private.d_showgrid)
1642   {
1643     if (COLORS_DIFFER(g_xywindow_globals.color_gridminor, g_xywindow_globals.color_gridback))
1644     {
1645       glColor3fv(vector3_to_array(g_xywindow_globals.color_gridminor));
1646
1647       glBegin (GL_LINES);
1648       int i = 0;
1649       for (x = xb ; x < xe ; x += minor_step, ++i)
1650       {
1651         if((i & mask) != 0)
1652         {
1653           glVertex2f (x, yb);
1654           glVertex2f (x, ye);
1655         }
1656       }
1657       i = 0;
1658       for (y = yb ; y < ye ; y += minor_step, ++i)
1659       {
1660         if((i & mask) != 0)
1661         {
1662           glVertex2f (xb, y);
1663           glVertex2f (xe, y);
1664         }
1665       }
1666       glEnd();
1667     }
1668
1669     // draw major blocks
1670     if (COLORS_DIFFER(g_xywindow_globals.color_gridmajor, g_xywindow_globals.color_gridback))
1671     {
1672       glColor3fv(vector3_to_array(g_xywindow_globals.color_gridmajor));
1673
1674       glBegin (GL_LINES);
1675       for (x=xb ; x<=xe ; x+=step)
1676       {
1677         glVertex2f (x, yb);
1678         glVertex2f (x, ye);
1679       }
1680       for (y=yb ; y<=ye ; y+=step)
1681       {
1682         glVertex2f (xb, y);
1683         glVertex2f (xe, y);
1684       }
1685       glEnd();
1686     }
1687   }
1688
1689   // draw coordinate text if needed
1690   if ( g_xywindow_globals_private.show_coordinates)
1691   {
1692     glColor3fv(vector3_to_array(g_xywindow_globals.color_gridtext));
1693                 float offx = m_vOrigin[nDim2] + h - 6 / m_fScale, offy = m_vOrigin[nDim1] - w + 1 / m_fScale;
1694                 for (x = xb - fmod(xb, stepx); x <= xe ; x += stepx)
1695                 {
1696                   glRasterPos2f (x, offx);
1697                         sprintf (text, "%g", x);
1698                         GlobalOpenGL().drawString(text);
1699                 }
1700                 for (y = yb - fmod(yb, stepy); y <= ye ; y += stepy)
1701                 {
1702                   glRasterPos2f (offy, y);
1703                         sprintf (text, "%g", y);
1704                         GlobalOpenGL().drawString(text);
1705                 }
1706
1707     if (Active())
1708       glColor3fv(vector3_to_array(g_xywindow_globals.color_viewname));
1709
1710     // we do this part (the old way) only if show_axis is disabled
1711     if (!g_xywindow_globals_private.show_axis)
1712     {
1713       glRasterPos2f ( m_vOrigin[nDim1] - w + 35 / m_fScale, m_vOrigin[nDim2] + h - 20 / m_fScale );
1714
1715       GlobalOpenGL().drawString(ViewType_getTitle(m_viewType));
1716     }
1717   }
1718
1719   if ( g_xywindow_globals_private.show_axis)
1720   {
1721     const char g_AxisName[3] = { 'X', 'Y', 'Z' };
1722
1723     const Vector3& colourX = (m_viewType == YZ) ? g_xywindow_globals.AxisColorY : g_xywindow_globals.AxisColorX;
1724     const Vector3& colourY = (m_viewType == XY) ? g_xywindow_globals.AxisColorY : g_xywindow_globals.AxisColorZ;
1725
1726     // draw two lines with corresponding axis colors to highlight current view
1727     // horizontal line: nDim1 color
1728     glLineWidth(2);
1729     glBegin( GL_LINES );
1730     glColor3fv (vector3_to_array(colourX));
1731     glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale );
1732     glVertex2f( m_vOrigin[nDim1] - w + 65 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale );
1733     glVertex2f( 0, 0 );
1734     glVertex2f( 32 / m_fScale, 0 );
1735     glColor3fv (vector3_to_array(colourY));
1736     glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale );
1737     glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 20 / m_fScale );
1738     glVertex2f( 0, 0 );
1739     glVertex2f( 0, 32 / m_fScale );
1740     glEnd();
1741     glLineWidth(1);
1742     // now print axis symbols
1743     glColor3fv (vector3_to_array(colourX));
1744     glRasterPos2f ( m_vOrigin[nDim1] - w + 55 / m_fScale, m_vOrigin[nDim2] + h - 55 / m_fScale );
1745     GlobalOpenGL().drawChar(g_AxisName[nDim1]);
1746     glRasterPos2f (28 / m_fScale, -10 / m_fScale );
1747     GlobalOpenGL().drawChar(g_AxisName[nDim1]);
1748     glColor3fv (vector3_to_array(colourY));
1749     glRasterPos2f ( m_vOrigin[nDim1] - w + 25 / m_fScale, m_vOrigin[nDim2] + h - 30 / m_fScale );
1750     GlobalOpenGL().drawChar(g_AxisName[nDim2]);
1751     glRasterPos2f ( -10 / m_fScale, 28 / m_fScale );
1752     GlobalOpenGL().drawChar(g_AxisName[nDim2]);
1753
1754   }
1755
1756   // show current work zone?
1757   // the work zone is used to place dropped points and brushes
1758   if (g_xywindow_globals_private.d_show_work)
1759   {
1760     glColor3f( 1.0f, 0.0f, 0.0f );
1761     glBegin( GL_LINES );
1762     glVertex2f( xb, Select_getWorkZone().d_work_min[nDim2] );
1763     glVertex2f( xe, Select_getWorkZone().d_work_min[nDim2] );
1764     glVertex2f( xb, Select_getWorkZone().d_work_max[nDim2] );
1765     glVertex2f( xe, Select_getWorkZone().d_work_max[nDim2] );
1766     glVertex2f( Select_getWorkZone().d_work_min[nDim1], yb );
1767     glVertex2f( Select_getWorkZone().d_work_min[nDim1], ye );
1768     glVertex2f( Select_getWorkZone().d_work_max[nDim1], yb );
1769     glVertex2f( Select_getWorkZone().d_work_max[nDim1], ye );
1770     glEnd();
1771   }
1772 }
1773
1774 /*
1775 ==============
1776 XY_DrawBlockGrid
1777 ==============
1778 */
1779 void XYWnd::XY_DrawBlockGrid()
1780 {
1781   if(Map_FindWorldspawn(g_map) == 0)
1782   {
1783     return;
1784   }
1785   const char *value = Node_getEntity(*Map_GetWorldspawn(g_map))->getKeyValue("_blocksize" );
1786   if (strlen(value))
1787         sscanf( value, "%i", &g_xywindow_globals_private.blockSize );
1788
1789   if (!g_xywindow_globals_private.blockSize || g_xywindow_globals_private.blockSize > 65536 || g_xywindow_globals_private.blockSize < 1024)
1790           // don't use custom blocksize if it is less than the default, or greater than the maximum world coordinate
1791         g_xywindow_globals_private.blockSize = 1024;
1792
1793   float x, y, xb, xe, yb, ye;
1794   float         w, h;
1795   char  text[32];
1796
1797   glDisable(GL_TEXTURE_2D);
1798   glDisable(GL_TEXTURE_1D);
1799   glDisable(GL_DEPTH_TEST);
1800   glDisable(GL_BLEND);
1801
1802   w = (m_nWidth / 2 / m_fScale);
1803   h = (m_nHeight / 2 / m_fScale);
1804
1805   int nDim1 = (m_viewType == YZ) ? 1 : 0;
1806   int nDim2 = (m_viewType == XY) ? 1 : 2;
1807
1808   xb = m_vOrigin[nDim1] - w;
1809   if (xb < region_mins[nDim1])
1810     xb = region_mins[nDim1];
1811   xb = static_cast<float>(g_xywindow_globals_private.blockSize * floor (xb/g_xywindow_globals_private.blockSize));
1812
1813   xe = m_vOrigin[nDim1] + w;
1814   if (xe > region_maxs[nDim1])
1815     xe = region_maxs[nDim1];
1816   xe = static_cast<float>(g_xywindow_globals_private.blockSize * ceil (xe/g_xywindow_globals_private.blockSize));
1817
1818   yb = m_vOrigin[nDim2] - h;
1819   if (yb < region_mins[nDim2])
1820     yb = region_mins[nDim2];
1821   yb = static_cast<float>(g_xywindow_globals_private.blockSize * floor (yb/g_xywindow_globals_private.blockSize));
1822
1823   ye = m_vOrigin[nDim2] + h;
1824   if (ye > region_maxs[nDim2])
1825     ye = region_maxs[nDim2];
1826   ye = static_cast<float>(g_xywindow_globals_private.blockSize * ceil (ye/g_xywindow_globals_private.blockSize));
1827
1828   // draw major blocks
1829
1830   glColor3fv(vector3_to_array(g_xywindow_globals.color_gridblock));
1831   glLineWidth (2);
1832
1833   glBegin (GL_LINES);
1834         
1835   for (x=xb ; x<=xe ; x+=g_xywindow_globals_private.blockSize)
1836   {
1837     glVertex2f (x, yb);
1838     glVertex2f (x, ye);
1839   }
1840
1841   if (m_viewType == XY)
1842   {
1843         for (y=yb ; y<=ye ; y+=g_xywindow_globals_private.blockSize)
1844         {
1845           glVertex2f (xb, y);
1846           glVertex2f (xe, y);
1847         }
1848   }
1849         
1850   glEnd();
1851   glLineWidth (1);
1852
1853   // draw coordinate text if needed
1854
1855   if (m_viewType == XY && m_fScale > .1)
1856   {
1857         for (x=xb ; x<xe ; x+=g_xywindow_globals_private.blockSize)
1858                 for (y=yb ; y<ye ; y+=g_xywindow_globals_private.blockSize)
1859                 {
1860                   glRasterPos2f (x+(g_xywindow_globals_private.blockSize/2), y+(g_xywindow_globals_private.blockSize/2));
1861                         sprintf (text, "%i,%i",(int)floor(x/g_xywindow_globals_private.blockSize), (int)floor(y/g_xywindow_globals_private.blockSize) );
1862                         GlobalOpenGL().drawString(text);
1863                 }
1864   }
1865
1866   glColor4f(0, 0, 0, 0);
1867 }
1868
1869 void XYWnd::DrawCameraIcon(const Vector3& origin, const Vector3& angles)
1870 {
1871   float x, y, fov, box;
1872   double a;
1873
1874   fov = 48 / m_fScale;
1875   box = 16 / m_fScale;
1876
1877   if (m_viewType == XY)
1878   {
1879     x = origin[0];
1880     y = origin[1];
1881     a = degrees_to_radians(angles[CAMERA_YAW]);
1882   }
1883   else if (m_viewType == YZ)
1884   {
1885     x = origin[1];
1886     y = origin[2];
1887     a = degrees_to_radians(angles[CAMERA_PITCH]);
1888   }
1889   else
1890   {
1891     x = origin[0];
1892     y = origin[2];
1893     a = degrees_to_radians(angles[CAMERA_PITCH]);
1894   }
1895
1896   glColor3f (0.0, 0.0, 1.0);
1897   glBegin(GL_LINE_STRIP);
1898   glVertex3f (x-box,y,0);
1899   glVertex3f (x,y+(box/2),0);
1900   glVertex3f (x+box,y,0);
1901   glVertex3f (x,y-(box/2),0);
1902   glVertex3f (x-box,y,0);
1903   glVertex3f (x+box,y,0);
1904   glEnd();
1905         
1906   glBegin(GL_LINE_STRIP);
1907   glVertex3f (x + static_cast<float>(fov*cos(a+c_pi/4)), y + static_cast<float>(fov*sin(a+c_pi/4)), 0);
1908   glVertex3f (x, y, 0);
1909   glVertex3f (x + static_cast<float>(fov*cos(a-c_pi/4)), y + static_cast<float>(fov*sin(a-c_pi/4)), 0);
1910   glEnd();
1911
1912 }
1913
1914
1915 float Betwixt(float f1, float f2)
1916 {
1917   if (f1 > f2)
1918     return f2 + ((f1 - f2) / 2);
1919   else
1920     return f1 + ((f2 - f1) / 2);
1921 }
1922
1923
1924 // can be greatly simplified but per usual i am in a hurry 
1925 // which is not an excuse, just a fact
1926 void XYWnd::PaintSizeInfo(int nDim1, int nDim2, Vector3& vMinBounds, Vector3& vMaxBounds)
1927 {
1928   if(vector3_equal(vMinBounds, vMaxBounds))
1929   {
1930     return;
1931   }
1932   const char* g_pDimStrings[] = {"x:", "y:", "z:"};
1933   typedef const char* OrgStrings[2];
1934   const OrgStrings g_pOrgStrings[] = { { "x:", "y:", }, { "x:", "z:", }, { "y:", "z:", } };
1935
1936   Vector3 vSize(vector3_subtracted(vMaxBounds, vMinBounds));
1937
1938   glColor3f(g_xywindow_globals.color_selbrushes[0] * .65f, 
1939              g_xywindow_globals.color_selbrushes[1] * .65f,
1940              g_xywindow_globals.color_selbrushes[2] * .65f);
1941
1942   StringOutputStream dimensions(16);
1943
1944   if (m_viewType == XY)
1945   {
1946     glBegin (GL_LINES);
1947
1948     glVertex3f(vMinBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale, 0.0f);
1949     glVertex3f(vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f);
1950
1951     glVertex3f(vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale, 0.0f);
1952     glVertex3f(vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale, 0.0f);
1953
1954     glVertex3f(vMaxBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale, 0.0f);
1955     glVertex3f(vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f);
1956   
1957
1958     glVertex3f(vMaxBounds[nDim1] + 6.0f  / m_fScale, vMinBounds[nDim2], 0.0f);
1959     glVertex3f(vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2], 0.0f);
1960
1961     glVertex3f(vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2], 0.0f);
1962     glVertex3f(vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2], 0.0f);
1963   
1964     glVertex3f(vMaxBounds[nDim1] + 6.0f  / m_fScale, vMaxBounds[nDim2], 0.0f);
1965     glVertex3f(vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2], 0.0f);
1966
1967     glEnd();
1968
1969     glRasterPos3f (Betwixt(vMinBounds[nDim1], vMaxBounds[nDim1]),  vMinBounds[nDim2] - 20.0f  / m_fScale, 0.0f);
1970     dimensions << g_pDimStrings[nDim1] << vSize[nDim1];
1971     GlobalOpenGL().drawString(dimensions.c_str());
1972     dimensions.clear();
1973     
1974     glRasterPos3f (vMaxBounds[nDim1] + 16.0f  / m_fScale, Betwixt(vMinBounds[nDim2], vMaxBounds[nDim2]), 0.0f);
1975     dimensions << g_pDimStrings[nDim2] << vSize[nDim2];
1976     GlobalOpenGL().drawString(dimensions.c_str());
1977     dimensions.clear();
1978
1979     glRasterPos3f (vMinBounds[nDim1] + 4, vMaxBounds[nDim2] + 8 / m_fScale, 0.0f);
1980     dimensions << "(" << g_pOrgStrings[0][0] << vMinBounds[nDim1] << "  " << g_pOrgStrings[0][1] << vMaxBounds[nDim2] << ")";
1981     GlobalOpenGL().drawString(dimensions.c_str());
1982   }
1983   else if (m_viewType == XZ)
1984   {
1985     glBegin (GL_LINES);
1986
1987     glVertex3f(vMinBounds[nDim1], 0, vMinBounds[nDim2] - 6.0f  / m_fScale);
1988     glVertex3f(vMinBounds[nDim1], 0, vMinBounds[nDim2] - 10.0f / m_fScale);
1989
1990     glVertex3f(vMinBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f  / m_fScale);
1991     glVertex3f(vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f  / m_fScale);
1992
1993     glVertex3f(vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 6.0f  / m_fScale);
1994     glVertex3f(vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f / m_fScale);
1995   
1996
1997     glVertex3f(vMaxBounds[nDim1] + 6.0f  / m_fScale, 0,vMinBounds[nDim2]);
1998     glVertex3f(vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMinBounds[nDim2]);
1999
2000     glVertex3f(vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMinBounds[nDim2]);
2001     glVertex3f(vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMaxBounds[nDim2]);
2002   
2003     glVertex3f(vMaxBounds[nDim1] + 6.0f  / m_fScale, 0,vMaxBounds[nDim2]);
2004     glVertex3f(vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMaxBounds[nDim2]);
2005
2006     glEnd();
2007
2008     glRasterPos3f (Betwixt(vMinBounds[nDim1], vMaxBounds[nDim1]), 0, vMinBounds[nDim2] - 20.0f  / m_fScale);
2009     dimensions << g_pDimStrings[nDim1] << vSize[nDim1];
2010     GlobalOpenGL().drawString(dimensions.c_str());
2011     dimensions.clear();
2012     
2013     glRasterPos3f (vMaxBounds[nDim1] + 16.0f  / m_fScale, 0, Betwixt(vMinBounds[nDim2], vMaxBounds[nDim2]));
2014     dimensions << g_pDimStrings[nDim2] << vSize[nDim2];
2015     GlobalOpenGL().drawString(dimensions.c_str());
2016     dimensions.clear();
2017
2018     glRasterPos3f (vMinBounds[nDim1] + 4, 0, vMaxBounds[nDim2] + 8 / m_fScale);
2019     dimensions << "(" << g_pOrgStrings[1][0] << vMinBounds[nDim1] << "  " << g_pOrgStrings[1][1] << vMaxBounds[nDim2] << ")";
2020     GlobalOpenGL().drawString(dimensions.c_str());
2021   }
2022   else
2023   {
2024     glBegin (GL_LINES);
2025
2026     glVertex3f(0, vMinBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale);
2027     glVertex3f(0, vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale);
2028
2029     glVertex3f(0, vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale);
2030     glVertex3f(0, vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale);
2031
2032     glVertex3f(0, vMaxBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale);
2033     glVertex3f(0, vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale);
2034   
2035
2036     glVertex3f(0, vMaxBounds[nDim1] + 6.0f  / m_fScale, vMinBounds[nDim2]);
2037     glVertex3f(0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2]);
2038
2039     glVertex3f(0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2]);
2040     glVertex3f(0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2]);
2041   
2042     glVertex3f(0, vMaxBounds[nDim1] + 6.0f  / m_fScale, vMaxBounds[nDim2]);
2043     glVertex3f(0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2]);
2044
2045     glEnd();
2046
2047     glRasterPos3f (0, Betwixt(vMinBounds[nDim1], vMaxBounds[nDim1]),  vMinBounds[nDim2] - 20.0f  / m_fScale);
2048     dimensions << g_pDimStrings[nDim1] << vSize[nDim1];
2049     GlobalOpenGL().drawString(dimensions.c_str());
2050     dimensions.clear();
2051     
2052     glRasterPos3f (0, vMaxBounds[nDim1] + 16.0f  / m_fScale, Betwixt(vMinBounds[nDim2], vMaxBounds[nDim2]));
2053     dimensions << g_pDimStrings[nDim2] << vSize[nDim2];
2054     GlobalOpenGL().drawString(dimensions.c_str());
2055     dimensions.clear();
2056
2057     glRasterPos3f (0, vMinBounds[nDim1] + 4.0f, vMaxBounds[nDim2] + 8 / m_fScale);
2058     dimensions << "(" << g_pOrgStrings[2][0] << vMinBounds[nDim1] << "  " << g_pOrgStrings[2][1] << vMaxBounds[nDim2] << ")";
2059     GlobalOpenGL().drawString(dimensions.c_str());
2060   }
2061 }
2062
2063 class XYRenderer: public Renderer
2064 {
2065   struct state_type
2066   {
2067     state_type() :
2068     m_highlight(0),
2069     m_state(0)
2070     {
2071     }  
2072     unsigned int m_highlight;
2073     Shader* m_state;
2074   };
2075 public:
2076   XYRenderer(RenderStateFlags globalstate, Shader* selected) :
2077     m_globalstate(globalstate),
2078     m_state_selected(selected)
2079   {
2080     ASSERT_NOTNULL(selected);
2081     m_state_stack.push_back(state_type());
2082   }
2083
2084   void SetState(Shader* state, EStyle style)
2085   {
2086     ASSERT_NOTNULL(state);
2087     if(style == eWireframeOnly)
2088       m_state_stack.back().m_state = state;
2089   }
2090   const EStyle getStyle() const
2091   {
2092     return eWireframeOnly;
2093   }
2094   void PushState()
2095   {
2096     m_state_stack.push_back(m_state_stack.back());
2097   }
2098   void PopState()
2099   {
2100     ASSERT_MESSAGE(!m_state_stack.empty(), "popping empty stack");
2101     m_state_stack.pop_back();
2102   }
2103   void Highlight(EHighlightMode mode, bool bEnable = true)
2104   {
2105     (bEnable)
2106       ? m_state_stack.back().m_highlight |= mode
2107       : m_state_stack.back().m_highlight &= ~mode;
2108   }
2109   void addRenderable(const OpenGLRenderable& renderable, const Matrix4& localToWorld)
2110   {
2111     if(m_state_stack.back().m_highlight & ePrimitive)
2112     {
2113       m_state_selected->addRenderable(renderable, localToWorld);
2114     }
2115     else
2116     {
2117       m_state_stack.back().m_state->addRenderable(renderable, localToWorld);
2118     }
2119   }
2120
2121   void render(const Matrix4& modelview, const Matrix4& projection)
2122   {
2123     GlobalShaderCache().render(m_globalstate, modelview, projection);
2124   }
2125 private:
2126   std::vector<state_type> m_state_stack;
2127   RenderStateFlags m_globalstate;
2128   Shader* m_state_selected;
2129 };
2130
2131 void XYWnd::updateProjection()
2132 {
2133   m_projection[0] = 1.0f / static_cast<float>(m_nWidth / 2);
2134   m_projection[5] = 1.0f / static_cast<float>(m_nHeight / 2);
2135   m_projection[10] = 1.0f / (g_MaxWorldCoord * m_fScale);
2136
2137   m_projection[12] = 0.0f;
2138   m_projection[13] = 0.0f;
2139   m_projection[14] = -1.0f;
2140
2141   m_projection[1] =
2142   m_projection[2] =
2143   m_projection[3] =
2144
2145   m_projection[4] =
2146   m_projection[6] =
2147   m_projection[7] =
2148
2149   m_projection[8] =
2150   m_projection[9] =
2151   m_projection[11] = 0.0f;
2152
2153   m_projection[15] = 1.0f;
2154
2155   m_view.Construct(m_projection, m_modelview, m_nWidth, m_nHeight);
2156 }
2157
2158 // note: modelview matrix must have a uniform scale, otherwise strange things happen when rendering the rotation manipulator.
2159 void XYWnd::updateModelview()
2160 {
2161   int nDim1 = (m_viewType == YZ) ? 1 : 0;
2162   int nDim2 = (m_viewType == XY) ? 1 : 2;
2163
2164   // translation
2165   m_modelview[12] = -m_vOrigin[nDim1] * m_fScale;
2166   m_modelview[13] = -m_vOrigin[nDim2] * m_fScale;
2167   m_modelview[14] = g_MaxWorldCoord * m_fScale;
2168
2169   // axis base
2170   switch(m_viewType)
2171   {
2172   case XY:
2173     m_modelview[0]  =  m_fScale;
2174     m_modelview[1]  =  0;
2175     m_modelview[2]  =  0;
2176
2177     m_modelview[4]  =  0;
2178     m_modelview[5]  =  m_fScale;
2179     m_modelview[6]  =  0;
2180
2181     m_modelview[8]  =  0;
2182     m_modelview[9]  =  0;
2183     m_modelview[10] = -m_fScale;
2184     break;
2185   case XZ:
2186     m_modelview[0]  =  m_fScale;
2187     m_modelview[1]  =  0;
2188     m_modelview[2]  =  0;
2189
2190     m_modelview[4]  =  0;
2191     m_modelview[5]  =  0;
2192     m_modelview[6]  =  m_fScale;
2193
2194     m_modelview[8]  =  0;
2195     m_modelview[9]  =  m_fScale;
2196     m_modelview[10] =  0;
2197     break;
2198   case YZ:
2199     m_modelview[0]  =  0;
2200     m_modelview[1]  =  0;
2201     m_modelview[2]  = -m_fScale;
2202
2203     m_modelview[4]  =  m_fScale;
2204     m_modelview[5]  =  0;
2205     m_modelview[6]  =  0;
2206
2207     m_modelview[8]  =  0;
2208     m_modelview[9]  =  m_fScale;
2209     m_modelview[10] =  0;
2210     break;
2211   }
2212
2213   m_modelview[3] = m_modelview[7] = m_modelview[11] = 0;
2214   m_modelview[15] = 1;
2215
2216   m_view.Construct(m_projection, m_modelview, m_nWidth, m_nHeight);
2217 }
2218
2219 /*
2220 ==============
2221 XY_Draw
2222 ==============
2223 */
2224
2225 //#define DBG_SCENEDUMP
2226
2227 void XYWnd::XY_Draw()
2228 {
2229   //
2230   // clear
2231   //
2232   glViewport(0, 0, m_nWidth, m_nHeight);
2233   glClearColor (g_xywindow_globals.color_gridback[0],
2234                  g_xywindow_globals.color_gridback[1],
2235                  g_xywindow_globals.color_gridback[2],0);
2236
2237   glClear(GL_COLOR_BUFFER_BIT);
2238
2239   //
2240   // set up viewpoint
2241   //
2242
2243   glMatrixMode(GL_PROJECTION);
2244   glLoadMatrixf(reinterpret_cast<const float*>(&m_projection));
2245
2246   glMatrixMode(GL_MODELVIEW);
2247   glLoadIdentity();
2248   glScalef(m_fScale, m_fScale, 1);
2249   int nDim1 = (m_viewType == YZ) ? 1 : 0;
2250   int nDim2 = (m_viewType == XY) ? 1 : 2;
2251   glTranslatef(-m_vOrigin[nDim1], -m_vOrigin[nDim2], 0);
2252
2253   glDisable (GL_LINE_STIPPLE);
2254   glLineWidth(1);
2255   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
2256   glDisableClientState(GL_NORMAL_ARRAY);
2257   glDisableClientState(GL_COLOR_ARRAY);
2258   glDisable(GL_TEXTURE_2D);
2259   glDisable(GL_LIGHTING);
2260   glDisable(GL_COLOR_MATERIAL);
2261   glDisable(GL_DEPTH_TEST);
2262
2263   XY_DrawGrid();
2264   if ( g_xywindow_globals_private.show_blocks)
2265     XY_DrawBlockGrid();
2266
2267   glLoadMatrixf(reinterpret_cast<const float*>(&m_modelview));
2268
2269   unsigned int globalstate = RENDER_COLOURARRAY | RENDER_COLOURWRITE | RENDER_POLYGONSMOOTH | RENDER_LINESMOOTH;
2270   if(!g_xywindow_globals.m_bNoStipple)
2271   {
2272     globalstate |= RENDER_LINESTIPPLE;
2273   }
2274
2275   {
2276     XYRenderer renderer(globalstate, m_state_selected);
2277
2278     Scene_Render(renderer, m_view);
2279
2280     GlobalOpenGL_debugAssertNoErrors();
2281     renderer.render(m_modelview, m_projection);
2282     GlobalOpenGL_debugAssertNoErrors();
2283   }
2284
2285   glDepthMask(GL_FALSE);
2286
2287   GlobalOpenGL_debugAssertNoErrors();
2288
2289   glLoadMatrixf(reinterpret_cast<const float*>(&m_modelview));
2290   
2291   GlobalOpenGL_debugAssertNoErrors();
2292   glDisable(GL_LINE_STIPPLE);
2293   GlobalOpenGL_debugAssertNoErrors();
2294   glLineWidth(1);
2295   GlobalOpenGL_debugAssertNoErrors();
2296   if(GlobalOpenGL().GL_1_3())
2297   {
2298     glActiveTexture(GL_TEXTURE0);
2299     glClientActiveTexture(GL_TEXTURE0);
2300   }
2301   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
2302   GlobalOpenGL_debugAssertNoErrors();
2303   glDisableClientState(GL_NORMAL_ARRAY);
2304   GlobalOpenGL_debugAssertNoErrors();
2305   glDisableClientState(GL_COLOR_ARRAY);
2306   GlobalOpenGL_debugAssertNoErrors();
2307   glDisable(GL_TEXTURE_2D);
2308   GlobalOpenGL_debugAssertNoErrors();
2309   glDisable(GL_LIGHTING);
2310   GlobalOpenGL_debugAssertNoErrors();
2311   glDisable(GL_COLOR_MATERIAL);
2312   GlobalOpenGL_debugAssertNoErrors();
2313
2314   GlobalOpenGL_debugAssertNoErrors();
2315
2316
2317   // size info
2318   if(g_xywindow_globals_private.m_bSizePaint && GlobalSelectionSystem().countSelected() != 0)
2319   {
2320     Vector3 min, max;
2321     Select_GetBounds(min, max);
2322     PaintSizeInfo(nDim1, nDim2, min, max);
2323   }
2324
2325   if (g_bCrossHairs)
2326   {
2327     glColor4f(0.2f, 0.9f, 0.2f, 0.8f);
2328     glBegin (GL_LINES);
2329     if (m_viewType == XY)
2330     {
2331       glVertex2f(2.0f * g_MinWorldCoord, m_mousePosition[1]);
2332       glVertex2f(2.0f * g_MaxWorldCoord, m_mousePosition[1]);
2333       glVertex2f(m_mousePosition[0], 2.0f * g_MinWorldCoord);
2334       glVertex2f(m_mousePosition[0], 2.0f * g_MaxWorldCoord);
2335     }
2336     else if (m_viewType == YZ)
2337     {
2338       glVertex3f(m_mousePosition[0], 2.0f * g_MinWorldCoord, m_mousePosition[2]);
2339       glVertex3f(m_mousePosition[0], 2.0f * g_MaxWorldCoord, m_mousePosition[2]);
2340       glVertex3f(m_mousePosition[0], m_mousePosition[1], 2.0f * g_MinWorldCoord);
2341       glVertex3f(m_mousePosition[0], m_mousePosition[1], 2.0f * g_MaxWorldCoord);
2342     }
2343     else
2344     {
2345       glVertex3f (2.0f * g_MinWorldCoord, m_mousePosition[1], m_mousePosition[2]);
2346       glVertex3f (2.0f * g_MaxWorldCoord, m_mousePosition[1], m_mousePosition[2]);
2347       glVertex3f(m_mousePosition[0], m_mousePosition[1], 2.0f * g_MinWorldCoord);
2348       glVertex3f(m_mousePosition[0], m_mousePosition[1], 2.0f * g_MaxWorldCoord);
2349     }
2350     glEnd();
2351   }
2352
2353   if (ClipMode())
2354   {
2355     GlobalClipPoints_Draw(m_fScale);
2356   }
2357
2358   GlobalOpenGL_debugAssertNoErrors();
2359     
2360     // reset modelview
2361   glLoadIdentity();
2362   glScalef(m_fScale, m_fScale, 1);
2363   glTranslatef(-m_vOrigin[nDim1], -m_vOrigin[nDim2], 0);
2364
2365   DrawCameraIcon (Camera_getOrigin(*g_pParentWnd->GetCamWnd()), Camera_getAngles(*g_pParentWnd->GetCamWnd()));
2366
2367   Feedback_draw2D( m_viewType );
2368
2369   if (g_xywindow_globals_private.show_outline)
2370   {
2371     if (Active())
2372     {
2373       glMatrixMode (GL_PROJECTION);
2374       glLoadIdentity();
2375       glOrtho (0, m_nWidth, 0, m_nHeight, 0, 1);
2376
2377       glMatrixMode (GL_MODELVIEW);
2378       glLoadIdentity();
2379
2380       // four view mode doesn't colorize
2381       if (g_pParentWnd->CurrentStyle() == MainFrame::eSplit)
2382         glColor3fv(vector3_to_array(g_xywindow_globals.color_viewname));
2383       else
2384       {
2385         switch(m_viewType)
2386         {
2387         case YZ:
2388           glColor3fv(vector3_to_array(g_xywindow_globals.AxisColorX));
2389           break;
2390         case XZ:
2391           glColor3fv(vector3_to_array(g_xywindow_globals.AxisColorY));
2392           break;
2393         case XY:
2394           glColor3fv(vector3_to_array(g_xywindow_globals.AxisColorZ));
2395           break;
2396         }
2397       }
2398       glBegin (GL_LINE_LOOP);
2399       glVertex2i (0, 0);
2400       glVertex2i (m_nWidth-1, 0);
2401       glVertex2i (m_nWidth-1, m_nHeight-1);
2402       glVertex2i (0, m_nHeight-1);
2403       glEnd();
2404     }
2405   }
2406
2407   GlobalOpenGL_debugAssertNoErrors();
2408
2409   glFinish();
2410 }
2411
2412 void XYWnd_MouseToPoint(XYWnd* xywnd, int x, int y, Vector3& point)
2413 {
2414   xywnd->XY_ToPoint(x, y, point);
2415   xywnd->XY_SnapToGrid(point);
2416
2417   int nDim = (xywnd->GetViewType() == XY) ? 2 : (xywnd->GetViewType() == YZ) ? 0 : 1;
2418   float fWorkMid = float_mid(Select_getWorkZone().d_work_min[nDim], Select_getWorkZone().d_work_max[nDim]);
2419   point[nDim] = float_snapped(fWorkMid, GetGridSize());
2420 }
2421
2422 void XYWnd::OnEntityCreate (const char* item)
2423 {
2424   StringOutputStream command;
2425   command << "entityCreate -class " << item;
2426   UndoableCommand undo(command.c_str());
2427   Vector3 point;
2428   XYWnd_MouseToPoint(this, m_entityCreate_x, m_entityCreate_y, point);
2429   Entity_createFromSelection(item, point);
2430 }
2431
2432
2433
2434 void GetFocusPosition(Vector3& position)
2435 {
2436   if(GlobalSelectionSystem().countSelected() != 0)
2437   {
2438     Select_GetMid(position);
2439   }
2440   else
2441   {
2442     position = Camera_getOrigin(*g_pParentWnd->GetCamWnd());
2443   }
2444 }
2445
2446 void XYWnd_Focus(XYWnd* xywnd)
2447 {
2448   Vector3 position;
2449   GetFocusPosition(position);
2450   xywnd->PositionView(position);
2451 }
2452
2453 void XY_Split_Focus()
2454 {
2455   Vector3 position;
2456   GetFocusPosition(position);
2457   g_pParentWnd->GetXYWnd()->PositionView(position);
2458   g_pParentWnd->GetXZWnd()->PositionView(position);
2459   g_pParentWnd->GetYZWnd()->PositionView(position);
2460 }
2461
2462 void XY_Focus()
2463 {
2464   XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2465   XYWnd_Focus(xywnd);
2466 }
2467
2468 void XY_Top()
2469 {
2470   XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2471   xywnd->SetViewType(XY);
2472   XYWnd_Focus(xywnd);
2473 }
2474
2475 void XY_Side()
2476 {
2477   XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2478   xywnd->SetViewType(XZ);
2479   XYWnd_Focus(xywnd);
2480 }
2481
2482 void XY_Front()
2483 {
2484   g_pParentWnd->GetXYWnd()->SetViewType(YZ);
2485   XYWnd_Focus(g_pParentWnd->GetXYWnd());
2486 }
2487
2488 void XY_Next()
2489 {
2490   XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2491   if (xywnd->GetViewType() == XY)
2492     xywnd->SetViewType(XZ);
2493   else if (xywnd->GetViewType() ==  XZ)
2494     xywnd->SetViewType(YZ);
2495   else
2496     xywnd->SetViewType(XY);
2497   XYWnd_Focus(xywnd);
2498 }
2499
2500 void XY_Zoom100()
2501 {
2502   if (g_pParentWnd->GetXYWnd())
2503     g_pParentWnd->GetXYWnd()->SetScale(1);
2504   if (g_pParentWnd->GetXZWnd())
2505     g_pParentWnd->GetXZWnd()->SetScale(1);
2506   if (g_pParentWnd->GetYZWnd())
2507     g_pParentWnd->GetYZWnd()->SetScale(1);
2508 }
2509
2510 void XY_ZoomIn()
2511 {
2512   XYWnd_ZoomIn(g_pParentWnd->ActiveXY());
2513 }
2514
2515 // NOTE: the zoom out factor is 4/5, we could think about customizing it
2516 //  we don't go below a zoom factor corresponding to 10% of the max world size
2517 //  (this has to be computed against the window size)
2518 void XY_ZoomOut()
2519 {
2520   XYWnd_ZoomOut(g_pParentWnd->ActiveXY());
2521 }
2522
2523
2524
2525 void ToggleShowCrosshair()
2526 {
2527   g_bCrossHairs ^= 1; 
2528   XY_UpdateAllWindows();
2529 }
2530
2531 void ToggleShowSizeInfo()
2532 {
2533   g_xywindow_globals_private.m_bSizePaint = !g_xywindow_globals_private.m_bSizePaint;
2534   XY_UpdateAllWindows();
2535 }
2536
2537 void ToggleShowGrid()
2538 {
2539   g_xywindow_globals_private.d_showgrid = !g_xywindow_globals_private.d_showgrid;
2540   XY_UpdateAllWindows();
2541 }
2542
2543 ToggleShown g_xy_top_shown(true);
2544
2545 void XY_Top_Shown_Construct(GtkWindow* parent)
2546 {
2547   g_xy_top_shown.connect(GTK_WIDGET(parent));
2548 }
2549
2550 ToggleShown g_yz_side_shown(false);
2551
2552 void YZ_Side_Shown_Construct(GtkWindow* parent)
2553 {
2554   g_yz_side_shown.connect(GTK_WIDGET(parent));
2555 }
2556
2557 ToggleShown g_xz_front_shown(false);
2558
2559 void XZ_Front_Shown_Construct(GtkWindow* parent)
2560 {
2561   g_xz_front_shown.connect(GTK_WIDGET(parent));
2562 }
2563
2564
2565 class EntityClassMenu : public ModuleObserver
2566 {
2567   std::size_t m_unrealised;
2568 public:
2569   EntityClassMenu() : m_unrealised(1)
2570   {
2571   }
2572   void realise()
2573   {
2574     if(--m_unrealised == 0)
2575     {
2576     }
2577   }
2578   void unrealise()
2579   {
2580     if(++m_unrealised == 1)
2581     {
2582       if(XYWnd::m_mnuDrop != 0)
2583       {
2584         gtk_widget_destroy(GTK_WIDGET(XYWnd::m_mnuDrop));
2585         XYWnd::m_mnuDrop = 0;
2586       }
2587     }
2588   }
2589 };
2590
2591 EntityClassMenu g_EntityClassMenu;
2592
2593
2594
2595
2596 void ShowNamesToggle()
2597 {
2598   GlobalEntityCreator().setShowNames(!GlobalEntityCreator().getShowNames());
2599   XY_UpdateAllWindows();
2600 }
2601 typedef FreeCaller<ShowNamesToggle> ShowNamesToggleCaller;
2602 void ShowNamesExport(const BoolImportCallback& importer)
2603 {
2604   importer(GlobalEntityCreator().getShowNames());
2605 }
2606 typedef FreeCaller1<const BoolImportCallback&, ShowNamesExport> ShowNamesExportCaller;
2607
2608 void ShowAnglesToggle()
2609 {
2610   GlobalEntityCreator().setShowAngles(!GlobalEntityCreator().getShowAngles());
2611   XY_UpdateAllWindows();
2612 }
2613 typedef FreeCaller<ShowAnglesToggle> ShowAnglesToggleCaller;
2614 void ShowAnglesExport(const BoolImportCallback& importer)
2615 {
2616   importer(GlobalEntityCreator().getShowAngles());
2617 }
2618 typedef FreeCaller1<const BoolImportCallback&, ShowAnglesExport> ShowAnglesExportCaller;
2619
2620 void ShowBlocksToggle()
2621 {
2622   g_xywindow_globals_private.show_blocks ^= 1;
2623   XY_UpdateAllWindows();
2624 }
2625 typedef FreeCaller<ShowBlocksToggle> ShowBlocksToggleCaller;
2626 void ShowBlocksExport(const BoolImportCallback& importer)
2627 {
2628   importer(g_xywindow_globals_private.show_blocks);
2629 }
2630 typedef FreeCaller1<const BoolImportCallback&, ShowBlocksExport> ShowBlocksExportCaller;
2631
2632 void ShowCoordinatesToggle()
2633 {
2634   g_xywindow_globals_private.show_coordinates ^= 1;
2635   XY_UpdateAllWindows();
2636 }
2637 typedef FreeCaller<ShowCoordinatesToggle> ShowCoordinatesToggleCaller;
2638 void ShowCoordinatesExport(const BoolImportCallback& importer)
2639 {
2640   importer(g_xywindow_globals_private.show_coordinates);
2641 }
2642 typedef FreeCaller1<const BoolImportCallback&, ShowCoordinatesExport> ShowCoordinatesExportCaller;
2643
2644 void ShowOutlineToggle()
2645 {
2646   g_xywindow_globals_private.show_outline ^= 1;
2647   XY_UpdateAllWindows();
2648 }
2649 typedef FreeCaller<ShowOutlineToggle> ShowOutlineToggleCaller;
2650 void ShowOutlineExport(const BoolImportCallback& importer)
2651 {
2652   importer(g_xywindow_globals_private.show_outline);
2653 }
2654 typedef FreeCaller1<const BoolImportCallback&, ShowOutlineExport> ShowOutlineExportCaller;
2655
2656 void ShowAxesToggle()
2657 {
2658   g_xywindow_globals_private.show_axis ^= 1;
2659   XY_UpdateAllWindows();
2660 }
2661 typedef FreeCaller<ShowAxesToggle> ShowAxesToggleCaller;
2662 void ShowAxesExport(const BoolImportCallback& importer)
2663 {
2664   importer(g_xywindow_globals_private.show_axis);
2665 }
2666 typedef FreeCaller1<const BoolImportCallback&, ShowAxesExport> ShowAxesExportCaller;
2667
2668 void ShowWorkzoneToggle()
2669 {
2670   g_xywindow_globals_private.d_show_work ^= 1;
2671   XY_UpdateAllWindows();
2672 }
2673 typedef FreeCaller<ShowWorkzoneToggle> ShowWorkzoneToggleCaller;
2674 void ShowWorkzoneExport(const BoolImportCallback& importer)
2675 {
2676   importer(g_xywindow_globals_private.d_show_work);
2677 }
2678 typedef FreeCaller1<const BoolImportCallback&, ShowWorkzoneExport> ShowWorkzoneExportCaller;
2679
2680 ShowNamesExportCaller g_show_names_caller;
2681 BoolExportCallback g_show_names_callback(g_show_names_caller);
2682 ToggleItem g_show_names(g_show_names_callback);
2683
2684 ShowAnglesExportCaller g_show_angles_caller;
2685 BoolExportCallback g_show_angles_callback(g_show_angles_caller);
2686 ToggleItem g_show_angles(g_show_angles_callback);
2687
2688 ShowBlocksExportCaller g_show_blocks_caller;
2689 BoolExportCallback g_show_blocks_callback(g_show_blocks_caller);
2690 ToggleItem g_show_blocks(g_show_blocks_callback);
2691
2692 ShowCoordinatesExportCaller g_show_coordinates_caller;
2693 BoolExportCallback g_show_coordinates_callback(g_show_coordinates_caller);
2694 ToggleItem g_show_coordinates(g_show_coordinates_callback);
2695
2696 ShowOutlineExportCaller g_show_outline_caller;
2697 BoolExportCallback g_show_outline_callback(g_show_outline_caller);
2698 ToggleItem g_show_outline(g_show_outline_callback);
2699
2700 ShowAxesExportCaller g_show_axes_caller;
2701 BoolExportCallback g_show_axes_callback(g_show_axes_caller);
2702 ToggleItem g_show_axes(g_show_axes_callback);
2703
2704 ShowWorkzoneExportCaller g_show_workzone_caller;
2705 BoolExportCallback g_show_workzone_callback(g_show_workzone_caller);
2706 ToggleItem g_show_workzone(g_show_workzone_callback);
2707
2708 void XYShow_registerCommands()
2709 {
2710   GlobalToggles_insert("ShowAngles", ShowAnglesToggleCaller(), ToggleItem::AddCallbackCaller(g_show_angles));
2711   GlobalToggles_insert("ShowNames", ShowNamesToggleCaller(), ToggleItem::AddCallbackCaller(g_show_names));
2712   GlobalToggles_insert("ShowBlocks", ShowBlocksToggleCaller(), ToggleItem::AddCallbackCaller(g_show_blocks));
2713   GlobalToggles_insert("ShowCoordinates", ShowCoordinatesToggleCaller(), ToggleItem::AddCallbackCaller(g_show_coordinates));
2714   GlobalToggles_insert("ShowWindowOutline", ShowOutlineToggleCaller(), ToggleItem::AddCallbackCaller(g_show_outline));
2715   GlobalToggles_insert("ShowAxes", ShowAxesToggleCaller(), ToggleItem::AddCallbackCaller(g_show_axes));
2716   GlobalToggles_insert("ShowWorkzone", ShowWorkzoneToggleCaller(), ToggleItem::AddCallbackCaller(g_show_workzone));
2717 }
2718
2719 void XYWnd_registerShortcuts()
2720 {
2721   command_connect_accelerator("ToggleCrosshairs");
2722   command_connect_accelerator("ToggleSizePaint");
2723 }
2724
2725
2726
2727 void Orthographic_constructPreferences(PreferencesPage& page)
2728 {
2729   page.appendCheckBox("", "Solid selection boxes", g_xywindow_globals.m_bNoStipple);
2730   page.appendCheckBox("", "Display size info", g_xywindow_globals_private.m_bSizePaint);
2731   page.appendCheckBox("", "Chase mouse during drags", g_xywindow_globals_private.m_bChaseMouse);
2732   page.appendCheckBox("", "Update views on camera move", g_xywindow_globals_private.m_bCamXYUpdate);
2733 }
2734 void Orthographic_constructPage(PreferenceGroup& group)
2735 {
2736   PreferencesPage page(group.createPage("Orthographic", "Orthographic View Preferences"));
2737   Orthographic_constructPreferences(page);
2738 }
2739 void Orthographic_registerPreferencesPage()
2740 {
2741   PreferencesDialog_addSettingsPage(FreeCaller1<PreferenceGroup&, Orthographic_constructPage>());
2742 }
2743
2744 void Clipper_constructPreferences(PreferencesPage& page)
2745 {
2746   page.appendCheckBox("", "Clipper tool uses caulk", g_clip_useCaulk);
2747 }
2748 void Clipper_constructPage(PreferenceGroup& group)
2749 {
2750   PreferencesPage page(group.createPage("Clipper", "Clipper Tool Settings"));
2751   Clipper_constructPreferences(page);
2752 }
2753 void Clipper_registerPreferencesPage()
2754 {
2755   PreferencesDialog_addSettingsPage(FreeCaller1<PreferenceGroup&, Clipper_constructPage>());
2756 }
2757
2758
2759 #include "preferencesystem.h"
2760 #include "stringio.h"
2761
2762
2763
2764
2765 void ToggleShown_importBool(ToggleShown& self, bool value)
2766 {
2767   self.set(value);
2768 }
2769 typedef ReferenceCaller1<ToggleShown, bool, ToggleShown_importBool> ToggleShownImportBoolCaller;
2770 void ToggleShown_exportBool(const ToggleShown& self, const BoolImportCallback& importer)
2771 {
2772   importer(self.active());
2773 }
2774 typedef ConstReferenceCaller1<ToggleShown, const BoolImportCallback&, ToggleShown_exportBool> ToggleShownExportBoolCaller;
2775
2776
2777 void XYWindow_Construct()
2778 {
2779   GlobalCommands_insert("ToggleCrosshairs", FreeCaller<ToggleShowCrosshair>(), Accelerator('X', (GdkModifierType)GDK_SHIFT_MASK));
2780   GlobalCommands_insert("ToggleSizePaint", FreeCaller<ToggleShowSizeInfo>(), Accelerator('J'));
2781   GlobalCommands_insert("ToggleGrid", FreeCaller<ToggleShowGrid>(), Accelerator('0'));
2782
2783   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)));
2784   GlobalToggles_insert("ToggleSideView", ToggleShown::ToggleCaller(g_yz_side_shown), ToggleItem::AddCallbackCaller(g_yz_side_shown.m_item));
2785   GlobalToggles_insert("ToggleFrontView", ToggleShown::ToggleCaller(g_xz_front_shown), ToggleItem::AddCallbackCaller(g_xz_front_shown.m_item));
2786   GlobalCommands_insert("NextView", FreeCaller<XY_Next>(), Accelerator(GDK_Tab, (GdkModifierType)GDK_CONTROL_MASK));
2787   GlobalCommands_insert("ZoomIn", FreeCaller<XY_ZoomIn>(), Accelerator(GDK_Delete));
2788   GlobalCommands_insert("ZoomOut", FreeCaller<XY_ZoomOut>(), Accelerator(GDK_Insert));
2789   GlobalCommands_insert("ViewTop", FreeCaller<XY_Top>());
2790   GlobalCommands_insert("ViewSide", FreeCaller<XY_Side>());
2791   GlobalCommands_insert("ViewFront", FreeCaller<XY_Front>());
2792   GlobalCommands_insert("Zoom100", FreeCaller<XY_Zoom100>());
2793   GlobalCommands_insert("CenterXYViews", FreeCaller<XY_Split_Focus>(), Accelerator(GDK_Tab, (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK)));
2794   GlobalCommands_insert("CenterXYView", FreeCaller<XY_Focus>(), Accelerator(GDK_Tab, (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK)));
2795
2796   GlobalPreferenceSystem().registerPreference("ClipCaulk", BoolImportStringCaller(g_clip_useCaulk), BoolExportStringCaller(g_clip_useCaulk));
2797
2798   GlobalPreferenceSystem().registerPreference("NewRightClick", BoolImportStringCaller(g_xywindow_globals.m_bRightClick), BoolExportStringCaller(g_xywindow_globals.m_bRightClick));
2799   GlobalPreferenceSystem().registerPreference("ChaseMouse", BoolImportStringCaller(g_xywindow_globals_private.m_bChaseMouse), BoolExportStringCaller(g_xywindow_globals_private.m_bChaseMouse));
2800   GlobalPreferenceSystem().registerPreference("SizePainting", BoolImportStringCaller(g_xywindow_globals_private.m_bSizePaint), BoolExportStringCaller(g_xywindow_globals_private.m_bSizePaint));
2801   GlobalPreferenceSystem().registerPreference("NoStipple", BoolImportStringCaller(g_xywindow_globals.m_bNoStipple), BoolExportStringCaller(g_xywindow_globals.m_bNoStipple));
2802   GlobalPreferenceSystem().registerPreference("SI_ShowCoords", BoolImportStringCaller(g_xywindow_globals_private.show_coordinates), BoolExportStringCaller(g_xywindow_globals_private.show_coordinates));
2803   GlobalPreferenceSystem().registerPreference("SI_ShowOutlines", BoolImportStringCaller(g_xywindow_globals_private.show_outline), BoolExportStringCaller(g_xywindow_globals_private.show_outline));
2804   GlobalPreferenceSystem().registerPreference("SI_ShowAxis", BoolImportStringCaller(g_xywindow_globals_private.show_axis), BoolExportStringCaller(g_xywindow_globals_private.show_axis));
2805   GlobalPreferenceSystem().registerPreference("CamXYUpdate", BoolImportStringCaller(g_xywindow_globals_private.m_bCamXYUpdate), BoolExportStringCaller(g_xywindow_globals_private.m_bCamXYUpdate));
2806   GlobalPreferenceSystem().registerPreference("ShowWorkzone", BoolImportStringCaller(g_xywindow_globals_private.d_show_work), BoolExportStringCaller(g_xywindow_globals_private.d_show_work));
2807
2808   GlobalPreferenceSystem().registerPreference("SI_AxisColors0", Vector3ImportStringCaller(g_xywindow_globals.AxisColorX), Vector3ExportStringCaller(g_xywindow_globals.AxisColorX));
2809   GlobalPreferenceSystem().registerPreference("SI_AxisColors1", Vector3ImportStringCaller(g_xywindow_globals.AxisColorY), Vector3ExportStringCaller(g_xywindow_globals.AxisColorY));
2810   GlobalPreferenceSystem().registerPreference("SI_AxisColors2", Vector3ImportStringCaller(g_xywindow_globals.AxisColorZ), Vector3ExportStringCaller(g_xywindow_globals.AxisColorZ));
2811   GlobalPreferenceSystem().registerPreference("SI_Colors1", Vector3ImportStringCaller(g_xywindow_globals.color_gridback), Vector3ExportStringCaller(g_xywindow_globals.color_gridback));
2812   GlobalPreferenceSystem().registerPreference("SI_Colors2", Vector3ImportStringCaller(g_xywindow_globals.color_gridminor), Vector3ExportStringCaller(g_xywindow_globals.color_gridminor));
2813   GlobalPreferenceSystem().registerPreference("SI_Colors3", Vector3ImportStringCaller(g_xywindow_globals.color_gridmajor), Vector3ExportStringCaller(g_xywindow_globals.color_gridmajor));
2814   GlobalPreferenceSystem().registerPreference("SI_Colors6", Vector3ImportStringCaller(g_xywindow_globals.color_gridblock), Vector3ExportStringCaller(g_xywindow_globals.color_gridblock));
2815   GlobalPreferenceSystem().registerPreference("SI_Colors7", Vector3ImportStringCaller(g_xywindow_globals.color_gridtext), Vector3ExportStringCaller(g_xywindow_globals.color_gridtext));
2816   GlobalPreferenceSystem().registerPreference("SI_Colors8", Vector3ImportStringCaller(g_xywindow_globals.color_brushes), Vector3ExportStringCaller(g_xywindow_globals.color_brushes));
2817   GlobalPreferenceSystem().registerPreference("SI_Colors9", Vector3ImportStringCaller(g_xywindow_globals.color_selbrushes), Vector3ExportStringCaller(g_xywindow_globals.color_selbrushes));
2818   GlobalPreferenceSystem().registerPreference("SI_Colors10", Vector3ImportStringCaller(g_xywindow_globals.color_clipper), Vector3ExportStringCaller(g_xywindow_globals.color_clipper));
2819   GlobalPreferenceSystem().registerPreference("SI_Colors11", Vector3ImportStringCaller(g_xywindow_globals.color_viewname), Vector3ExportStringCaller(g_xywindow_globals.color_viewname));
2820   GlobalPreferenceSystem().registerPreference("SI_Colors13", Vector3ImportStringCaller(g_xywindow_globals.color_gridminor_alt), Vector3ExportStringCaller(g_xywindow_globals.color_gridminor_alt));
2821   GlobalPreferenceSystem().registerPreference("SI_Colors14", Vector3ImportStringCaller(g_xywindow_globals.color_gridmajor_alt), Vector3ExportStringCaller(g_xywindow_globals.color_gridmajor_alt));
2822
2823
2824   GlobalPreferenceSystem().registerPreference("XZVIS", makeBoolStringImportCallback(ToggleShownImportBoolCaller(g_xz_front_shown)), makeBoolStringExportCallback(ToggleShownExportBoolCaller(g_xz_front_shown)));
2825   GlobalPreferenceSystem().registerPreference("YZVIS", makeBoolStringImportCallback(ToggleShownImportBoolCaller(g_yz_side_shown)), makeBoolStringExportCallback(ToggleShownExportBoolCaller(g_yz_side_shown)));
2826
2827   Orthographic_registerPreferencesPage();
2828   Clipper_registerPreferencesPage();
2829
2830   XYWnd::captureStates();
2831   GlobalEntityClassManager().attach(g_EntityClassMenu);
2832 }
2833
2834 void XYWindow_Destroy()
2835 {
2836   GlobalEntityClassManager().detach(g_EntityClassMenu);
2837   XYWnd::releaseStates();
2838 }