]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/camwindow.cpp
Merge commit '5a8c27d93c0c57243722ade7aa3ca1f696de46f2' into garux-merge
[xonotic/netradiant.git] / radiant / camwindow.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 // Camera Window
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 #include "camwindow.h"
29
30 #include <gtk/gtk.h>
31 #include <gdk/gdkkeysyms.h>
32
33 #include "debugging/debugging.h"
34
35 #include "iscenegraph.h"
36 #include "irender.h"
37 #include "igl.h"
38 #include "icamera.h"
39 #include "cullable.h"
40 #include "renderable.h"
41 #include "preferencesystem.h"
42
43 #include "signal/signal.h"
44 #include "container/array.h"
45 #include "scenelib.h"
46 #include "render.h"
47 #include "cmdlib.h"
48 #include "math/frustum.h"
49
50 #include "gtkutil/widget.h"
51 #include "gtkutil/button.h"
52 #include "gtkutil/toolbar.h"
53 #include "gtkutil/glwidget.h"
54 #include "gtkutil/xorrectangle.h"
55 #include "gtkmisc.h"
56 #include "selection.h"
57 #include "mainframe.h"
58 #include "preferences.h"
59 #include "commands.h"
60 #include "xywindow.h"
61 #include "windowobservers.h"
62 #include "renderstate.h"
63
64 #include "timer.h"
65
66 Signal0 g_cameraMoved_callbacks;
67
68 void AddCameraMovedCallback( const SignalHandler& handler ){
69         g_cameraMoved_callbacks.connectLast( handler );
70 }
71
72 void CameraMovedNotify(){
73         g_cameraMoved_callbacks();
74 }
75
76
77 struct camwindow_globals_private_t
78 {
79         int m_nMoveSpeed;
80         bool m_bCamLinkSpeed;
81         int m_nAngleSpeed;
82         bool m_bCamInverseMouse;
83         bool m_bCamDiscrete;
84         bool m_bCubicClipping;
85         bool m_showStats;
86         int m_nStrafeMode;
87
88         camwindow_globals_private_t() :
89                 m_nMoveSpeed( 100 ),
90                 m_bCamLinkSpeed( true ),
91                 m_nAngleSpeed( 3 ),
92                 m_bCamInverseMouse( false ),
93                 m_bCamDiscrete( true ),
94                 m_bCubicClipping( false ),
95                 m_showStats( true ),
96                 m_nStrafeMode( 0 ){
97         }
98
99 };
100
101 camwindow_globals_private_t g_camwindow_globals_private;
102
103
104 const Matrix4 g_opengl2radiant(
105         0, 0,-1, 0,
106         -1, 0, 0, 0,
107         0, 1, 0, 0,
108         0, 0, 0, 1
109         );
110
111 const Matrix4 g_radiant2opengl(
112         0,-1, 0, 0,
113         0, 0, 1, 0,
114         -1, 0, 0, 0,
115         0, 0, 0, 1
116         );
117
118 struct camera_t;
119 void Camera_mouseMove( camera_t& camera, int x, int y );
120
121 enum camera_draw_mode
122 {
123         cd_wire,
124         cd_solid,
125         cd_texture,
126         cd_lighting
127 };
128
129 struct camera_t
130 {
131         int width, height;
132
133         bool timing;
134
135         Vector3 origin;
136         Vector3 angles;
137
138         Vector3 color; // background
139
140         Vector3 forward, right; // move matrix (TTimo: used to have up but it was not updated)
141         Vector3 vup, vpn, vright; // view matrix (taken from the modelview matrix)
142
143         Matrix4 projection;
144         Matrix4 modelview;
145
146         bool m_strafe; // true when in strafemode toggled by the ctrl-key
147         bool m_strafe_forward; // true when in strafemode by ctrl-key and shift is pressed for forward strafing
148
149         unsigned int movementflags; // movement flags
150         Timer m_keycontrol_timer;
151         guint m_keymove_handler;
152
153
154         float fieldOfView;
155
156         DeferredMotionDelta m_mouseMove;
157
158         static void motionDelta( int x, int y, void* data ){
159                 Camera_mouseMove( *reinterpret_cast<camera_t*>( data ), x, y );
160         }
161
162         View* m_view;
163         Callback<void()> m_update;
164
165         static camera_draw_mode draw_mode;
166
167         camera_t( View* view, const Callback<void()>& update )
168                 : width( 0 ),
169                 height( 0 ),
170                 timing( false ),
171                 origin( 0, 0, 0 ),
172                 angles( 0, 0, 0 ),
173                 color( 0, 0, 0 ),
174                 movementflags( 0 ),
175                 m_keymove_handler( 0 ),
176                 fieldOfView( 110.0f ),
177                 m_mouseMove( motionDelta, this ),
178                 m_view( view ),
179                 m_update( update ){
180         }
181 };
182
183 camera_draw_mode camera_t::draw_mode = cd_texture;
184
185 inline Matrix4 projection_for_camera( float near_z, float far_z, float fieldOfView, int width, int height ){
186         const float half_width = static_cast<float>( near_z * tan( degrees_to_radians( fieldOfView * 0.5 ) ) );
187         const float half_height = half_width * ( static_cast<float>( height ) / static_cast<float>( width ) );
188
189         return matrix4_frustum(
190                            -half_width,
191                            half_width,
192                            -half_height,
193                            half_height,
194                            near_z,
195                            far_z
196                            );
197 }
198
199 float Camera_getFarClipPlane( camera_t& camera ){
200         return ( g_camwindow_globals_private.m_bCubicClipping ) ? pow( 2.0, ( g_camwindow_globals.m_nCubicScale + 7 ) / 2.0 ) : 32768.0f;
201 }
202
203 void Camera_updateProjection( camera_t& camera ){
204         float farClip = Camera_getFarClipPlane( camera );
205         camera.projection = projection_for_camera( farClip / 4096.0f, farClip, camera.fieldOfView, camera.width, camera.height );
206
207         camera.m_view->Construct( camera.projection, camera.modelview, camera.width, camera.height );
208 }
209
210 void Camera_updateVectors( camera_t& camera ){
211         for ( int i = 0 ; i < 3 ; i++ )
212         {
213                 camera.vright[i] = camera.modelview[( i << 2 ) + 0];
214                 camera.vup[i] = camera.modelview[( i << 2 ) + 1];
215                 camera.vpn[i] = camera.modelview[( i << 2 ) + 2];
216         }
217 }
218
219 void Camera_updateModelview( camera_t& camera ){
220         camera.modelview = g_matrix4_identity;
221
222         // roll, pitch, yaw
223         Vector3 radiant_eulerXYZ( 0, -camera.angles[CAMERA_PITCH], camera.angles[CAMERA_YAW] );
224
225         matrix4_translate_by_vec3( camera.modelview, camera.origin );
226         matrix4_rotate_by_euler_xyz_degrees( camera.modelview, radiant_eulerXYZ );
227         matrix4_multiply_by_matrix4( camera.modelview, g_radiant2opengl );
228         matrix4_affine_invert( camera.modelview );
229
230         Camera_updateVectors( camera );
231
232         camera.m_view->Construct( camera.projection, camera.modelview, camera.width, camera.height );
233 }
234
235
236 void Camera_Move_updateAxes( camera_t& camera ){
237         double ya = degrees_to_radians( camera.angles[CAMERA_YAW] );
238
239         // the movement matrix is kept 2d
240         camera.forward[0] = static_cast<float>( cos( ya ) );
241         camera.forward[1] = static_cast<float>( sin( ya ) );
242         camera.forward[2] = 0;
243         camera.right[0] = camera.forward[1];
244         camera.right[1] = -camera.forward[0];
245 }
246
247 void Camera_Freemove_updateAxes( camera_t& camera ){
248         camera.right = camera.vright;
249         camera.forward = vector3_negated( camera.vpn );
250 }
251
252 const Vector3& Camera_getOrigin( camera_t& camera ){
253         return camera.origin;
254 }
255
256 void Camera_setOrigin( camera_t& camera, const Vector3& origin ){
257         camera.origin = origin;
258         Camera_updateModelview( camera );
259         camera.m_update();
260         CameraMovedNotify();
261 }
262
263 const Vector3& Camera_getAngles( camera_t& camera ){
264         return camera.angles;
265 }
266
267 void Camera_setAngles( camera_t& camera, const Vector3& angles ){
268         camera.angles = angles;
269         Camera_updateModelview( camera );
270         camera.m_update();
271         CameraMovedNotify();
272 }
273
274
275 void Camera_FreeMove( camera_t& camera, int dx, int dy ){
276         // free strafe mode, toggled by the ctrl key with optional shift for forward movement
277         if ( camera.m_strafe ) {
278                 float strafespeed = 0.65f;
279
280                 if ( g_camwindow_globals_private.m_bCamLinkSpeed ) {
281                         strafespeed = (float)g_camwindow_globals_private.m_nMoveSpeed / 100;
282                 }
283
284                 camera.origin -= camera.vright * strafespeed * dx;
285                 if ( camera.m_strafe_forward ) {
286                         camera.origin -= camera.vpn * strafespeed * dy;
287                 }
288                 else{
289                         camera.origin += camera.vup * strafespeed * dy;
290                 }
291         }
292         else // free rotation
293         {
294                 const float dtime = 0.1f;
295
296                 if ( g_camwindow_globals_private.m_bCamInverseMouse ) {
297                         camera.angles[CAMERA_PITCH] -= dy * dtime * g_camwindow_globals_private.m_nAngleSpeed;
298                 }
299                 else{
300                         camera.angles[CAMERA_PITCH] += dy * dtime * g_camwindow_globals_private.m_nAngleSpeed;
301                 }
302
303                 camera.angles[CAMERA_YAW] += dx * dtime * g_camwindow_globals_private.m_nAngleSpeed;
304
305                 if ( camera.angles[CAMERA_PITCH] > 90 ) {
306                         camera.angles[CAMERA_PITCH] = 90;
307                 }
308                 else if ( camera.angles[CAMERA_PITCH] < -90 ) {
309                         camera.angles[CAMERA_PITCH] = -90;
310                 }
311
312                 if ( camera.angles[CAMERA_YAW] >= 360 ) {
313                         camera.angles[CAMERA_YAW] -= 360;
314                 }
315                 else if ( camera.angles[CAMERA_YAW] <= 0 ) {
316                         camera.angles[CAMERA_YAW] += 360;
317                 }
318         }
319
320         Camera_updateModelview( camera );
321         Camera_Freemove_updateAxes( camera );
322 }
323
324 void Cam_MouseControl( camera_t& camera, int x, int y ){
325         float xf = (float)( x - camera.width / 2 ) / ( camera.width / 2 );
326         float yf = (float)( y - camera.height / 2 ) / ( camera.height / 2 );
327
328         xf *= 1.0f - fabsf( yf );
329         if ( xf < 0 ) {
330                 xf += 0.1f;
331                 if ( xf > 0 ) {
332                         xf = 0;
333                 }
334         }
335         else
336         {
337                 xf -= 0.1f;
338                 if ( xf < 0 ) {
339                         xf = 0;
340                 }
341         }
342
343         vector3_add( camera.origin, vector3_scaled( camera.forward, yf * 0.1f * g_camwindow_globals_private.m_nMoveSpeed ) );
344         camera.angles[CAMERA_YAW] += xf * -0.1f * g_camwindow_globals_private.m_nAngleSpeed;
345
346         Camera_updateModelview( camera );
347 }
348
349 void Camera_mouseMove( camera_t& camera, int x, int y ){
350         //globalOutputStream() << "mousemove... ";
351         Camera_FreeMove( camera, -x, -y );
352         camera.m_update();
353         CameraMovedNotify();
354 }
355
356 const unsigned int MOVE_NONE = 0;
357 const unsigned int MOVE_FORWARD = 1 << 0;
358 const unsigned int MOVE_BACK = 1 << 1;
359 const unsigned int MOVE_ROTRIGHT = 1 << 2;
360 const unsigned int MOVE_ROTLEFT = 1 << 3;
361 const unsigned int MOVE_STRAFERIGHT = 1 << 4;
362 const unsigned int MOVE_STRAFELEFT = 1 << 5;
363 const unsigned int MOVE_UP = 1 << 6;
364 const unsigned int MOVE_DOWN = 1 << 7;
365 const unsigned int MOVE_PITCHUP = 1 << 8;
366 const unsigned int MOVE_PITCHDOWN = 1 << 9;
367 const unsigned int MOVE_ALL = MOVE_FORWARD | MOVE_BACK | MOVE_ROTRIGHT | MOVE_ROTLEFT | MOVE_STRAFERIGHT | MOVE_STRAFELEFT | MOVE_UP | MOVE_DOWN | MOVE_PITCHUP | MOVE_PITCHDOWN;
368
369 void Cam_KeyControl( camera_t& camera, float dtime ){
370         // Update angles
371         if ( camera.movementflags & MOVE_ROTLEFT ) {
372                 camera.angles[CAMERA_YAW] += 15 * dtime * g_camwindow_globals_private.m_nAngleSpeed;
373         }
374         if ( camera.movementflags & MOVE_ROTRIGHT ) {
375                 camera.angles[CAMERA_YAW] -= 15 * dtime * g_camwindow_globals_private.m_nAngleSpeed;
376         }
377         if ( camera.movementflags & MOVE_PITCHUP ) {
378                 camera.angles[CAMERA_PITCH] += 15 * dtime * g_camwindow_globals_private.m_nAngleSpeed;
379                 if ( camera.angles[CAMERA_PITCH] > 90 ) {
380                         camera.angles[CAMERA_PITCH] = 90;
381                 }
382         }
383         if ( camera.movementflags & MOVE_PITCHDOWN ) {
384                 camera.angles[CAMERA_PITCH] -= 15 * dtime * g_camwindow_globals_private.m_nAngleSpeed;
385                 if ( camera.angles[CAMERA_PITCH] < -90 ) {
386                         camera.angles[CAMERA_PITCH] = -90;
387                 }
388         }
389
390         Camera_updateModelview( camera );
391         Camera_Freemove_updateAxes( camera );
392
393         // Update position
394         if ( camera.movementflags & MOVE_FORWARD ) {
395                 vector3_add( camera.origin, vector3_scaled( camera.forward, dtime * g_camwindow_globals_private.m_nMoveSpeed ) );
396         }
397         if ( camera.movementflags & MOVE_BACK ) {
398                 vector3_add( camera.origin, vector3_scaled( camera.forward, -dtime * g_camwindow_globals_private.m_nMoveSpeed ) );
399         }
400         if ( camera.movementflags & MOVE_STRAFELEFT ) {
401                 vector3_add( camera.origin, vector3_scaled( camera.right, -dtime * g_camwindow_globals_private.m_nMoveSpeed ) );
402         }
403         if ( camera.movementflags & MOVE_STRAFERIGHT ) {
404                 vector3_add( camera.origin, vector3_scaled( camera.right, dtime * g_camwindow_globals_private.m_nMoveSpeed ) );
405         }
406         if ( camera.movementflags & MOVE_UP ) {
407                 vector3_add( camera.origin, vector3_scaled( g_vector3_axis_z, dtime * g_camwindow_globals_private.m_nMoveSpeed ) );
408         }
409         if ( camera.movementflags & MOVE_DOWN ) {
410                 vector3_add( camera.origin, vector3_scaled( g_vector3_axis_z, -dtime * g_camwindow_globals_private.m_nMoveSpeed ) );
411         }
412
413         Camera_updateModelview( camera );
414 }
415
416 void Camera_keyMove( camera_t& camera ){
417         camera.m_mouseMove.flush();
418
419         //globalOutputStream() << "keymove... ";
420         float time_seconds = camera.m_keycontrol_timer.elapsed_msec() / static_cast<float>( msec_per_sec );
421         camera.m_keycontrol_timer.start();
422         if ( time_seconds > 0.05f ) {
423                 time_seconds = 0.05f; // 20fps
424         }
425         Cam_KeyControl( camera, time_seconds * 5.0f );
426
427         camera.m_update();
428         CameraMovedNotify();
429 }
430
431 gboolean camera_keymove( gpointer data ){
432         Camera_keyMove( *reinterpret_cast<camera_t*>( data ) );
433         return TRUE;
434 }
435
436 void Camera_setMovementFlags( camera_t& camera, unsigned int mask ){
437         if ( ( ~camera.movementflags & mask ) != 0 && camera.movementflags == 0 ) {
438                 camera.m_keymove_handler = g_idle_add( camera_keymove, &camera );
439         }
440         camera.movementflags |= mask;
441 }
442 void Camera_clearMovementFlags( camera_t& camera, unsigned int mask ){
443         if ( ( camera.movementflags & ~mask ) == 0 && camera.movementflags != 0 ) {
444                 g_source_remove( camera.m_keymove_handler );
445                 camera.m_keymove_handler = 0;
446         }
447         camera.movementflags &= ~mask;
448 }
449
450 void Camera_MoveForward_KeyDown( camera_t& camera ){
451         Camera_setMovementFlags( camera, MOVE_FORWARD );
452 }
453 void Camera_MoveForward_KeyUp( camera_t& camera ){
454         Camera_clearMovementFlags( camera, MOVE_FORWARD );
455 }
456 void Camera_MoveBack_KeyDown( camera_t& camera ){
457         Camera_setMovementFlags( camera, MOVE_BACK );
458 }
459 void Camera_MoveBack_KeyUp( camera_t& camera ){
460         Camera_clearMovementFlags( camera, MOVE_BACK );
461 }
462
463 void Camera_MoveLeft_KeyDown( camera_t& camera ){
464         Camera_setMovementFlags( camera, MOVE_STRAFELEFT );
465 }
466 void Camera_MoveLeft_KeyUp( camera_t& camera ){
467         Camera_clearMovementFlags( camera, MOVE_STRAFELEFT );
468 }
469 void Camera_MoveRight_KeyDown( camera_t& camera ){
470         Camera_setMovementFlags( camera, MOVE_STRAFERIGHT );
471 }
472 void Camera_MoveRight_KeyUp( camera_t& camera ){
473         Camera_clearMovementFlags( camera, MOVE_STRAFERIGHT );
474 }
475
476 void Camera_MoveUp_KeyDown( camera_t& camera ){
477         Camera_setMovementFlags( camera, MOVE_UP );
478 }
479 void Camera_MoveUp_KeyUp( camera_t& camera ){
480         Camera_clearMovementFlags( camera, MOVE_UP );
481 }
482 void Camera_MoveDown_KeyDown( camera_t& camera ){
483         Camera_setMovementFlags( camera, MOVE_DOWN );
484 }
485 void Camera_MoveDown_KeyUp( camera_t& camera ){
486         Camera_clearMovementFlags( camera, MOVE_DOWN );
487 }
488
489 void Camera_RotateLeft_KeyDown( camera_t& camera ){
490         Camera_setMovementFlags( camera, MOVE_ROTLEFT );
491 }
492 void Camera_RotateLeft_KeyUp( camera_t& camera ){
493         Camera_clearMovementFlags( camera, MOVE_ROTLEFT );
494 }
495 void Camera_RotateRight_KeyDown( camera_t& camera ){
496         Camera_setMovementFlags( camera, MOVE_ROTRIGHT );
497 }
498 void Camera_RotateRight_KeyUp( camera_t& camera ){
499         Camera_clearMovementFlags( camera, MOVE_ROTRIGHT );
500 }
501
502 void Camera_PitchUp_KeyDown( camera_t& camera ){
503         Camera_setMovementFlags( camera, MOVE_PITCHUP );
504 }
505 void Camera_PitchUp_KeyUp( camera_t& camera ){
506         Camera_clearMovementFlags( camera, MOVE_PITCHUP );
507 }
508 void Camera_PitchDown_KeyDown( camera_t& camera ){
509         Camera_setMovementFlags( camera, MOVE_PITCHDOWN );
510 }
511 void Camera_PitchDown_KeyUp( camera_t& camera ){
512         Camera_clearMovementFlags( camera, MOVE_PITCHDOWN );
513 }
514
515
516 typedef ReferenceCaller<camera_t, void(), &Camera_MoveForward_KeyDown> FreeMoveCameraMoveForwardKeyDownCaller;
517 typedef ReferenceCaller<camera_t, void(), &Camera_MoveForward_KeyUp> FreeMoveCameraMoveForwardKeyUpCaller;
518 typedef ReferenceCaller<camera_t, void(), &Camera_MoveBack_KeyDown> FreeMoveCameraMoveBackKeyDownCaller;
519 typedef ReferenceCaller<camera_t, void(), &Camera_MoveBack_KeyUp> FreeMoveCameraMoveBackKeyUpCaller;
520 typedef ReferenceCaller<camera_t, void(), &Camera_MoveLeft_KeyDown> FreeMoveCameraMoveLeftKeyDownCaller;
521 typedef ReferenceCaller<camera_t, void(), &Camera_MoveLeft_KeyUp> FreeMoveCameraMoveLeftKeyUpCaller;
522 typedef ReferenceCaller<camera_t, void(), &Camera_MoveRight_KeyDown> FreeMoveCameraMoveRightKeyDownCaller;
523 typedef ReferenceCaller<camera_t, void(), &Camera_MoveRight_KeyUp> FreeMoveCameraMoveRightKeyUpCaller;
524 typedef ReferenceCaller<camera_t, void(), &Camera_MoveUp_KeyDown> FreeMoveCameraMoveUpKeyDownCaller;
525 typedef ReferenceCaller<camera_t, void(), &Camera_MoveUp_KeyUp> FreeMoveCameraMoveUpKeyUpCaller;
526 typedef ReferenceCaller<camera_t, void(), &Camera_MoveDown_KeyDown> FreeMoveCameraMoveDownKeyDownCaller;
527 typedef ReferenceCaller<camera_t, void(), &Camera_MoveDown_KeyUp> FreeMoveCameraMoveDownKeyUpCaller;
528
529
530 const float SPEED_MOVE = 32;
531 const float SPEED_TURN = 22.5;
532 const float MIN_CAM_SPEED = 10;
533 const float MAX_CAM_SPEED = 610;
534 const float CAM_SPEED_STEP = 50;
535
536 void Camera_MoveForward_Discrete( camera_t& camera ){
537         Camera_Move_updateAxes( camera );
538         Camera_setOrigin( camera, vector3_added( Camera_getOrigin( camera ), vector3_scaled( camera.forward, SPEED_MOVE ) ) );
539 }
540 void Camera_MoveBack_Discrete( camera_t& camera ){
541         Camera_Move_updateAxes( camera );
542         Camera_setOrigin( camera, vector3_added( Camera_getOrigin( camera ), vector3_scaled( camera.forward, -SPEED_MOVE ) ) );
543 }
544
545 void Camera_MoveUp_Discrete( camera_t& camera ){
546         Vector3 origin( Camera_getOrigin( camera ) );
547         origin[2] += SPEED_MOVE;
548         Camera_setOrigin( camera, origin );
549 }
550 void Camera_MoveDown_Discrete( camera_t& camera ){
551         Vector3 origin( Camera_getOrigin( camera ) );
552         origin[2] -= SPEED_MOVE;
553         Camera_setOrigin( camera, origin );
554 }
555
556 void Camera_MoveLeft_Discrete( camera_t& camera ){
557         Camera_Move_updateAxes( camera );
558         Camera_setOrigin( camera, vector3_added( Camera_getOrigin( camera ), vector3_scaled( camera.right, -SPEED_MOVE ) ) );
559 }
560 void Camera_MoveRight_Discrete( camera_t& camera ){
561         Camera_Move_updateAxes( camera );
562         Camera_setOrigin( camera, vector3_added( Camera_getOrigin( camera ), vector3_scaled( camera.right, SPEED_MOVE ) ) );
563 }
564
565 void Camera_RotateLeft_Discrete( camera_t& camera ){
566         Vector3 angles( Camera_getAngles( camera ) );
567         angles[CAMERA_YAW] += SPEED_TURN;
568         Camera_setAngles( camera, angles );
569 }
570 void Camera_RotateRight_Discrete( camera_t& camera ){
571         Vector3 angles( Camera_getAngles( camera ) );
572         angles[CAMERA_YAW] -= SPEED_TURN;
573         Camera_setAngles( camera, angles );
574 }
575
576 void Camera_PitchUp_Discrete( camera_t& camera ){
577         Vector3 angles( Camera_getAngles( camera ) );
578         angles[CAMERA_PITCH] += SPEED_TURN;
579         if ( angles[CAMERA_PITCH] > 90 ) {
580                 angles[CAMERA_PITCH] = 90;
581         }
582         Camera_setAngles( camera, angles );
583 }
584 void Camera_PitchDown_Discrete( camera_t& camera ){
585         Vector3 angles( Camera_getAngles( camera ) );
586         angles[CAMERA_PITCH] -= SPEED_TURN;
587         if ( angles[CAMERA_PITCH] < -90 ) {
588                 angles[CAMERA_PITCH] = -90;
589         }
590         Camera_setAngles( camera, angles );
591 }
592
593
594 class RadiantCameraView : public CameraView
595 {
596 camera_t& m_camera;
597 View* m_view;
598 Callback<void()> m_update;
599 public:
600 RadiantCameraView( camera_t& camera, View* view, const Callback<void()>& update ) : m_camera( camera ), m_view( view ), m_update( update ){
601 }
602 void update(){
603         m_view->Construct( m_camera.projection, m_camera.modelview, m_camera.width, m_camera.height );
604         m_update();
605 }
606 void setModelview( const Matrix4& modelview ){
607         m_camera.modelview = modelview;
608         matrix4_multiply_by_matrix4( m_camera.modelview, g_radiant2opengl );
609         matrix4_affine_invert( m_camera.modelview );
610         Camera_updateVectors( m_camera );
611         update();
612 }
613 void setFieldOfView( float fieldOfView ){
614         float farClip = Camera_getFarClipPlane( m_camera );
615         m_camera.projection = projection_for_camera( farClip / 4096.0f, farClip, fieldOfView, m_camera.width, m_camera.height );
616         update();
617 }
618 };
619
620
621 void Camera_motionDelta( int x, int y, unsigned int state, void* data ){
622         camera_t* cam = reinterpret_cast<camera_t*>( data );
623
624         cam->m_mouseMove.motion_delta( x, y, state );
625
626         switch ( g_camwindow_globals_private.m_nStrafeMode )
627         {
628         case 0:
629                 cam->m_strafe = ( state & GDK_CONTROL_MASK ) != 0;
630                 if ( cam->m_strafe ) {
631                         cam->m_strafe_forward = ( state & GDK_SHIFT_MASK ) != 0;
632                 }
633                 else{
634                         cam->m_strafe_forward = false;
635                 }
636                 break;
637         case 1:
638                 cam->m_strafe = ( state & GDK_CONTROL_MASK ) != 0 && ( state & GDK_SHIFT_MASK ) == 0;
639                 cam->m_strafe_forward = false;
640                 break;
641         case 2:
642                 cam->m_strafe = ( state & GDK_CONTROL_MASK ) != 0 && ( state & GDK_SHIFT_MASK ) == 0;
643                 cam->m_strafe_forward = cam->m_strafe;
644                 break;
645         }
646 }
647
648 class CamWnd
649 {
650 View m_view;
651 camera_t m_Camera;
652 RadiantCameraView m_cameraview;
653 #if 0
654 int m_PositionDragCursorX;
655 int m_PositionDragCursorY;
656 #endif
657
658 guint m_freemove_handle_focusout;
659
660 static Shader* m_state_select1;
661 static Shader* m_state_select2;
662
663 FreezePointer m_freezePointer;
664
665 public:
666 ui::GLArea m_gl_widget;
667 ui::Window m_parent{ui::null};
668
669 SelectionSystemWindowObserver* m_window_observer;
670 XORRectangle m_XORRectangle;
671
672 DeferredDraw m_deferredDraw;
673 DeferredMotion m_deferred_motion;
674
675 guint m_selection_button_press_handler;
676 guint m_selection_button_release_handler;
677 guint m_selection_motion_handler;
678
679 guint m_freelook_button_press_handler;
680
681 guint m_sizeHandler;
682 guint m_exposeHandler;
683
684 CamWnd();
685 ~CamWnd();
686
687 bool m_drawing;
688 void queue_draw(){
689         //ASSERT_MESSAGE(!m_drawing, "CamWnd::queue_draw(): called while draw is already in progress");
690         if ( m_drawing ) {
691                 return;
692         }
693         //globalOutputStream() << "queue... ";
694         m_deferredDraw.draw();
695 }
696 void draw();
697
698 static void captureStates(){
699         m_state_select1 = GlobalShaderCache().capture( "$CAM_HIGHLIGHT" );
700         m_state_select2 = GlobalShaderCache().capture( "$CAM_OVERLAY" );
701 }
702 static void releaseStates(){
703         GlobalShaderCache().release( "$CAM_HIGHLIGHT" );
704         GlobalShaderCache().release( "$CAM_OVERLAY" );
705 }
706
707 camera_t& getCamera(){
708         return m_Camera;
709 };
710
711 void BenchMark();
712 void Cam_ChangeFloor( bool up );
713
714 void DisableFreeMove();
715 void EnableFreeMove();
716 bool m_bFreeMove;
717
718 CameraView& getCameraView(){
719         return m_cameraview;
720 }
721
722 private:
723 void Cam_Draw();
724 };
725
726 typedef MemberCaller<CamWnd, void(), &CamWnd::queue_draw> CamWndQueueDraw;
727
728 Shader* CamWnd::m_state_select1 = 0;
729 Shader* CamWnd::m_state_select2 = 0;
730
731 CamWnd* NewCamWnd(){
732         return new CamWnd;
733 }
734 void DeleteCamWnd( CamWnd* camwnd ){
735         delete camwnd;
736 }
737
738 void CamWnd_constructStatic(){
739         CamWnd::captureStates();
740 }
741
742 void CamWnd_destroyStatic(){
743         CamWnd::releaseStates();
744 }
745
746 static CamWnd* g_camwnd = 0;
747
748 void GlobalCamera_setCamWnd( CamWnd& camwnd ){
749         g_camwnd = &camwnd;
750 }
751
752
753 ui::GLArea CamWnd_getWidget( CamWnd& camwnd ){
754         return camwnd.m_gl_widget;
755 }
756
757 ui::Window CamWnd_getParent( CamWnd& camwnd ){
758         return camwnd.m_parent;
759 }
760
761 ToggleShown g_camera_shown( true );
762
763 void CamWnd_setParent( CamWnd& camwnd, ui::Window parent ){
764         camwnd.m_parent = parent;
765         g_camera_shown.connect( camwnd.m_parent );
766 }
767
768 void CamWnd_Update( CamWnd& camwnd ){
769         camwnd.queue_draw();
770 }
771
772
773
774 camwindow_globals_t g_camwindow_globals;
775
776 const Vector3& Camera_getOrigin( CamWnd& camwnd ){
777         return Camera_getOrigin( camwnd.getCamera() );
778 }
779
780 void Camera_setOrigin( CamWnd& camwnd, const Vector3& origin ){
781         Camera_setOrigin( camwnd.getCamera(), origin );
782 }
783
784 const Vector3& Camera_getAngles( CamWnd& camwnd ){
785         return Camera_getAngles( camwnd.getCamera() );
786 }
787
788 void Camera_setAngles( CamWnd& camwnd, const Vector3& angles ){
789         Camera_setAngles( camwnd.getCamera(), angles );
790 }
791
792
793 // =============================================================================
794 // CamWnd class
795
796 gboolean enable_freelook_button_press( ui::Widget widget, GdkEventButton* event, CamWnd* camwnd ){
797         if ( event->type == GDK_BUTTON_PRESS && event->button == 3 && modifiers_for_state( event->state ) == c_modifierNone ) {
798                 camwnd->EnableFreeMove();
799                 return TRUE;
800         }
801         return FALSE;
802 }
803
804 gboolean disable_freelook_button_press( ui::Widget widget, GdkEventButton* event, CamWnd* camwnd ){
805         if ( event->type == GDK_BUTTON_PRESS && event->button == 3 && modifiers_for_state( event->state ) == c_modifierNone ) {
806                 camwnd->DisableFreeMove();
807                 return TRUE;
808         }
809         return FALSE;
810 }
811
812 #if 0
813 gboolean mousecontrol_button_press( ui::Widget widget, GdkEventButton* event, CamWnd* camwnd ){
814         if ( event->type == GDK_BUTTON_PRESS && event->button == 3 ) {
815                 Cam_MouseControl( camwnd->getCamera(), event->x, widget->allocation.height - 1 - event->y );
816         }
817         return FALSE;
818 }
819 #endif
820
821 void camwnd_update_xor_rectangle( CamWnd& self, rect_t area ){
822         if ( self.m_gl_widget.visible() ) {
823                 self.m_XORRectangle.set( rectangle_from_area( area.min, area.max, self.getCamera().width, self.getCamera().height ) );
824         }
825 }
826
827
828 gboolean selection_button_press( ui::Widget widget, GdkEventButton* event, WindowObserver* observer ){
829         if ( event->type == GDK_BUTTON_PRESS ) {
830                 observer->onMouseDown( WindowVector_forDouble( event->x, event->y ), button_for_button( event->button ), modifiers_for_state( event->state ) );
831         }
832         return FALSE;
833 }
834
835 gboolean selection_button_release( ui::Widget widget, GdkEventButton* event, WindowObserver* observer ){
836         if ( event->type == GDK_BUTTON_RELEASE ) {
837                 observer->onMouseUp( WindowVector_forDouble( event->x, event->y ), button_for_button( event->button ), modifiers_for_state( event->state ) );
838         }
839         return FALSE;
840 }
841
842 void selection_motion( gdouble x, gdouble y, guint state, void* data ){
843         //globalOutputStream() << "motion... ";
844         reinterpret_cast<WindowObserver*>( data )->onMouseMotion( WindowVector_forDouble( x, y ), modifiers_for_state( state ) );
845 }
846
847 inline WindowVector windowvector_for_widget_centre( ui::Widget widget ){
848         auto allocation = widget.dimensions();
849         return WindowVector( static_cast<float>( allocation.width / 2 ), static_cast<float>(allocation.height / 2 ) );
850 }
851
852 gboolean selection_button_press_freemove( ui::Widget widget, GdkEventButton* event, WindowObserver* observer ){
853         if ( event->type == GDK_BUTTON_PRESS ) {
854                 observer->onMouseDown( windowvector_for_widget_centre( widget ), button_for_button( event->button ), modifiers_for_state( event->state ) );
855         }
856         return FALSE;
857 }
858
859 gboolean selection_button_release_freemove( ui::Widget widget, GdkEventButton* event, WindowObserver* observer ){
860         if ( event->type == GDK_BUTTON_RELEASE ) {
861                 observer->onMouseUp( windowvector_for_widget_centre( widget ), button_for_button( event->button ), modifiers_for_state( event->state ) );
862         }
863         return FALSE;
864 }
865
866 gboolean selection_motion_freemove( ui::Widget widget, GdkEventMotion *event, WindowObserver* observer ){
867         observer->onMouseMotion( windowvector_for_widget_centre( widget ), modifiers_for_state( event->state ) );
868         return FALSE;
869 }
870
871 gboolean wheelmove_scroll( ui::Widget widget, GdkEventScroll* event, CamWnd* camwnd ){
872         if ( event->direction == GDK_SCROLL_UP ) {
873                 Camera_Freemove_updateAxes( camwnd->getCamera() );
874                 Camera_setOrigin( *camwnd, vector3_added( Camera_getOrigin( *camwnd ), vector3_scaled( camwnd->getCamera().forward, static_cast<float>( g_camwindow_globals_private.m_nMoveSpeed ) ) ) );
875         }
876         else if ( event->direction == GDK_SCROLL_DOWN ) {
877                 Camera_Freemove_updateAxes( camwnd->getCamera() );
878                 Camera_setOrigin( *camwnd, vector3_added( Camera_getOrigin( *camwnd ), vector3_scaled( camwnd->getCamera().forward, -static_cast<float>( g_camwindow_globals_private.m_nMoveSpeed ) ) ) );
879         }
880
881         return FALSE;
882 }
883
884 gboolean camera_size_allocate( ui::Widget widget, GtkAllocation* allocation, CamWnd* camwnd ){
885         camwnd->getCamera().width = allocation->width;
886         camwnd->getCamera().height = allocation->height;
887         Camera_updateProjection( camwnd->getCamera() );
888         camwnd->m_window_observer->onSizeChanged( camwnd->getCamera().width, camwnd->getCamera().height );
889         camwnd->queue_draw();
890         return FALSE;
891 }
892
893 gboolean camera_expose( ui::Widget widget, GdkEventExpose* event, gpointer data ){
894         reinterpret_cast<CamWnd*>( data )->draw();
895         return FALSE;
896 }
897
898 void KeyEvent_connect( const char* name ){
899         const KeyEvent& keyEvent = GlobalKeyEvents_find( name );
900         keydown_accelerators_add( keyEvent.m_accelerator, keyEvent.m_keyDown );
901         keyup_accelerators_add( keyEvent.m_accelerator, keyEvent.m_keyUp );
902 }
903
904 void KeyEvent_disconnect( const char* name ){
905         const KeyEvent& keyEvent = GlobalKeyEvents_find( name );
906         keydown_accelerators_remove( keyEvent.m_accelerator );
907         keyup_accelerators_remove( keyEvent.m_accelerator );
908 }
909
910 void CamWnd_registerCommands( CamWnd& camwnd ){
911         GlobalKeyEvents_insert( "CameraForward", Accelerator( GDK_KEY_Up ),
912                                                         ReferenceCaller<camera_t, void(), Camera_MoveForward_KeyDown>( camwnd.getCamera() ),
913                                                         ReferenceCaller<camera_t, void(), Camera_MoveForward_KeyUp>( camwnd.getCamera() )
914                                                         );
915         GlobalKeyEvents_insert( "CameraBack", Accelerator( GDK_KEY_Down ),
916                                                         ReferenceCaller<camera_t, void(), Camera_MoveBack_KeyDown>( camwnd.getCamera() ),
917                                                         ReferenceCaller<camera_t, void(), Camera_MoveBack_KeyUp>( camwnd.getCamera() )
918                                                         );
919         GlobalKeyEvents_insert( "CameraLeft", Accelerator( GDK_KEY_Left ),
920                                                         ReferenceCaller<camera_t, void(), Camera_RotateLeft_KeyDown>( camwnd.getCamera() ),
921                                                         ReferenceCaller<camera_t, void(), Camera_RotateLeft_KeyUp>( camwnd.getCamera() )
922                                                         );
923         GlobalKeyEvents_insert( "CameraRight", Accelerator( GDK_KEY_Right ),
924                                                         ReferenceCaller<camera_t, void(), Camera_RotateRight_KeyDown>( camwnd.getCamera() ),
925                                                         ReferenceCaller<camera_t, void(), Camera_RotateRight_KeyUp>( camwnd.getCamera() )
926                                                         );
927         GlobalKeyEvents_insert( "CameraStrafeRight", Accelerator( GDK_KEY_period ),
928                                                         ReferenceCaller<camera_t, void(), Camera_MoveRight_KeyDown>( camwnd.getCamera() ),
929                                                         ReferenceCaller<camera_t, void(), Camera_MoveRight_KeyUp>( camwnd.getCamera() )
930                                                         );
931         GlobalKeyEvents_insert( "CameraStrafeLeft", Accelerator( GDK_KEY_comma ),
932                                                         ReferenceCaller<camera_t, void(), Camera_MoveLeft_KeyDown>( camwnd.getCamera() ),
933                                                         ReferenceCaller<camera_t, void(), Camera_MoveLeft_KeyUp>( camwnd.getCamera() )
934                                                         );
935         GlobalKeyEvents_insert( "CameraUp", Accelerator( 'D' ),
936                                                         ReferenceCaller<camera_t, void(), Camera_MoveUp_KeyDown>( camwnd.getCamera() ),
937                                                         ReferenceCaller<camera_t, void(), Camera_MoveUp_KeyUp>( camwnd.getCamera() )
938                                                         );
939         GlobalKeyEvents_insert( "CameraDown", Accelerator( 'C' ),
940                                                         ReferenceCaller<camera_t, void(), Camera_MoveDown_KeyDown>( camwnd.getCamera() ),
941                                                         ReferenceCaller<camera_t, void(), Camera_MoveDown_KeyUp>( camwnd.getCamera() )
942                                                         );
943         GlobalKeyEvents_insert( "CameraAngleDown", Accelerator( 'A' ),
944                                                         ReferenceCaller<camera_t, void(), Camera_PitchDown_KeyDown>( camwnd.getCamera() ),
945                                                         ReferenceCaller<camera_t, void(), Camera_PitchDown_KeyUp>( camwnd.getCamera() )
946                                                         );
947         GlobalKeyEvents_insert( "CameraAngleUp", Accelerator( 'Z' ),
948                                                         ReferenceCaller<camera_t, void(), Camera_PitchUp_KeyDown>( camwnd.getCamera() ),
949                                                         ReferenceCaller<camera_t, void(), Camera_PitchUp_KeyUp>( camwnd.getCamera() )
950                                                         );
951
952         GlobalKeyEvents_insert( "CameraFreeMoveForward", Accelerator( GDK_KEY_Up ),
953                                                         FreeMoveCameraMoveForwardKeyDownCaller( camwnd.getCamera() ),
954                                                         FreeMoveCameraMoveForwardKeyUpCaller( camwnd.getCamera() )
955                                                         );
956         GlobalKeyEvents_insert( "CameraFreeMoveBack", Accelerator( GDK_KEY_Down ),
957                                                         FreeMoveCameraMoveBackKeyDownCaller( camwnd.getCamera() ),
958                                                         FreeMoveCameraMoveBackKeyUpCaller( camwnd.getCamera() )
959                                                         );
960         GlobalKeyEvents_insert( "CameraFreeMoveLeft", Accelerator( GDK_KEY_Left ),
961                                                         FreeMoveCameraMoveLeftKeyDownCaller( camwnd.getCamera() ),
962                                                         FreeMoveCameraMoveLeftKeyUpCaller( camwnd.getCamera() )
963                                                         );
964         GlobalKeyEvents_insert( "CameraFreeMoveRight", Accelerator( GDK_KEY_Right ),
965                                                         FreeMoveCameraMoveRightKeyDownCaller( camwnd.getCamera() ),
966                                                         FreeMoveCameraMoveRightKeyUpCaller( camwnd.getCamera() )
967                                                         );
968
969         GlobalKeyEvents_insert( "CameraFreeMoveForward2", Accelerator( GDK_Up ),
970                                                         FreeMoveCameraMoveForwardKeyDownCaller( camwnd.getCamera() ),
971                                                         FreeMoveCameraMoveForwardKeyUpCaller( camwnd.getCamera() )
972                                                         );
973         GlobalKeyEvents_insert( "CameraFreeMoveBack2", Accelerator( GDK_Down ),
974                                                         FreeMoveCameraMoveBackKeyDownCaller( camwnd.getCamera() ),
975                                                         FreeMoveCameraMoveBackKeyUpCaller( camwnd.getCamera() )
976                                                         );
977         GlobalKeyEvents_insert( "CameraFreeMoveLeft2", Accelerator( GDK_Left ),
978                                                         FreeMoveCameraMoveLeftKeyDownCaller( camwnd.getCamera() ),
979                                                         FreeMoveCameraMoveLeftKeyUpCaller( camwnd.getCamera() )
980                                                         );
981         GlobalKeyEvents_insert( "CameraFreeMoveRight2", Accelerator( GDK_Right ),
982                                                         FreeMoveCameraMoveRightKeyDownCaller( camwnd.getCamera() ),
983                                                         FreeMoveCameraMoveRightKeyUpCaller( camwnd.getCamera() )
984                                                         );
985
986         GlobalKeyEvents_insert( "CameraFreeMoveUp", Accelerator( 'D' ),
987                                                         FreeMoveCameraMoveUpKeyDownCaller( camwnd.getCamera() ),
988                                                         FreeMoveCameraMoveUpKeyUpCaller( camwnd.getCamera() )
989                                                         );
990         GlobalKeyEvents_insert( "CameraFreeMoveDown", Accelerator( 'C' ),
991                                                         FreeMoveCameraMoveDownKeyDownCaller( camwnd.getCamera() ),
992                                                         FreeMoveCameraMoveDownKeyUpCaller( camwnd.getCamera() )
993                                                         );
994
995         GlobalCommands_insert( "CameraForward", ReferenceCaller<camera_t, void(), Camera_MoveForward_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_Up ) );
996         GlobalCommands_insert( "CameraBack", ReferenceCaller<camera_t, void(), Camera_MoveBack_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_Down ) );
997         GlobalCommands_insert( "CameraLeft", ReferenceCaller<camera_t, void(), Camera_RotateLeft_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_Left ) );
998         GlobalCommands_insert( "CameraRight", ReferenceCaller<camera_t, void(), Camera_RotateRight_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_Right ) );
999         GlobalCommands_insert( "CameraStrafeRight", ReferenceCaller<camera_t, void(), Camera_MoveRight_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_period ) );
1000         GlobalCommands_insert( "CameraStrafeLeft", ReferenceCaller<camera_t, void(), Camera_MoveLeft_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_comma ) );
1001
1002         GlobalCommands_insert( "CameraUp", ReferenceCaller<camera_t, void(), Camera_MoveUp_Discrete>( camwnd.getCamera() ), Accelerator( 'D' ) );
1003         GlobalCommands_insert( "CameraDown", ReferenceCaller<camera_t, void(), Camera_MoveDown_Discrete>( camwnd.getCamera() ), Accelerator( 'C' ) );
1004         GlobalCommands_insert( "CameraAngleUp", ReferenceCaller<camera_t, void(), Camera_PitchUp_Discrete>( camwnd.getCamera() ), Accelerator( 'A' ) );
1005         GlobalCommands_insert( "CameraAngleDown", ReferenceCaller<camera_t, void(), Camera_PitchDown_Discrete>( camwnd.getCamera() ), Accelerator( 'Z' ) );
1006 }
1007
1008 void CamWnd_Move_Enable( CamWnd& camwnd ){
1009         KeyEvent_connect( "CameraForward" );
1010         KeyEvent_connect( "CameraBack" );
1011         KeyEvent_connect( "CameraLeft" );
1012         KeyEvent_connect( "CameraRight" );
1013         KeyEvent_connect( "CameraStrafeRight" );
1014         KeyEvent_connect( "CameraStrafeLeft" );
1015         KeyEvent_connect( "CameraUp" );
1016         KeyEvent_connect( "CameraDown" );
1017         KeyEvent_connect( "CameraAngleUp" );
1018         KeyEvent_connect( "CameraAngleDown" );
1019 }
1020
1021 void CamWnd_Move_Disable( CamWnd& camwnd ){
1022         KeyEvent_disconnect( "CameraForward" );
1023         KeyEvent_disconnect( "CameraBack" );
1024         KeyEvent_disconnect( "CameraLeft" );
1025         KeyEvent_disconnect( "CameraRight" );
1026         KeyEvent_disconnect( "CameraStrafeRight" );
1027         KeyEvent_disconnect( "CameraStrafeLeft" );
1028         KeyEvent_disconnect( "CameraUp" );
1029         KeyEvent_disconnect( "CameraDown" );
1030         KeyEvent_disconnect( "CameraAngleUp" );
1031         KeyEvent_disconnect( "CameraAngleDown" );
1032 }
1033
1034 void CamWnd_Move_Discrete_Enable( CamWnd& camwnd ){
1035         command_connect_accelerator( "CameraForward" );
1036         command_connect_accelerator( "CameraBack" );
1037         command_connect_accelerator( "CameraLeft" );
1038         command_connect_accelerator( "CameraRight" );
1039         command_connect_accelerator( "CameraStrafeRight" );
1040         command_connect_accelerator( "CameraStrafeLeft" );
1041         command_connect_accelerator( "CameraUp" );
1042         command_connect_accelerator( "CameraDown" );
1043         command_connect_accelerator( "CameraAngleUp" );
1044         command_connect_accelerator( "CameraAngleDown" );
1045 }
1046
1047 void CamWnd_Move_Discrete_Disable( CamWnd& camwnd ){
1048         command_disconnect_accelerator( "CameraForward" );
1049         command_disconnect_accelerator( "CameraBack" );
1050         command_disconnect_accelerator( "CameraLeft" );
1051         command_disconnect_accelerator( "CameraRight" );
1052         command_disconnect_accelerator( "CameraStrafeRight" );
1053         command_disconnect_accelerator( "CameraStrafeLeft" );
1054         command_disconnect_accelerator( "CameraUp" );
1055         command_disconnect_accelerator( "CameraDown" );
1056         command_disconnect_accelerator( "CameraAngleUp" );
1057         command_disconnect_accelerator( "CameraAngleDown" );
1058 }
1059
1060 struct CamWnd_Move_Discrete {
1061         static void Export(const Callback<void(bool)> &returnz) {
1062                 returnz(g_camwindow_globals_private.m_bCamDiscrete);
1063         }
1064
1065         static void Import(bool value) {
1066                 if (g_camwnd) {
1067                         Import_(*g_camwnd, value);
1068                 } else {
1069                         g_camwindow_globals_private.m_bCamDiscrete = value;
1070                 }
1071         }
1072
1073         static void Import_(CamWnd &camwnd, bool value) {
1074         if ( g_camwindow_globals_private.m_bCamDiscrete ) {
1075                 CamWnd_Move_Discrete_Disable( camwnd );
1076                 } else {
1077                 CamWnd_Move_Disable( camwnd );
1078         }
1079
1080         g_camwindow_globals_private.m_bCamDiscrete = value;
1081
1082         if ( g_camwindow_globals_private.m_bCamDiscrete ) {
1083                 CamWnd_Move_Discrete_Enable( camwnd );
1084                 } else {
1085                 CamWnd_Move_Enable( camwnd );
1086         }
1087 }
1088 };
1089
1090
1091 void CamWnd_Add_Handlers_Move( CamWnd& camwnd ){
1092         camwnd.m_selection_button_press_handler = camwnd.m_gl_widget.connect( "button_press_event", G_CALLBACK( selection_button_press ), camwnd.m_window_observer );
1093         camwnd.m_selection_button_release_handler = camwnd.m_gl_widget.connect( "button_release_event", G_CALLBACK( selection_button_release ), camwnd.m_window_observer );
1094         camwnd.m_selection_motion_handler = camwnd.m_gl_widget.connect( "motion_notify_event", G_CALLBACK( DeferredMotion::gtk_motion ), &camwnd.m_deferred_motion );
1095
1096         camwnd.m_freelook_button_press_handler = camwnd.m_gl_widget.connect( "button_press_event", G_CALLBACK( enable_freelook_button_press ), &camwnd );
1097
1098         if ( g_camwindow_globals_private.m_bCamDiscrete ) {
1099                 CamWnd_Move_Discrete_Enable( camwnd );
1100         }
1101         else
1102         {
1103                 CamWnd_Move_Enable( camwnd );
1104         }
1105 }
1106
1107 void CamWnd_Remove_Handlers_Move( CamWnd& camwnd ){
1108         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_button_press_handler );
1109         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_button_release_handler );
1110         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_motion_handler );
1111
1112         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_freelook_button_press_handler );
1113
1114         if ( g_camwindow_globals_private.m_bCamDiscrete ) {
1115                 CamWnd_Move_Discrete_Disable( camwnd );
1116         }
1117         else
1118         {
1119                 CamWnd_Move_Disable( camwnd );
1120         }
1121 }
1122
1123 void CamWnd_Add_Handlers_FreeMove( CamWnd& camwnd ){
1124         camwnd.m_selection_button_press_handler = camwnd.m_gl_widget.connect( "button_press_event", G_CALLBACK( selection_button_press_freemove ), camwnd.m_window_observer );
1125         camwnd.m_selection_button_release_handler = camwnd.m_gl_widget.connect( "button_release_event", G_CALLBACK( selection_button_release_freemove ), camwnd.m_window_observer );
1126         camwnd.m_selection_motion_handler = camwnd.m_gl_widget.connect( "motion_notify_event", G_CALLBACK( selection_motion_freemove ), camwnd.m_window_observer );
1127
1128         camwnd.m_freelook_button_press_handler = camwnd.m_gl_widget.connect( "button_press_event", G_CALLBACK( disable_freelook_button_press ), &camwnd );
1129
1130         KeyEvent_connect( "CameraFreeMoveForward" );
1131         KeyEvent_connect( "CameraFreeMoveBack" );
1132         KeyEvent_connect( "CameraFreeMoveLeft" );
1133         KeyEvent_connect( "CameraFreeMoveRight" );
1134
1135         KeyEvent_connect( "CameraFreeMoveForward2" );
1136         KeyEvent_connect( "CameraFreeMoveBack2" );
1137         KeyEvent_connect( "CameraFreeMoveLeft2" );
1138         KeyEvent_connect( "CameraFreeMoveRight2" );
1139
1140         KeyEvent_connect( "CameraFreeMoveUp" );
1141         KeyEvent_connect( "CameraFreeMoveDown" );
1142 }
1143
1144 void CamWnd_Remove_Handlers_FreeMove( CamWnd& camwnd ){
1145         KeyEvent_disconnect( "CameraFreeMoveForward" );
1146         KeyEvent_disconnect( "CameraFreeMoveBack" );
1147         KeyEvent_disconnect( "CameraFreeMoveLeft" );
1148         KeyEvent_disconnect( "CameraFreeMoveRight" );
1149
1150         KeyEvent_disconnect( "CameraFreeMoveForward2" );
1151         KeyEvent_disconnect( "CameraFreeMoveBack2" );
1152         KeyEvent_disconnect( "CameraFreeMoveLeft2" );
1153         KeyEvent_disconnect( "CameraFreeMoveRight2" );
1154
1155         KeyEvent_disconnect( "CameraFreeMoveUp" );
1156         KeyEvent_disconnect( "CameraFreeMoveDown" );
1157
1158         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_button_press_handler );
1159         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_button_release_handler );
1160         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_motion_handler );
1161
1162         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_freelook_button_press_handler );
1163 }
1164
1165 CamWnd::CamWnd() :
1166         m_view( true ),
1167         m_Camera( &m_view, CamWndQueueDraw( *this ) ),
1168         m_cameraview( m_Camera, &m_view, ReferenceCaller<CamWnd, void(), CamWnd_Update>( *this ) ),
1169         m_gl_widget( glwidget_new( TRUE ) ),
1170         m_window_observer( NewWindowObserver() ),
1171         m_XORRectangle( m_gl_widget ),
1172         m_deferredDraw( WidgetQueueDrawCaller( m_gl_widget ) ),
1173         m_deferred_motion( selection_motion, m_window_observer ),
1174         m_selection_button_press_handler( 0 ),
1175         m_selection_button_release_handler( 0 ),
1176         m_selection_motion_handler( 0 ),
1177         m_freelook_button_press_handler( 0 ),
1178         m_drawing( false ){
1179         m_bFreeMove = false;
1180
1181         GlobalWindowObservers_add( m_window_observer );
1182         GlobalWindowObservers_connectWidget( m_gl_widget );
1183
1184         m_window_observer->setRectangleDrawCallback( ReferenceCaller<CamWnd, void(rect_t), camwnd_update_xor_rectangle>( *this ) );
1185         m_window_observer->setView( m_view );
1186
1187         g_object_ref( m_gl_widget._handle );
1188
1189         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 );
1190         gtk_widget_set_can_focus( m_gl_widget, true );
1191
1192         m_sizeHandler = m_gl_widget.connect( "size_allocate", G_CALLBACK( camera_size_allocate ), this );
1193         m_exposeHandler = m_gl_widget.on_render( G_CALLBACK( camera_expose ), this );
1194
1195         Map_addValidCallback( g_map, DeferredDrawOnMapValidChangedCaller( m_deferredDraw ) );
1196
1197         CamWnd_registerCommands( *this );
1198
1199         CamWnd_Add_Handlers_Move( *this );
1200
1201         m_gl_widget.connect( "scroll_event", G_CALLBACK( wheelmove_scroll ), this );
1202
1203         AddSceneChangeCallback( ReferenceCaller<CamWnd, void(), CamWnd_Update>( *this ) );
1204
1205         PressedButtons_connect( g_pressedButtons, m_gl_widget );
1206 }
1207
1208 CamWnd::~CamWnd(){
1209         if ( m_bFreeMove ) {
1210                 DisableFreeMove();
1211         }
1212
1213         CamWnd_Remove_Handlers_Move( *this );
1214
1215         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_sizeHandler );
1216         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_exposeHandler );
1217
1218         m_gl_widget.unref();
1219
1220         m_window_observer->release();
1221 }
1222
1223 class FloorHeightWalker : public scene::Graph::Walker
1224 {
1225 float m_current;
1226 float& m_bestUp;
1227 float& m_bestDown;
1228 public:
1229 FloorHeightWalker( float current, float& bestUp, float& bestDown ) :
1230         m_current( current ), m_bestUp( bestUp ), m_bestDown( bestDown ){
1231         bestUp = g_MaxWorldCoord;
1232         bestDown = -g_MaxWorldCoord;
1233 }
1234 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1235         if ( path.top().get().visible()
1236                  && Node_isBrush( path.top() ) ) { // this node is a floor
1237                 const AABB& aabb = instance.worldAABB();
1238                 float floorHeight = aabb.origin.z() + aabb.extents.z();
1239                 if ( floorHeight > m_current && floorHeight < m_bestUp ) {
1240                         m_bestUp = floorHeight;
1241                 }
1242                 if ( floorHeight < m_current && floorHeight > m_bestDown ) {
1243                         m_bestDown = floorHeight;
1244                 }
1245         }
1246         else if( !path.top().get().visible() ){
1247                 return false;
1248         }
1249         return true;
1250 }
1251 };
1252
1253 void CamWnd::Cam_ChangeFloor( bool up ){
1254         float current = m_Camera.origin[2] - 48;
1255         float bestUp;
1256         float bestDown;
1257         GlobalSceneGraph().traverse( FloorHeightWalker( current, bestUp, bestDown ) );
1258
1259         if ( up && bestUp != g_MaxWorldCoord ) {
1260                 current = bestUp;
1261         }
1262         if ( !up && bestDown != -g_MaxWorldCoord ) {
1263                 current = bestDown;
1264         }
1265
1266         m_Camera.origin[2] = current + 48;
1267         Camera_updateModelview( getCamera() );
1268         CamWnd_Update( *this );
1269         CameraMovedNotify();
1270 }
1271
1272
1273 #if 0
1274
1275 // button_press
1276 Sys_GetCursorPos( &m_PositionDragCursorX, &m_PositionDragCursorY );
1277
1278 // motion
1279 if ( ( m_bFreeMove && ( buttons == ( RAD_CONTROL | RAD_SHIFT ) ) )
1280          || ( !m_bFreeMove && ( buttons == ( RAD_RBUTTON | RAD_CONTROL ) ) ) ) {
1281         Cam_PositionDrag();
1282         CamWnd_Update( camwnd );
1283         CameraMovedNotify();
1284         return;
1285 }
1286
1287 void CamWnd::Cam_PositionDrag(){
1288         int x, y;
1289
1290         Sys_GetCursorPos( m_gl_widget, &x, &y );
1291         if ( x != m_PositionDragCursorX || y != m_PositionDragCursorY ) {
1292                 x -= m_PositionDragCursorX;
1293                 vector3_add( m_Camera.origin, vector3_scaled( m_Camera.vright, x ) );
1294                 y -= m_PositionDragCursorY;
1295                 m_Camera.origin[2] -= y;
1296                 Camera_updateModelview();
1297                 CamWnd_Update( camwnd );
1298                 CameraMovedNotify();
1299
1300                 Sys_SetCursorPos( m_parent, m_PositionDragCursorX, m_PositionDragCursorY );
1301         }
1302 }
1303 #endif
1304
1305
1306 // NOTE TTimo if there's an OS-level focus out of the application
1307 //   then we can release the camera cursor grab
1308 static gboolean camwindow_freemove_focusout( ui::Widget widget, GdkEventFocus* event, gpointer data ){
1309         reinterpret_cast<CamWnd*>( data )->DisableFreeMove();
1310         return FALSE;
1311 }
1312
1313 void CamWnd::EnableFreeMove(){
1314         //globalOutputStream() << "EnableFreeMove\n";
1315
1316         ASSERT_MESSAGE( !m_bFreeMove, "EnableFreeMove: free-move was already enabled" );
1317         m_bFreeMove = true;
1318         Camera_clearMovementFlags( getCamera(), MOVE_ALL );
1319
1320         CamWnd_Remove_Handlers_Move( *this );
1321         CamWnd_Add_Handlers_FreeMove( *this );
1322
1323         gtk_window_set_focus( m_parent, m_gl_widget );
1324         m_freemove_handle_focusout = m_gl_widget.connect( "focus_out_event", G_CALLBACK( camwindow_freemove_focusout ), this );
1325         m_freezePointer.freeze_pointer( m_parent, m_gl_widget, Camera_motionDelta, &m_Camera );
1326
1327         CamWnd_Update( *this );
1328 }
1329
1330 void CamWnd::DisableFreeMove(){
1331         //globalOutputStream() << "DisableFreeMove\n";
1332
1333         ASSERT_MESSAGE( m_bFreeMove, "DisableFreeMove: free-move was not enabled" );
1334         m_bFreeMove = false;
1335         Camera_clearMovementFlags( getCamera(), MOVE_ALL );
1336
1337         CamWnd_Remove_Handlers_FreeMove( *this );
1338         CamWnd_Add_Handlers_Move( *this );
1339
1340         m_freezePointer.unfreeze_pointer( m_parent, true );
1341         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_freemove_handle_focusout );
1342
1343         CamWnd_Update( *this );
1344 }
1345
1346
1347 #include "renderer.h"
1348
1349 class CamRenderer : public Renderer
1350 {
1351 struct state_type
1352 {
1353         state_type() : m_highlight( 0 ), m_state( 0 ), m_lights( 0 ){
1354         }
1355         unsigned int m_highlight;
1356         Shader* m_state;
1357         const LightList* m_lights;
1358 };
1359
1360 std::vector<state_type> m_state_stack;
1361 RenderStateFlags m_globalstate;
1362 Shader* m_state_select0;
1363 Shader* m_state_select1;
1364 const Vector3& m_viewer;
1365
1366 public:
1367 CamRenderer( RenderStateFlags globalstate, Shader* select0, Shader* select1, const Vector3& viewer ) :
1368         m_globalstate( globalstate ),
1369         m_state_select0( select0 ),
1370         m_state_select1( select1 ),
1371         m_viewer( viewer ){
1372         ASSERT_NOTNULL( select0 );
1373         ASSERT_NOTNULL( select1 );
1374         m_state_stack.push_back( state_type() );
1375 }
1376
1377 void SetState( Shader* state, EStyle style ){
1378         ASSERT_NOTNULL( state );
1379         if ( style == eFullMaterials ) {
1380                 m_state_stack.back().m_state = state;
1381         }
1382 }
1383 EStyle getStyle() const {
1384         return eFullMaterials;
1385 }
1386 void PushState(){
1387         m_state_stack.push_back( m_state_stack.back() );
1388 }
1389 void PopState(){
1390         ASSERT_MESSAGE( !m_state_stack.empty(), "popping empty stack" );
1391         m_state_stack.pop_back();
1392 }
1393 void Highlight( EHighlightMode mode, bool bEnable = true ){
1394         ( bEnable )
1395         ? m_state_stack.back().m_highlight |= mode
1396                                                                                   : m_state_stack.back().m_highlight &= ~mode;
1397 }
1398 void setLights( const LightList& lights ){
1399         m_state_stack.back().m_lights = &lights;
1400 }
1401 void addRenderable( const OpenGLRenderable& renderable, const Matrix4& world ){
1402         if ( m_state_stack.back().m_highlight & ePrimitive ) {
1403                 m_state_select0->addRenderable( renderable, world, m_state_stack.back().m_lights );
1404         }
1405         if ( m_state_stack.back().m_highlight & eFace ) {
1406                 m_state_select1->addRenderable( renderable, world, m_state_stack.back().m_lights );
1407         }
1408
1409         m_state_stack.back().m_state->addRenderable( renderable, world, m_state_stack.back().m_lights );
1410 }
1411
1412 void render( const Matrix4& modelview, const Matrix4& projection ){
1413         GlobalShaderCache().render( m_globalstate, modelview, projection, m_viewer );
1414 }
1415 };
1416
1417 /*
1418    ==============
1419    Cam_Draw
1420    ==============
1421  */
1422 /*
1423 void ShowStatsToggle(){
1424         g_camwindow_globals_private.m_showStats ^= 1;
1425 }
1426
1427 void ShowStatsExport( const Callback<void(bool)> &importer ){
1428         importer( g_camwindow_globals_private.m_showStats );
1429 }
1430
1431 FreeCaller<void(const Callback<void(bool)>&), ShowStatsExport> g_show_stats_caller;
1432 Callback<void(const Callback<void(bool)> &)> g_show_stats_callback( g_show_stats_caller );
1433 ToggleItem g_show_stats( g_show_stats_callback );
1434 */
1435 BoolExportCaller g_show_stats_caller( g_camwindow_globals_private.m_showStats );
1436 ToggleItem g_show_stats( g_show_stats_caller );
1437 void ShowStatsToggle(){
1438         g_camwindow_globals_private.m_showStats ^= 1;
1439         g_show_stats.update();
1440         UpdateAllWindows();
1441 }
1442
1443 void CamWnd::Cam_Draw(){
1444         glViewport( 0, 0, m_Camera.width, m_Camera.height );
1445 #if 0
1446         GLint viewprt[4];
1447         glGetIntegerv( GL_VIEWPORT, viewprt );
1448 #endif
1449
1450         // enable depth buffer writes
1451         glDepthMask( GL_TRUE );
1452         glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
1453
1454         Vector3 clearColour( 0, 0, 0 );
1455         if ( m_Camera.draw_mode != cd_lighting ) {
1456                 clearColour = g_camwindow_globals.color_cameraback;
1457         }
1458
1459         glClearColor( clearColour[0], clearColour[1], clearColour[2], 0 );
1460         glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
1461
1462         extern void Renderer_ResetStats();
1463         Renderer_ResetStats();
1464         extern void Cull_ResetStats();
1465         Cull_ResetStats();
1466
1467         glMatrixMode( GL_PROJECTION );
1468         glLoadMatrixf( reinterpret_cast<const float*>( &m_Camera.projection ) );
1469
1470         glMatrixMode( GL_MODELVIEW );
1471         glLoadMatrixf( reinterpret_cast<const float*>( &m_Camera.modelview ) );
1472
1473
1474         // one directional light source directly behind the viewer
1475         {
1476                 GLfloat inverse_cam_dir[4], ambient[4], diffuse[4]; //, material[4];
1477
1478                 ambient[0] = ambient[1] = ambient[2] = 0.4f;
1479                 ambient[3] = 1.0f;
1480                 diffuse[0] = diffuse[1] = diffuse[2] = 0.4f;
1481                 diffuse[3] = 1.0f;
1482                 //material[0] = material[1] = material[2] = 0.8f;
1483                 //material[3] = 1.0f;
1484
1485                 inverse_cam_dir[0] = m_Camera.vpn[0];
1486                 inverse_cam_dir[1] = m_Camera.vpn[1];
1487                 inverse_cam_dir[2] = m_Camera.vpn[2];
1488                 inverse_cam_dir[3] = 0;
1489
1490                 glLightfv( GL_LIGHT0, GL_POSITION, inverse_cam_dir );
1491
1492                 glLightfv( GL_LIGHT0, GL_AMBIENT, ambient );
1493                 glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuse );
1494
1495                 glEnable( GL_LIGHT0 );
1496         }
1497
1498
1499         unsigned int globalstate = RENDER_DEPTHTEST | RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_ALPHATEST | RENDER_BLEND | RENDER_CULLFACE | RENDER_COLOURARRAY | RENDER_OFFSETLINE | RENDER_POLYGONSMOOTH | RENDER_LINESMOOTH | RENDER_FOG | RENDER_COLOURCHANGE;
1500         switch ( m_Camera.draw_mode )
1501         {
1502         case cd_wire:
1503                 break;
1504         case cd_solid:
1505                 globalstate |= RENDER_FILL
1506                                            | RENDER_LIGHTING
1507                                            | RENDER_SMOOTH
1508                                            | RENDER_SCALED;
1509                 break;
1510         case cd_texture:
1511                 globalstate |= RENDER_FILL
1512                                            | RENDER_LIGHTING
1513                                            | RENDER_TEXTURE
1514                                            | RENDER_SMOOTH
1515                                            | RENDER_SCALED;
1516                 break;
1517         case cd_lighting:
1518                 globalstate |= RENDER_FILL
1519                                            | RENDER_LIGHTING
1520                                            | RENDER_TEXTURE
1521                                            | RENDER_SMOOTH
1522                                            | RENDER_SCALED
1523                                            | RENDER_BUMP
1524                                            | RENDER_PROGRAM
1525                                            | RENDER_SCREEN;
1526                 break;
1527         default:
1528                 globalstate = 0;
1529                 break;
1530         }
1531
1532 //      if ( !g_xywindow_globals.m_bNoStipple ) {
1533                 globalstate |= RENDER_LINESTIPPLE | RENDER_POLYGONSTIPPLE;
1534 //      }
1535
1536         {
1537                 CamRenderer renderer( globalstate, m_state_select2, m_state_select1, m_view.getViewer() );
1538
1539                 Scene_Render( renderer, m_view );
1540
1541                 renderer.render( m_Camera.modelview, m_Camera.projection );
1542         }
1543
1544         // prepare for 2d stuff
1545         glColor4f( 1, 1, 1, 1 );
1546         glDisable( GL_BLEND );
1547         glMatrixMode( GL_PROJECTION );
1548         glLoadIdentity();
1549         glOrtho( 0, (float)m_Camera.width, 0, (float)m_Camera.height, -100, 100 );
1550         glScalef( 1, -1, 1 );
1551         glTranslatef( 0, -(float)m_Camera.height, 0 );
1552         glMatrixMode( GL_MODELVIEW );
1553         glLoadIdentity();
1554
1555         if ( GlobalOpenGL().GL_1_3() ) {
1556                 glClientActiveTexture( GL_TEXTURE0 );
1557                 glActiveTexture( GL_TEXTURE0 );
1558         }
1559
1560         glDisableClientState( GL_TEXTURE_COORD_ARRAY );
1561         glDisableClientState( GL_NORMAL_ARRAY );
1562         glDisableClientState( GL_COLOR_ARRAY );
1563
1564         glDisable( GL_TEXTURE_2D );
1565         glDisable( GL_LIGHTING );
1566         glDisable( GL_COLOR_MATERIAL );
1567         glDisable( GL_DEPTH_TEST );
1568         glColor3f( 1.f, 1.f, 1.f );
1569         glLineWidth( 1 );
1570
1571         // draw the crosshair
1572         if ( m_bFreeMove ) {
1573                 glBegin( GL_LINES );
1574                 glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f + 6 );
1575                 glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f + 2 );
1576                 glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f - 6 );
1577                 glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f - 2 );
1578                 glVertex2f( (float)m_Camera.width / 2.f + 6, (float)m_Camera.height / 2.f );
1579                 glVertex2f( (float)m_Camera.width / 2.f + 2, (float)m_Camera.height / 2.f );
1580                 glVertex2f( (float)m_Camera.width / 2.f - 6, (float)m_Camera.height / 2.f );
1581                 glVertex2f( (float)m_Camera.width / 2.f - 2, (float)m_Camera.height / 2.f );
1582                 glEnd();
1583         }
1584
1585         if ( g_camwindow_globals_private.m_showStats ) {
1586                 glRasterPos3f( 1.0f, static_cast<float>( m_Camera.height ) - GlobalOpenGL().m_font->getPixelDescent(), 0.0f );
1587                 extern const char* Renderer_GetStats();
1588                 GlobalOpenGL().drawString( Renderer_GetStats() );
1589
1590                 glRasterPos3f( 1.0f, static_cast<float>( m_Camera.height ) - GlobalOpenGL().m_font->getPixelDescent() - GlobalOpenGL().m_font->getPixelHeight(), 0.0f );
1591                 extern const char* Cull_GetStats();
1592                 GlobalOpenGL().drawString( Cull_GetStats() );
1593         }
1594
1595         // bind back to the default texture so that we don't have problems
1596         // elsewhere using/modifying texture maps between contexts
1597         glBindTexture( GL_TEXTURE_2D, 0 );
1598 }
1599
1600 void CamWnd::draw(){
1601         m_drawing = true;
1602
1603         //globalOutputStream() << "draw...\n";
1604         if ( glwidget_make_current( m_gl_widget ) != FALSE ) {
1605                 if ( Map_Valid( g_map ) && ScreenUpdates_Enabled() ) {
1606                         GlobalOpenGL_debugAssertNoErrors();
1607                         Cam_Draw();
1608                         GlobalOpenGL_debugAssertNoErrors();
1609                         //qglFinish();
1610
1611                         m_XORRectangle.set( rectangle_t() );
1612                 }
1613
1614                 glwidget_swap_buffers( m_gl_widget );
1615         }
1616
1617         m_drawing = false;
1618 }
1619
1620 void CamWnd::BenchMark(){
1621         double dStart = Sys_DoubleTime();
1622         for ( int i = 0 ; i < 100 ; i++ )
1623         {
1624                 Vector3 angles;
1625                 angles[CAMERA_ROLL] = 0;
1626                 angles[CAMERA_PITCH] = 0;
1627                 angles[CAMERA_YAW] = static_cast<float>( i * ( 360.0 / 100.0 ) );
1628                 Camera_setAngles( *this, angles );
1629         }
1630         double dEnd = Sys_DoubleTime();
1631         globalOutputStream() << FloatFormat( dEnd - dStart, 5, 2 ) << " seconds\n";
1632 }
1633
1634
1635 void fill_view_camera_menu( ui::Menu menu ){
1636         create_check_menu_item_with_mnemonic( menu, "Camera View", "ToggleCamera" );
1637 }
1638
1639 void GlobalCamera_ResetAngles(){
1640         CamWnd& camwnd = *g_camwnd;
1641         Vector3 angles;
1642         angles[CAMERA_ROLL] = angles[CAMERA_PITCH] = 0;
1643         angles[CAMERA_YAW] = static_cast<float>( 22.5 * floor( ( Camera_getAngles( camwnd )[CAMERA_YAW] + 11 ) / 22.5 ) );
1644         Camera_setAngles( camwnd, angles );
1645 }
1646
1647 void Camera_ChangeFloorUp(){
1648         CamWnd& camwnd = *g_camwnd;
1649         camwnd.Cam_ChangeFloor( true );
1650 }
1651
1652 void Camera_ChangeFloorDown(){
1653         CamWnd& camwnd = *g_camwnd;
1654         camwnd.Cam_ChangeFloor( false );
1655 }
1656
1657 void Camera_CubeIn(){
1658         CamWnd& camwnd = *g_camwnd;
1659         g_camwindow_globals.m_nCubicScale--;
1660         if ( g_camwindow_globals.m_nCubicScale < 1 ) {
1661                 g_camwindow_globals.m_nCubicScale = 1;
1662         }
1663         Camera_updateProjection( camwnd.getCamera() );
1664         CamWnd_Update( camwnd );
1665         g_pParentWnd->SetGridStatus();
1666 }
1667
1668 void Camera_CubeOut(){
1669         CamWnd& camwnd = *g_camwnd;
1670         g_camwindow_globals.m_nCubicScale++;
1671         if ( g_camwindow_globals.m_nCubicScale > 23 ) {
1672                 g_camwindow_globals.m_nCubicScale = 23;
1673         }
1674         Camera_updateProjection( camwnd.getCamera() );
1675         CamWnd_Update( camwnd );
1676         g_pParentWnd->SetGridStatus();
1677 }
1678
1679 bool Camera_GetFarClip(){
1680         return g_camwindow_globals_private.m_bCubicClipping;
1681 }
1682
1683 ConstReferenceCaller<bool, void(const Callback<void(bool)> &), PropertyImpl<bool>::Export> g_getfarclip_caller( g_camwindow_globals_private.m_bCubicClipping );
1684 ToggleItem g_getfarclip_item( g_getfarclip_caller );
1685
1686 void Camera_SetFarClip( bool value ){
1687         CamWnd& camwnd = *g_camwnd;
1688         g_camwindow_globals_private.m_bCubicClipping = value;
1689         g_getfarclip_item.update();
1690         Camera_updateProjection( camwnd.getCamera() );
1691         CamWnd_Update( camwnd );
1692 }
1693
1694 struct Camera_FarClip {
1695         static void Export(const Callback<void(bool)> &returnz) {
1696                 returnz(g_camwindow_globals_private.m_bCubicClipping);
1697         }
1698
1699         static void Import(bool value) {
1700                 Camera_SetFarClip(value);
1701         }
1702 };
1703
1704 void Camera_ToggleFarClip(){
1705         Camera_SetFarClip( !Camera_GetFarClip() );
1706 }
1707
1708
1709 void CamWnd_constructToolbar( ui::Toolbar toolbar ){
1710         toolbar_append_toggle_button( toolbar, "Cubic clip the camera view (Ctrl + \\)", "view_cubicclipping.png", "ToggleCubicClip" );
1711 }
1712
1713 void CamWnd_registerShortcuts(){
1714         toggle_add_accelerator( "ToggleCubicClip" );
1715
1716         if ( g_pGameDescription->mGameType == "doom3" ) {
1717                 command_connect_accelerator( "TogglePreview" );
1718         }
1719
1720         command_connect_accelerator( "CameraSpeedInc" );
1721         command_connect_accelerator( "CameraSpeedDec" );
1722 }
1723
1724
1725 void GlobalCamera_Benchmark(){
1726         CamWnd& camwnd = *g_camwnd;
1727         camwnd.BenchMark();
1728 }
1729
1730 void GlobalCamera_Update(){
1731         CamWnd& camwnd = *g_camwnd;
1732         CamWnd_Update( camwnd );
1733 }
1734
1735 camera_draw_mode CamWnd_GetMode(){
1736         return camera_t::draw_mode;
1737 }
1738 void CamWnd_SetMode( camera_draw_mode mode ){
1739         ShaderCache_setBumpEnabled( mode == cd_lighting );
1740         camera_t::draw_mode = mode;
1741         if ( g_camwnd != 0 ) {
1742                 CamWnd_Update( *g_camwnd );
1743         }
1744 }
1745
1746 void CamWnd_TogglePreview( void ){
1747         // gametype must be doom3 for this function to work
1748         // if the gametype is not doom3 something is wrong with the
1749         // global command list or somebody else calls this function.
1750         ASSERT_MESSAGE( g_pGameDescription->mGameType == "doom3", "CamWnd_TogglePreview called although mGameType is not doom3 compatible" );
1751
1752         // switch between textured and lighting mode
1753         CamWnd_SetMode( ( CamWnd_GetMode() == cd_lighting ) ? cd_texture : cd_lighting );
1754 }
1755
1756
1757 CameraModel* g_camera_model = 0;
1758
1759 void CamWnd_LookThroughCamera( CamWnd& camwnd ){
1760         if ( g_camera_model != 0 ) {
1761                 CamWnd_Add_Handlers_Move( camwnd );
1762                 g_camera_model->setCameraView( 0, Callback<void()>() );
1763                 g_camera_model = 0;
1764                 Camera_updateModelview( camwnd.getCamera() );
1765                 Camera_updateProjection( camwnd.getCamera() );
1766                 CamWnd_Update( camwnd );
1767         }
1768 }
1769
1770 inline CameraModel* Instance_getCameraModel( scene::Instance& instance ){
1771         return InstanceTypeCast<CameraModel>::cast( instance );
1772 }
1773
1774 void CamWnd_LookThroughSelected( CamWnd& camwnd ){
1775         if ( g_camera_model != 0 ) {
1776                 CamWnd_LookThroughCamera( camwnd );
1777         }
1778
1779         if ( GlobalSelectionSystem().countSelected() != 0 ) {
1780                 scene::Instance& instance = GlobalSelectionSystem().ultimateSelected();
1781                 CameraModel* cameraModel = Instance_getCameraModel( instance );
1782                 if ( cameraModel != 0 ) {
1783                         CamWnd_Remove_Handlers_Move( camwnd );
1784                         g_camera_model = cameraModel;
1785                         g_camera_model->setCameraView( &camwnd.getCameraView(), ReferenceCaller<CamWnd, void(), CamWnd_LookThroughCamera>( camwnd ) );
1786                 }
1787         }
1788 }
1789
1790 void GlobalCamera_LookThroughSelected(){
1791         CamWnd_LookThroughSelected( *g_camwnd );
1792 }
1793
1794 void GlobalCamera_LookThroughCamera(){
1795         CamWnd_LookThroughCamera( *g_camwnd );
1796 }
1797
1798 struct RenderMode {
1799         static void Export(const Callback<void(int)> &returnz) {
1800                 switch (CamWnd_GetMode()) {
1801                         case cd_wire:
1802                                 returnz(0);
1803                                 break;
1804                         case cd_solid:
1805                                 returnz(1);
1806                                 break;
1807                         case cd_texture:
1808                                 returnz(2);
1809                                 break;
1810                         case cd_lighting:
1811                                 returnz(3);
1812                                 break;
1813                 }
1814         }
1815
1816         static void Import(int value) {
1817                 switch (value) {
1818         case 0:
1819                 CamWnd_SetMode( cd_wire );
1820                 break;
1821         case 1:
1822                 CamWnd_SetMode( cd_solid );
1823                 break;
1824         case 2:
1825                 CamWnd_SetMode( cd_texture );
1826                 break;
1827         case 3:
1828                 CamWnd_SetMode( cd_lighting );
1829                 break;
1830         default:
1831                 CamWnd_SetMode( cd_texture );
1832         }
1833 }
1834 };
1835
1836 void Camera_constructPreferences( PreferencesPage& page ){
1837         page.appendSlider( "Movement Speed", g_camwindow_globals_private.m_nMoveSpeed, TRUE, 0, 0, 100, MIN_CAM_SPEED, MAX_CAM_SPEED, 1, 10 );
1838         page.appendCheckBox( "", "Link strafe speed to movement speed", g_camwindow_globals_private.m_bCamLinkSpeed );
1839         page.appendSlider( "Rotation Speed", g_camwindow_globals_private.m_nAngleSpeed, TRUE, 0, 0, 3, 1, 180, 1, 10 );
1840         page.appendCheckBox( "", "Invert mouse vertical axis", g_camwindow_globals_private.m_bCamInverseMouse );
1841         page.appendCheckBox(
1842                 "", "Discrete movement",
1843                 make_property<CamWnd_Move_Discrete>()
1844                 );
1845         page.appendCheckBox(
1846                 "", "Enable far-clip plane",
1847                 make_property<Camera_FarClip>()
1848                 );
1849
1850         if ( g_pGameDescription->mGameType == "doom3" ) {
1851                 const char* render_mode[] = { "Wireframe", "Flatshade", "Textured", "Lighting" };
1852
1853                 page.appendCombo(
1854                         "Render Mode",
1855                         STRING_ARRAY_RANGE( render_mode ),
1856                         make_property<RenderMode>()
1857                         );
1858         }
1859         else
1860         {
1861                 const char* render_mode[] = { "Wireframe", "Flatshade", "Textured" };
1862
1863                 page.appendCombo(
1864                         "Render Mode",
1865                         STRING_ARRAY_RANGE( render_mode ),
1866                         make_property<RenderMode>()
1867                         );
1868         }
1869
1870         const char* strafe_mode[] = { "Both", "Forward", "Up" };
1871
1872         page.appendCombo(
1873                 "Strafe Mode",
1874                 g_camwindow_globals_private.m_nStrafeMode,
1875                 STRING_ARRAY_RANGE( strafe_mode )
1876                 );
1877 }
1878 void Camera_constructPage( PreferenceGroup& group ){
1879         PreferencesPage page( group.createPage( "Camera", "Camera View Preferences" ) );
1880         Camera_constructPreferences( page );
1881 }
1882 void Camera_registerPreferencesPage(){
1883         PreferencesDialog_addSettingsPage( makeCallbackF(Camera_constructPage) );
1884 }
1885
1886 #include "preferencesystem.h"
1887 #include "stringio.h"
1888 #include "dialog.h"
1889
1890 void CameraSpeed_increase(){
1891         if ( g_camwindow_globals_private.m_nMoveSpeed <= ( MAX_CAM_SPEED - CAM_SPEED_STEP - 10 ) ) {
1892                 g_camwindow_globals_private.m_nMoveSpeed += CAM_SPEED_STEP;
1893         }
1894         else {
1895                 g_camwindow_globals_private.m_nMoveSpeed = MAX_CAM_SPEED - 10;
1896         }
1897 }
1898
1899 void CameraSpeed_decrease(){
1900         if ( g_camwindow_globals_private.m_nMoveSpeed >= ( MIN_CAM_SPEED + CAM_SPEED_STEP ) ) {
1901                 g_camwindow_globals_private.m_nMoveSpeed -= CAM_SPEED_STEP;
1902         }
1903         else {
1904                 g_camwindow_globals_private.m_nMoveSpeed = MIN_CAM_SPEED;
1905         }
1906 }
1907
1908 /// \brief Initialisation for things that have the same lifespan as this module.
1909 void CamWnd_Construct(){
1910         GlobalCommands_insert( "CenterView", makeCallbackF(GlobalCamera_ResetAngles), Accelerator( GDK_KEY_End ) );
1911
1912         GlobalToggles_insert( "ToggleCubicClip", makeCallbackF(Camera_ToggleFarClip), ToggleItem::AddCallbackCaller( g_getfarclip_item ), Accelerator( '\\', (GdkModifierType)GDK_CONTROL_MASK ) );
1913         GlobalCommands_insert( "CubicClipZoomIn", makeCallbackF(Camera_CubeIn), Accelerator( '[', (GdkModifierType)GDK_CONTROL_MASK ) );
1914         GlobalCommands_insert( "CubicClipZoomOut", makeCallbackF(Camera_CubeOut), Accelerator( ']', (GdkModifierType)GDK_CONTROL_MASK ) );
1915
1916         GlobalCommands_insert( "UpFloor", makeCallbackF(Camera_ChangeFloorUp), Accelerator( GDK_KEY_Prior ) );
1917         GlobalCommands_insert( "DownFloor", makeCallbackF(Camera_ChangeFloorDown), Accelerator( GDK_KEY_Next ) );
1918
1919         GlobalToggles_insert( "ToggleCamera", ToggleShown::ToggleCaller( g_camera_shown ), ToggleItem::AddCallbackCaller( g_camera_shown.m_item ), Accelerator( 'C', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
1920         GlobalCommands_insert( "LookThroughSelected", makeCallbackF(GlobalCamera_LookThroughSelected) );
1921         GlobalCommands_insert( "LookThroughCamera", makeCallbackF(GlobalCamera_LookThroughCamera) );
1922
1923         if ( g_pGameDescription->mGameType == "doom3" ) {
1924                 GlobalCommands_insert( "TogglePreview", makeCallbackF(CamWnd_TogglePreview), Accelerator( GDK_KEY_F3 ) );
1925         }
1926
1927         GlobalCommands_insert( "CameraSpeedInc", makeCallbackF(CameraSpeed_increase), Accelerator( GDK_KEY_KP_Add, (GdkModifierType)GDK_SHIFT_MASK ) );
1928         GlobalCommands_insert( "CameraSpeedDec", makeCallbackF(CameraSpeed_decrease), Accelerator( GDK_KEY_KP_Subtract, (GdkModifierType)GDK_SHIFT_MASK ) );
1929
1930         GlobalShortcuts_insert( "CameraForward", Accelerator( GDK_KEY_Up ) );
1931         GlobalShortcuts_insert( "CameraBack", Accelerator( GDK_KEY_Down ) );
1932         GlobalShortcuts_insert( "CameraLeft", Accelerator( GDK_KEY_Left ) );
1933         GlobalShortcuts_insert( "CameraRight", Accelerator( GDK_KEY_Right ) );
1934         GlobalShortcuts_insert( "CameraStrafeRight", Accelerator( GDK_KEY_period ) );
1935         GlobalShortcuts_insert( "CameraStrafeLeft", Accelerator( GDK_KEY_comma ) );
1936
1937         GlobalShortcuts_insert( "CameraUp", accelerator_null() );
1938         GlobalShortcuts_insert( "CameraDown", accelerator_null() );
1939         GlobalShortcuts_insert( "CameraAngleUp", accelerator_null() );
1940         GlobalShortcuts_insert( "CameraAngleDown", accelerator_null() );
1941
1942         GlobalShortcuts_insert( "CameraFreeMoveForward", Accelerator( GDK_Up ) );
1943         GlobalShortcuts_insert( "CameraFreeMoveBack", Accelerator( GDK_Down ) );
1944         GlobalShortcuts_insert( "CameraFreeMoveLeft", Accelerator( GDK_Left ) );
1945         GlobalShortcuts_insert( "CameraFreeMoveRight", Accelerator( GDK_Right ) );
1946
1947         GlobalShortcuts_insert( "CameraFreeMoveForward2", Accelerator( GDK_Up ) );
1948         GlobalShortcuts_insert( "CameraFreeMoveBack2", Accelerator( GDK_Down ) );
1949         GlobalShortcuts_insert( "CameraFreeMoveLeft2", Accelerator( GDK_Left ) );
1950         GlobalShortcuts_insert( "CameraFreeMoveRight2", Accelerator( GDK_Right ) );
1951
1952         GlobalToggles_insert( "ShowStats", makeCallbackF(ShowStatsToggle), ToggleItem::AddCallbackCaller( g_show_stats ) );
1953
1954         GlobalPreferenceSystem().registerPreference( "ShowStats", make_property_string( g_camwindow_globals_private.m_showStats ) );
1955         GlobalPreferenceSystem().registerPreference( "MoveSpeed", make_property_string( g_camwindow_globals_private.m_nMoveSpeed ) );
1956         GlobalPreferenceSystem().registerPreference( "CamLinkSpeed", make_property_string( g_camwindow_globals_private.m_bCamLinkSpeed ) );
1957         GlobalPreferenceSystem().registerPreference( "AngleSpeed", make_property_string( g_camwindow_globals_private.m_nAngleSpeed ) );
1958         GlobalPreferenceSystem().registerPreference( "CamInverseMouse", make_property_string( g_camwindow_globals_private.m_bCamInverseMouse ) );
1959         GlobalPreferenceSystem().registerPreference( "CamDiscrete", make_property_string<CamWnd_Move_Discrete>());
1960         GlobalPreferenceSystem().registerPreference( "CubicClipping", make_property_string( g_camwindow_globals_private.m_bCubicClipping ) );
1961         GlobalPreferenceSystem().registerPreference( "CubicScale", make_property_string( g_camwindow_globals.m_nCubicScale ) );
1962         GlobalPreferenceSystem().registerPreference( "SI_Colors4", make_property_string( g_camwindow_globals.color_cameraback ) );
1963         GlobalPreferenceSystem().registerPreference( "SI_Colors12", make_property_string( g_camwindow_globals.color_selbrushes3d ) );
1964         GlobalPreferenceSystem().registerPreference( "CameraRenderMode", make_property_string<RenderMode>() );
1965         GlobalPreferenceSystem().registerPreference( "StrafeMode", make_property_string( g_camwindow_globals_private.m_nStrafeMode ) );
1966
1967         CamWnd_constructStatic();
1968
1969         Camera_registerPreferencesPage();
1970 }
1971 void CamWnd_Destroy(){
1972         CamWnd_destroyStatic();
1973 }