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