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