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