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