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