]> git.mxchange.org Git - flightgear.git/blob - src/GUI/gui.cxx
631accc8fa2be6adf62872d42fac0336f6a6fd69
[flightgear.git] / src / GUI / gui.cxx
1 /**************************************************************************
2  * gui.cxx
3  *
4  * Written 1998 by Durk Talsma, started Juni, 1998.  For the flight gear
5  * project.
6  *
7  * Additional mouse supported added by David Megginson, 1999.
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License as
11  * published by the Free Software Foundation; either version 2 of the
12  * License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22  *
23  * $Id$
24  **************************************************************************/
25
26
27 #ifdef HAVE_CONFIG_H
28 #  include <config.h>
29 #endif
30
31 #include <simgear/compiler.h>
32
33 #ifdef FG_MATH_EXCEPTION_CLASH
34 #  include <math.h>
35 #endif
36
37 #ifdef HAVE_WINDOWS_H
38 #  include <windows.h>
39 #endif
40
41 #include <GL/glut.h>
42 #include <simgear/xgl/xgl.h>
43
44 #if defined(FX) && defined(XMESA)
45 #  include <GL/xmesa.h>
46 #endif
47
48 #include STL_FSTREAM
49 #include STL_STRING
50
51 #include <stdlib.h>
52 #include <string.h>
53
54 #include <simgear/constants.h>
55 #include <simgear/debug/logstream.hxx>
56 #include <simgear/misc/fgpath.hxx>
57 #include <simgear/screen/screen-dump.hxx>
58
59 #include <Include/general.hxx>
60 #include <Aircraft/aircraft.hxx>
61 #include <Airports/simple.hxx>
62 #include <Autopilot/auto_gui.hxx>
63 #include <Autopilot/newauto.hxx>
64 #include <Cockpit/panel.hxx>
65 #include <Controls/controls.hxx>
66 #include <FDM/flight.hxx>
67 #include <Main/bfi.hxx>
68 #include <Main/fg_init.hxx>
69 #include <Main/globals.hxx>
70 #include <Main/options.hxx>
71 #include <Main/views.hxx>
72 #include <Main/save.hxx>
73 #ifdef FG_NETWORK_OLK
74 #include <NetworkOLK/network.h>
75 #endif
76
77 #if defined( WIN32 ) && !defined( __CYGWIN__ )
78 #  include <simgear/screen/win32-printer.h>
79 #  include <simgear/screen/GlBitmaps.h>
80 #endif
81
82 /*
83  * trackball.h
84  * A virtual trackball implementation
85  * Written by Gavin Bell for Silicon Graphics, November 1988.
86  */
87 /*
88  * Pass the x and y coordinates of the last and current positions of
89  * the mouse, scaled so they are from (-1.0 ... 1.0).
90  *
91  * The resulting rotation is returned as a quaternion rotation in the
92  * first paramater.
93  */
94 void
95 trackball(float q[4], float p1x, float p1y, float p2x, float p2y);
96
97 /*
98  * Given two quaternions, add them together to get a third quaternion.
99  * Adding quaternions to get a compound rotation is analagous to adding
100  * translations to get a compound translation.  When incrementally
101  * adding rotations, the first argument here should be the new
102
103   * rotation, the second and third the total rotation (which will be
104  * over-written with the resulting new total rotation).
105  */
106 void
107 add_quats(float *q1, float *q2, float *dest);
108
109 /*
110  * A useful function, builds a rotation matrix in Matrix based on
111  * given quaternion.
112  */
113 void
114 build_rotmatrix(float m[4][4], float q[4]);
115
116 /*
117  * This function computes a quaternion based on an axis (defined by
118  * the given vector) and an angle about which to rotate.  The angle is
119  * expressed in radians.  The result is put into the third argument.
120  */
121 void
122 axis_to_quat(float a[3], float phi, float q[4]);
123
124
125 #include "gui.h"
126
127 FG_USING_STD(string);
128
129 #ifndef FG_HAVE_NATIVE_SGI_COMPILERS
130 FG_USING_STD(cout);
131 #endif
132
133 #if defined(WIN32) || defined(__CYGWIN32__)
134 #define WIN32_CURSOR_TWEAKS
135 #elif (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9)
136 #define X_CURSOR_TWEAKS
137 #endif
138
139 // hack, should come from an include someplace
140 extern void fgInitVisuals( void );
141 extern void fgReshape( int width, int height );
142 extern void fgRenderFrame( void );
143
144 puFont guiFnt = 0;
145 fntTexFont *guiFntHandle = 0;
146
147 static puMenuBar    *mainMenuBar = 0;
148 //static puButton     *hideMenuButton = 0;
149
150 static puDialogBox  *dialogBox = 0;
151 static puFrame      *dialogFrame = 0;
152 static puText       *dialogBoxMessage = 0;
153 static puOneShot    *dialogBoxOkButton = 0;
154
155
156 static puDialogBox  *YNdialogBox = 0;
157 static puFrame      *YNdialogFrame = 0;
158 static puText       *YNdialogBoxMessage = 0;
159 static puOneShot    *YNdialogBoxOkButton = 0;
160 static puOneShot    *YNdialogBoxNoButton = 0;
161
162 static char msg_OK[]     = "OK";
163 static char msg_NO[]     = "NO";
164 static char msg_YES[]    = "YES";
165 static char msg_CANCEL[] = "Cancel";
166 static char msg_RESET[]  = "Reset";
167
168 char *gui_msg_OK;     // "OK"
169 char *gui_msg_NO;     // "NO"
170 char *gui_msg_YES;    // "YES"
171 char *gui_msg_CANCEL; // "CANCEL"
172 char *gui_msg_RESET;  // "RESET"
173
174 static char global_dialog_string[256];
175
176 // from autopilot.cxx
177 // extern void NewAltitude( puObject *cb );
178 // extern void NewHeading( puObject *cb );
179 // extern void fgAPAdjust( puObject * );
180 // extern void NewTgtAirport( puObject *cb );
181 // bool fgAPTerrainFollowEnabled( void );
182 // bool fgAPAltitudeEnabled( void );
183 // bool fgAPHeadingEnabled( void );
184 // bool fgAPWayPointEnabled( void );
185 // bool fgAPAutoThrottleEnabled( void );
186
187 // from cockpit.cxx
188 extern void fgLatLonFormatToggle( puObject *);
189
190 /* --------------------------------------------------------------------
191 Mouse stuff
192 ---------------------------------------------------------------------*/
193
194 static int _mX = 0;
195 static int _mY = 0;
196 static int _savedX = 0;
197 static int _savedY = 0;
198 static int last_buttons = 0 ;
199 static int mouse_active = 0;
200 static int menu_on = 0;
201 static int mouse_joystick_control = 0;
202
203 //static time_t mouse_off_time;
204 //static int mouse_timed_out;
205
206 // to allow returning to previous view
207 // on second left click in MOUSE_VIEW mode
208 // This has file scope so that it can be reset
209 // if the little rodent is moved  NHV
210 static  int _mVtoggle;
211
212 // we break up the glutGetModifiers return mask
213 // once per loop and stash what we need in these
214 static int glut_active_shift;
215 static int glut_active_ctrl;
216 static int glut_active_alt;
217
218 static float lastquat[4];
219 static float curquat[4];
220 static float _quat0[4];
221 float quat_mat[4][4];
222
223 // uncomment this for view to exactly follow mouse in MOUSE_VIEW mode
224 // else smooth out the view panning to .01 radian per frame
225 // see view_offset smoothing mechanism in main.cxx
226 #define NO_SMOOTH_MOUSE_VIEW
227
228 // uncomment following to
229 #define RESET_VIEW_ON_LEAVING_MOUSE_VIEW
230
231 /* --------------------------------------------------------------------
232 Support for mouse as control yoke (david@megginson.com)
233
234 - right button toggles between pointer and yoke
235 - horizontal drag with no buttons moves ailerons
236 - vertical drag with no buttons moves elevators
237 - horizontal drag with left button moves brakes (left=on)
238 - vertical drag with left button moves throttle (up=more)
239 - horizontal drag with middle button moves rudder
240 - vertical drag with middle button moves trim
241
242 For the *_sensitivity variables, a lower number means more sensitive.
243
244 TODO: figure out how to keep pointer from leaving window in yoke mode.
245 TODO: add thresholds and null zones
246 TODO: sensitivity should be configurable at user option.
247 TODO: allow differential braking (this will be useful if FlightGear
248       ever supports tail-draggers like the DC-3)
249 ---------------------------------------------------------------------*/
250
251 typedef enum {
252     MOUSE_POINTER,
253     MOUSE_YOKE,
254     MOUSE_VIEW
255 } MouseMode;
256
257 MouseMode mouse_mode = MOUSE_POINTER;
258
259 static double aileron_sensitivity = 1.0/500.0;
260 static double elevator_sensitivity = 1.0/500.0;
261 static double brake_sensitivity = 1.0/250.0;
262 static double throttle_sensitivity = 1.0/250.0;
263 static double rudder_sensitivity = 1.0/500.0;
264 static double trim_sensitivity = 1.0/1000.0;
265
266 static inline void Quat0( void ) {
267     curquat[0] = _quat0[0];
268     curquat[1] = _quat0[1];
269     curquat[2] = _quat0[2];
270     curquat[3] = _quat0[3];
271 }
272
273 static inline int left_button( void ) {
274     return( last_buttons & (1 << GLUT_LEFT_BUTTON) );
275 }
276
277 static inline int middle_button( void ) {
278     return( last_buttons & (1 << GLUT_MIDDLE_BUTTON) );
279 }
280
281 static inline int right_button( void ) {
282     return( last_buttons & (1 << GLUT_RIGHT_BUTTON) );
283 }
284
285 static inline void TurnCursorOn( void )
286 {
287     mouse_active = ~0;
288 #if defined(WIN32_CURSOR_TWEAKS)
289     switch (mouse_mode) {
290         case MOUSE_POINTER:
291             glutSetCursor(GLUT_CURSOR_INHERIT);
292             break;
293         case MOUSE_YOKE:
294             glutSetCursor(GLUT_CURSOR_CROSSHAIR);
295             break;
296         case MOUSE_VIEW:
297             glutSetCursor(GLUT_CURSOR_LEFT_RIGHT);
298             break;
299     }
300 #endif
301 #if defined(X_CURSOR_TWEAKS)
302     glutWarpPointer( current_view.get_winWidth()/2, current_view.get_winHeight()/2);
303 #endif
304 }
305
306 static inline void TurnCursorOff( void )
307 {
308     mouse_active = 0;
309 #if defined(WIN32_CURSOR_TWEAKS)
310     glutSetCursor(GLUT_CURSOR_NONE);
311 #elif defined(X_CURSOR_TWEAKS)
312     glutWarpPointer( current_view.get_winWidth(), current_view.get_winHeight());
313 #endif
314 }
315
316 void maybeToggleMouse( void )
317 {
318 #if defined(WIN32_CURSOR_TWEAKS)
319     static int first_time = ~0;
320     static int mouse_changed = 0;
321
322     if ( first_time ) {
323         if(!mouse_active) {
324             mouse_changed = ~mouse_changed;
325             TurnCursorOn();
326         }
327     } else {
328         if( mouse_mode != MOUSE_POINTER )
329             return;
330         if( mouse_changed ) {
331             mouse_changed = ~mouse_changed;
332             if(mouse_active) {
333                 TurnCursorOff();
334             }
335         }
336     }
337     first_time = ~first_time;
338 #endif // #ifdef WIN32
339 }
340
341 // Call with FALSE to init and TRUE to restore
342 void BusyCursor( int restore )
343 {
344     static GLenum cursor = (GLenum) 0;
345     if( restore ) {
346         glutSetCursor(cursor);
347     } else {
348         cursor = (GLenum) glutGet( (GLenum) GLUT_WINDOW_CURSOR );
349 #if defined(WIN32_CURSOR_TWEAKS)
350         TurnCursorOn();
351 #endif
352         glutSetCursor( GLUT_CURSOR_WAIT );
353     }
354 }
355
356 int guiGetMouseButton(void)
357 {
358     return last_buttons;
359 }
360
361 void guiGetMouse(int *x, int *y)
362 {
363     *x = _mX;
364     *y = _mY;
365 };
366
367 void guiMotionFunc ( int x, int y )
368 {
369     int ww, wh, need_warp = 0;
370     float W, H;
371     double offset;
372
373     if (mouse_mode == MOUSE_POINTER) {
374         puMouse ( x, y ) ;
375         glutPostRedisplay () ;
376     } else {
377         if( x == _mX && y == _mY)
378             return;
379         
380         // reset left click MOUSE_VIEW toggle feature
381         _mVtoggle = 0;
382         
383         ww = current_view.get_winWidth();
384         wh = current_view.get_winHeight();
385         
386         switch (mouse_mode) {
387             case MOUSE_YOKE:
388                 if( !mouse_joystick_control ) {
389                     mouse_joystick_control = 1;
390                     current_options.set_control_mode( fgOPTIONS::FG_MOUSE );
391                 } else {
392                     if ( left_button() ) {
393                         offset = (_mX - x) * brake_sensitivity;
394                         controls.move_brake(FGControls::ALL_WHEELS, offset);
395                         offset = (_mY - y) * throttle_sensitivity;
396                         controls.move_throttle(FGControls::ALL_ENGINES, offset);
397                     } else if ( right_button() ) {
398                         if( ! current_autopilot->get_HeadingEnabled() ) {
399                             offset = (x - _mX) * rudder_sensitivity;
400                             controls.move_rudder(offset);
401                         }
402                         if( ! current_autopilot->get_AltitudeEnabled() ) {
403                             offset = (_mY - y) * trim_sensitivity;
404                             controls.move_elevator_trim(offset);
405                         }
406                     } else {
407                         if( ! current_autopilot->get_HeadingEnabled() ) {
408                             offset = (x - _mX) * aileron_sensitivity;
409                             controls.move_aileron(offset);
410                         }
411                         if( ! current_autopilot->get_AltitudeEnabled() ) {
412                             offset = (_mY - y) * elevator_sensitivity;
413                             controls.move_elevator(offset);
414                         }
415                     }
416                 }
417                 // Keep the mouse in the window.
418                 if (x < 5 || x > ww-5 || y < 5 || y > wh-5) {
419                     x = ww / 2;
420                     y = wh / 2;
421                     need_warp = 1;
422                 }
423                 break;
424                 
425             case MOUSE_VIEW:
426                 if( y <= 0 ) {
427 #define CONTRAINED_MOUSE_VIEW_Y
428 #ifdef CONTRAINED_MOUSE_VIEW_Y
429                     y = 1;
430 #else
431                     y = wh-2;
432 #endif // CONTRAINED_MOUSE_VIEW_Y
433                     need_warp = 1;
434                 } else if( y >= wh-1) {
435 #ifdef CONTRAINED_MOUSE_VIEW_Y
436                     y = wh-2;
437 #else
438                     y = 1;
439 #endif // CONTRAINED_MOUSE_VIEW_Y
440                     need_warp = 1;
441                 }
442                 // wrap MOUSE_VIEW mode cursor x position
443                 if ( x <= 0 ) {
444                     need_warp = 1;
445                     x = ww-2;
446                 } else if ( x >= ww-1 ) {
447                     need_warp = 1;
448                     x = 1;
449                 }
450                 // try to get FG_PI movement in each half of screen
451                 // do spherical pan
452                 W = ww;
453                 H = wh;
454                 if( middle_button() ) {
455                     trackball(lastquat,
456                               (2.0f * _mX - W) / W,
457                               0, //(H - 2.0f * y) / H,         // 3
458                               (2.0f * x - W) / W,
459                               0 //(H - 2.0f * _mY) / H       // 1
460                              );
461                     x = _mX;
462                     y = _mY;
463                     need_warp = 1;
464                 } else {
465                     trackball(lastquat,
466                               0, //(2.0f * _mX - W) / W,  // 0
467                               (H - 2.0f * y) / H,         // 3
468                               0, //(2.0f * x - W) / W,    // 2
469                               (H - 2.0f * _mY) / H        // 1 
470                              );
471                 }
472                 add_quats(lastquat, curquat, curquat);
473                 build_rotmatrix(quat_mat, curquat);
474                 
475                 // do horizontal pan
476                 // this could be done in above quat
477                 // but requires redoing view pipeline
478                 offset = current_view.get_goal_view_offset();
479                 offset += ((_mX - x) * FG_2PI / W );
480                 while (offset < 0.0) {
481                     offset += FG_2PI;
482                 }
483                 while (offset > FG_2PI) {
484                     offset -= FG_2PI;
485                 }
486                 current_view.set_goal_view_offset(offset);
487 #ifdef NO_SMOOTH_MOUSE_VIEW
488                 current_view.set_view_offset(offset);
489 #endif
490                 break;
491             
492             default:
493                 break;
494         }
495     }
496     if( need_warp)
497         glutWarpPointer(x, y);
498     
499     // Record the new mouse position.
500     _mX = x;
501     _mY = y;
502 }
503
504
505 void guiMouseFunc(int button, int updown, int x, int y)
506 {
507     int glutModifiers;
508
509     // private MOUSE_VIEW state variables
510     // to allow alternate left clicks in MOUSE_VIEW mode
511     // to toggle between current offsets and straight ahead
512     // uses _mVtoggle
513     static int _mVx, _mVy, _Vx, _Vy;
514     static float _quat[4];
515     static double _view_offset;
516     
517     // general purpose variables
518     double offset;
519             
520     glutModifiers = glutGetModifiers();
521     glut_active_shift = glutModifiers & GLUT_ACTIVE_SHIFT;
522     glut_active_ctrl  = glutModifiers & GLUT_ACTIVE_CTRL; 
523     glut_active_alt   = glutModifiers & GLUT_ACTIVE_ALT;
524     
525     // Was the left button pressed?
526     if (updown == GLUT_DOWN ) {
527         if( button == GLUT_LEFT_BUTTON)
528         {
529             switch (mouse_mode) {
530                 case MOUSE_POINTER:
531                     break;
532                 case MOUSE_YOKE:
533                     break;
534                 case MOUSE_VIEW:
535                     if(_mVtoggle) {
536                         // resume previous view offsets
537                         _mX = _mVx;
538                         _mY = _mVy;
539                         x = _Vx;
540                         y = _Vy;
541                         curquat[0] = _quat[0];
542                         curquat[1] = _quat[1];
543                         curquat[2] = _quat[2];
544                         curquat[3] = _quat[3];
545                         current_view.set_goal_view_offset(_view_offset);
546 #ifdef NO_SMOOTH_MOUSE_VIEW
547                         current_view.set_view_offset(_view_offset);
548 #endif
549                     } else {
550                         // center view
551                         _mVx = _mX;
552                         _mVy = _mY;
553                         _Vx = x;
554                         _Vy = y;
555                         _quat[0] = curquat[0];
556                         _quat[1] = curquat[1];
557                         _quat[2] = curquat[2];
558                         _quat[3] = curquat[3];
559                         x = current_view.get_winWidth()/2;
560                         y = current_view.get_winHeight()/2;
561                         Quat0();
562                         _view_offset = current_view.get_goal_view_offset();
563                         current_view.set_goal_view_offset(0.0);
564 #ifdef NO_SMOOTH_MOUSE_VIEW
565                         current_view.set_view_offset(0.0);
566 #endif
567                     }
568                     glutWarpPointer( x , y);
569                     build_rotmatrix(quat_mat, curquat);
570                     _mVtoggle = ~_mVtoggle;
571                     break;
572             }
573         }else if ( button == GLUT_RIGHT_BUTTON) {
574             switch (mouse_mode) {
575                 case MOUSE_POINTER:
576                     mouse_mode = MOUSE_YOKE;
577                     mouse_joystick_control = 0;
578                     _savedX = x;
579                     _savedY = y;
580                     // start with zero point in center of screen
581                     _mX = current_view.get_winWidth()/2;
582                     _mY = current_view.get_winHeight()/2;
583                     
584                     // try to have the MOUSE_YOKE position
585                     // reflect the current stick position
586                     offset = controls.get_aileron();
587                     x = _mX - (int)(offset * aileron_sensitivity);
588                     offset = controls.get_elevator();
589                     y = _mY - (int)(offset * elevator_sensitivity);
590                     
591                     glutSetCursor(GLUT_CURSOR_CROSSHAIR);
592                     FG_LOG( FG_INPUT, FG_INFO, "Mouse in yoke mode" );
593                     break;
594                     
595                 case MOUSE_YOKE:
596                     mouse_mode = MOUSE_VIEW;
597                     current_options.set_control_mode( fgOPTIONS::FG_JOYSTICK );
598                     x = current_view.get_winWidth()/2;
599                     y = current_view.get_winHeight()/2;
600                     _mVtoggle = 0;
601                     Quat0();
602                     build_rotmatrix(quat_mat, curquat);
603                     glutSetCursor(GLUT_CURSOR_LEFT_RIGHT);
604                     FG_LOG( FG_INPUT, FG_INFO, "Mouse in view mode" );
605                     break;
606                     
607                 case MOUSE_VIEW:
608                     mouse_mode = MOUSE_POINTER;
609                     x = _savedX;
610                     y = _savedY;
611 #ifdef RESET_VIEW_ON_LEAVING_MOUSE_VIEW
612                     Quat0();
613                     build_rotmatrix(quat_mat, curquat);
614                     current_view.set_goal_view_offset(0.0);
615 #ifdef NO_SMOOTH_MOUSE_VIEW
616                     current_view.set_view_offset(0.0);
617 #endif
618 #endif      // RESET_VIEW_ON_LEAVING_MOUSE_VIEW
619                     glutSetCursor(GLUT_CURSOR_INHERIT);
620                     
621                     if(!menu_on)
622                         TurnCursorOff();
623                     
624                     FG_LOG( FG_INPUT, FG_INFO, "Mouse in pointer mode" );
625                     break;
626             }     
627             glutWarpPointer( x, y );
628         } // END RIGHT BUTTON
629     } // END UPDOWN == GLUT_DOWN
630     
631     // Note which button is pressed.
632     if ( updown == GLUT_DOWN ) {
633         last_buttons |=  ( 1 << button ) ;
634     } else {
635         last_buttons &= ~( 1 << button ) ;
636     }
637     
638     // If we're in pointer mode, let PUI
639     // know what's going on.
640     if (mouse_mode == MOUSE_POINTER) {
641       if (!puMouse (button, updown, x,y)) {
642         current_panel->doMouseAction(button, updown, x, y);
643       }
644     }
645     
646     // Register the new position (if it
647     // hasn't been registered already).
648     _mX = x;
649     _mY = y;
650     
651     glutPostRedisplay ();
652 }
653
654 /* ================ General Purpose Functions ================ */
655
656 // Intercept the Escape Key
657 void ConfirmExitDialog(void)
658 {
659     FG_PUSH_PUI_DIALOG( YNdialogBox );
660 }
661
662 // General Purpose Message Box
663 void mkDialog (const char *txt)
664 {
665     strncpy(global_dialog_string, txt, 256);
666     dialogBoxMessage->setLabel(global_dialog_string);
667     FG_PUSH_PUI_DIALOG( dialogBox );
668 }
669
670 // Toggle the Menu and Mouse display state
671 void guiToggleMenu(void)
672 {
673     if( menu_on ) {
674         // printf("Hiding Menu\n");
675         mainMenuBar->hide  ();
676 #if defined(WIN32_CURSOR_TWEAKS)
677         if( mouse_mode == MOUSE_POINTER )
678             TurnCursorOff();
679 #endif // #ifdef WIN32_CURSOR_TWEAKS
680     } else {
681         // printf("Showing Menu\n");
682         mainMenuBar->reveal();
683 #ifdef WIN32
684         TurnCursorOn();
685 #endif // #ifdef WIN32
686     }
687     menu_on = ~menu_on;
688 }
689     
690 /* -----------------------------------------------------------------------
691 the Gui callback functions 
692 ____________________________________________________________________*/
693
694 static void saveFlight(puObject *cv)
695 {
696     BusyCursor(0);
697     ofstream output("fgfs.sav");
698     if (output.good() && fgSaveFlight(output)) {
699       output.close();
700       mkDialog("Saved flight to ./fgfs.sav");
701       FG_LOG(FG_INPUT, FG_INFO, "Saved flight to fgfs.sav");
702     } else {
703       mkDialog("Cannot save flight to ./fgfs.sav");
704       FG_LOG(FG_INPUT, FG_ALERT, "Cannot save flight to fgfs.sav");
705     }
706     BusyCursor(1);
707 }
708
709 static void loadFlight(puObject *cb)
710 {
711     BusyCursor(0);
712     ifstream input("fgfs.sav");
713     if (input.good() && fgLoadFlight(input)) {
714       input.close();
715       mkDialog("Loaded flight from fgfs.sav");
716       FG_LOG(FG_INPUT, FG_INFO, "Restored flight from ./fgfs.sav");
717     } else {
718       mkDialog("Failed to load flight from fgfs.sav");
719       FG_LOG(FG_INPUT, FG_ALERT, "Cannot load flight from ./fgfs.sav");
720     }
721     BusyCursor(1);
722 }
723
724 void reInit(puObject *cb)
725 {
726     BusyCursor(0);
727     Quat0();
728     build_rotmatrix(quat_mat, curquat);
729     fgReInitSubsystems();
730     BusyCursor(1);
731 }
732
733 static void toggleClouds(puObject *cb)
734 {
735     FGBFI::setClouds( !FGBFI::getClouds() );
736 }
737         
738 // This is the accessor function
739 void guiTogglePanel(puObject *cb)
740 {
741     current_options.toggle_panel();
742 }
743     
744 //void MenuHideMenuCb(puObject *cb)
745 void hideMenuCb (puObject *cb)
746 {
747     guiToggleMenu();
748 }
749
750 void goodBye(puObject *)
751 {
752     // FG_LOG( FG_INPUT, FG_ALERT,
753     //      "Program exiting normally at user request." );
754     cout << "Program exiting normally at user request." << endl;
755
756 #ifdef FG_NETWORK_OLK    
757     if ( current_options.get_network_olk() ) {
758         if ( net_is_registered == 0 ) fgd_send_com( "8", FGFS_host);
759     }
760 #endif
761
762     //  if(gps_bug)
763     //      fclose(gps_bug);
764
765     exit(-1);
766 }
767
768
769 void goAwayCb (puObject *me)
770 {
771     FG_POP_PUI_DIALOG( dialogBox );
772 }
773
774 void mkDialogInit (void)
775 {
776     //  printf("mkDialogInit\n");
777     int x = (current_options.get_xsize()/2 - 400/2);
778     int y = (current_options.get_ysize()/2 - 100/2);
779     dialogBox = new puDialogBox (x, y); // 150, 50
780     {
781         dialogFrame = new puFrame (0,0,400,100);
782         dialogBoxMessage  =  new puText         (10, 70);
783         dialogBoxMessage  -> setLabel           ("");
784         dialogBoxOkButton =  new puOneShot      (180, 10, 240, 50);
785         dialogBoxOkButton -> setLegend          (gui_msg_OK);
786         dialogBoxOkButton -> makeReturnDefault  (TRUE );
787         dialogBoxOkButton -> setCallback        (goAwayCb);
788     }
789     FG_FINALIZE_PUI_DIALOG( dialogBox );
790 }
791
792 void MayBeGoodBye(puObject *)
793 {
794     ConfirmExitDialog(); 
795 }
796
797 void goAwayYesNoCb(puObject *me)
798 {
799     FG_POP_PUI_DIALOG( YNdialogBox);
800 }
801
802 void ConfirmExitDialogInit(void)
803 {
804     char msg[] = "Really Quit";
805     char *s;
806
807     //  printf("ConfirmExitDialogInit\n");
808     int len = 200 - puGetStringWidth( puGetDefaultLabelFont(), msg )/2;
809
810     int x = (current_options.get_xsize()/2 - 400/2);
811     int y = (current_options.get_ysize()/2 - 100/2);
812         
813     YNdialogBox = new puDialogBox (x, y); // 150, 50
814     //  YNdialogBox = new puDialogBox (150, 50);
815     {
816         YNdialogFrame = new puFrame (0,0,400, 100);
817         
818         YNdialogBoxMessage  =  new puText         (len, 70);
819         YNdialogBoxMessage  -> setDefaultValue    (msg);
820         YNdialogBoxMessage  -> getDefaultValue    (&s);
821         YNdialogBoxMessage  -> setLabel           (s);
822         
823         YNdialogBoxOkButton =  new puOneShot      (100, 10, 160, 50);
824         YNdialogBoxOkButton -> setLegend          (gui_msg_OK);
825         YNdialogBoxOkButton -> makeReturnDefault  (TRUE );
826         YNdialogBoxOkButton -> setCallback        (goodBye);
827         
828         YNdialogBoxNoButton =  new puOneShot      (240, 10, 300, 50);
829         YNdialogBoxNoButton -> setLegend          (gui_msg_NO);
830         YNdialogBoxNoButton -> setCallback        (goAwayYesNoCb);
831     }
832     FG_FINALIZE_PUI_DIALOG( YNdialogBox );
833 }
834
835 void notCb (puObject *)
836 {
837     mkDialog ("This function isn't implemented yet");
838 }
839
840 void helpCb (puObject *)
841 {
842     string command;
843         
844 #if defined(FX) && !defined(WIN32)
845 #  if defined(XMESA_FX_FULLSCREEN) && defined(XMESA_FX_WINDOW)
846     if ( global_fullscreen ) {
847         global_fullscreen = false;
848         XMesaSetFXmode( XMESA_FX_WINDOW );
849     }
850 #  endif
851 #endif
852         
853 #if !defined(WIN32)
854     string url = "http://www.flightgear.org/Docs/InstallGuide/getstart.html";
855         
856     if ( system("xwininfo -name Netscape > /dev/null 2>&1") == 0 ) {
857         command = "netscape -remote \"openURL(" + url + ")\" &";
858     } else {
859         command = "netscape " + url + " &";
860     }
861 #else
862     command = "webrun.bat";
863 #endif
864         
865     system( command.c_str() );
866     //string text = "Help started in netscape window.";
867
868     //mkDialog (text.c_str());
869     mkDialog ("Help started in netscape window.");
870 }
871
872 #if defined( WIN32 ) && !defined( __CYGWIN__)
873
874 static void rotateView( double roll, double pitch, double yaw )
875 {
876         // rotate view
877 }
878
879 static GlBitmap *b1 = NULL;
880 extern FGInterface cur_view_fdm;
881 GLubyte *hiResScreenCapture( int multiplier )
882 {
883         float oldfov = current_options.get_fov();
884         float fov = oldfov / multiplier;
885         FGView *v = &current_view;
886         current_options.set_fov(fov);
887         v->force_update_fov_math();
888     fgInitVisuals();
889     int cur_width = current_view.get_winWidth( );
890     int cur_height = current_view.get_winHeight( );
891         if (b1) delete( b1 );
892         // New empty (mostly) bitmap
893         b1 = new GlBitmap( GL_RGB, 1, 1, (unsigned char *)"123" );
894         int x,y;
895         for ( y = 0; y < multiplier; y++ )
896         {
897                 for ( x = 0; x < multiplier; x++ )
898                 {
899                         fgReshape( cur_width, cur_height );
900                         // pan to tile
901                         rotateView( 0, (y*fov)-((multiplier-1)*fov/2), (x*fov)-((multiplier-1)*fov/2) );
902                         fgRenderFrame();
903                         // restore view
904                         GlBitmap b2;
905                         b1->copyBitmap( &b2, cur_width*x, cur_height*y );
906                 }
907         }
908         current_view.UpdateViewParams(cur_view_fdm);
909         current_options.set_fov(oldfov);
910         v->force_update_fov_math();
911         return b1->getBitmap();
912 }
913 #endif
914
915
916 #if defined( WIN32 ) && !defined( __CYGWIN__)
917 // win32 print screen function
918 void printScreen ( puObject *obj ) {
919     bool show_pu_cursor = false;
920     TurnCursorOff();
921     if ( !puCursorIsHidden() ) {
922         show_pu_cursor = true;
923         puHideCursor();
924     }
925     BusyCursor( 0 );
926     mainMenuBar->hide();
927
928     CGlPrinter p( CGlPrinter::PRINT_BITMAP );
929     int cur_width = current_view.get_winWidth( );
930     int cur_height = current_view.get_winHeight( );
931     p.Begin( "FlightGear", cur_width*3, cur_height*3 );
932         p.End( hiResScreenCapture(3) );
933
934     if( menu_on ) {
935         mainMenuBar->reveal();
936     }
937     BusyCursor(1);
938     if ( show_pu_cursor ) {
939         puShowCursor();
940     }
941     TurnCursorOn();
942 }
943 #endif // #ifdef WIN32
944
945
946 void dumpSnapShot ( puObject *obj ) {
947     fgDumpSnapShot();
948 }
949
950
951 // do a screen snap shot
952 void fgDumpSnapShot () {
953     bool show_pu_cursor = false;
954
955     int freeze = globals->get_freeze();
956     if(!freeze)
957         globals->set_freeze( true );
958
959     mainMenuBar->hide();
960     TurnCursorOff();
961     if ( !puCursorIsHidden() ) {
962         show_pu_cursor = true;
963         puHideCursor();
964     }
965
966     fgInitVisuals();
967     fgReshape( current_view.get_winWidth(), current_view.get_winHeight() );
968
969     // we need two render frames here to clear the menu and cursor
970     // ... not sure why but doing an extra fgFenderFrame() shoulnd't
971     // hurt anything
972     fgRenderFrame();
973     fgRenderFrame();
974
975     my_glDumpWindow( "fgfs-screen.ppm", 
976                      current_options.get_xsize(), 
977                      current_options.get_ysize() );
978     
979     mkDialog ("Snap shot saved to fgfs-screen.ppm");
980
981     if ( show_pu_cursor ) {
982         puShowCursor();
983     }
984
985     TurnCursorOn();
986     if( menu_on ) {
987         mainMenuBar->reveal();
988     }
989
990     if(!freeze)
991         globals->set_freeze( false );
992 }
993
994
995 /// The beginnings of teleportation :-)
996 //  Needs cleaning up but works
997 //  These statics should disapear when this is a class
998 static puDialogBox     *AptDialog = 0;
999 static puFrame         *AptDialogFrame = 0;
1000 static puText          *AptDialogMessage = 0;
1001 static puInput         *AptDialogInput = 0;
1002
1003 static char NewAirportId[16];
1004 static char NewAirportLabel[] = "Enter New Airport ID"; 
1005
1006 static puOneShot       *AptDialogOkButton = 0;
1007 static puOneShot       *AptDialogCancelButton = 0;
1008 static puOneShot       *AptDialogResetButton = 0;
1009
1010 void AptDialog_Cancel(puObject *)
1011 {
1012     FG_POP_PUI_DIALOG( AptDialog );
1013 }
1014
1015 void AptDialog_OK (puObject *)
1016 {
1017     FGPath path( current_options.get_fg_root() );
1018     path.append( "Airports" );
1019     path.append( "simple.mk4" );
1020     FGAirports airports( path.c_str() );
1021
1022     FGAirport a;
1023     
1024     int freeze = globals->get_freeze();
1025     if(!freeze)
1026         globals->set_freeze( true );
1027
1028     char *s;
1029     AptDialogInput->getValue(&s);
1030     string AptId(s);
1031
1032         cout << "AptDialog_OK " << AptId << " " << AptId.length() << endl;
1033     
1034     AptDialog_Cancel( NULL );
1035     
1036     if ( AptId.length() ) {
1037         // set initial position from airport id
1038         FG_LOG( FG_GENERAL, FG_INFO,
1039                 "Attempting to set starting position from airport code "
1040                 << AptId );
1041
1042         if ( airports.search( AptId, &a ) )
1043         {
1044             current_options.set_airport_id( AptId.c_str() );
1045             current_options.set_altitude( -9999.0 );
1046             fgSetPosFromAirportID( AptId );
1047             BusyCursor(0);
1048             fgReInitSubsystems();
1049             BusyCursor(1);
1050         } else {
1051             AptId  += " not in database.";
1052             mkDialog(AptId.c_str());
1053         }
1054     }
1055     if(!freeze)
1056         globals->set_freeze( false );
1057 }
1058
1059 void AptDialog_Reset(puObject *)
1060 {
1061     //  strncpy( NewAirportId, current_options.get_airport_id().c_str(), 16 );
1062     sprintf( NewAirportId, "%s", current_options.get_airport_id().c_str() );
1063     AptDialogInput->setValue ( NewAirportId );
1064     AptDialogInput->setCursor( 0 ) ;
1065 }
1066
1067 void NewAirport(puObject *cb)
1068 {
1069     //  strncpy( NewAirportId, current_options.get_airport_id().c_str(), 16 );
1070     sprintf( NewAirportId, "%s", current_options.get_airport_id().c_str() );
1071 //      cout << "NewAirport " << NewAirportId << endl;
1072     AptDialogInput->setValue( NewAirportId );
1073
1074     FG_PUSH_PUI_DIALOG( AptDialog );
1075 }
1076
1077 static void NewAirportInit(void)
1078 {
1079     sprintf( NewAirportId, "%s", current_options.get_airport_id().c_str() );
1080     int len = 150 - puGetStringWidth( puGetDefaultLabelFont(),
1081                                       NewAirportLabel ) / 2;
1082
1083     AptDialog = new puDialogBox (150, 50);
1084     {
1085         AptDialogFrame   = new puFrame           (0,0,350, 150);
1086         AptDialogMessage = new puText            (len, 110);
1087         AptDialogMessage ->    setLabel          (NewAirportLabel);
1088
1089         AptDialogInput   = new puInput           (50, 70, 300, 100);
1090         AptDialogInput   ->    setValue          (NewAirportId);
1091         AptDialogInput   ->    acceptInput();
1092
1093         AptDialogOkButton     =  new puOneShot   (50, 10, 110, 50);
1094         AptDialogOkButton     ->     setLegend   (gui_msg_OK);
1095         AptDialogOkButton     ->     setCallback (AptDialog_OK);
1096         AptDialogOkButton     ->     makeReturnDefault(TRUE);
1097
1098         AptDialogCancelButton =  new puOneShot   (140, 10, 210, 50);
1099         AptDialogCancelButton ->     setLegend   (gui_msg_CANCEL);
1100         AptDialogCancelButton ->     setCallback (AptDialog_Cancel);
1101
1102         AptDialogResetButton  =  new puOneShot   (240, 10, 300, 50);
1103         AptDialogResetButton  ->     setLegend   (gui_msg_RESET);
1104         AptDialogResetButton  ->     setCallback (AptDialog_Reset);
1105     }
1106         cout << "NewAirportInit " << NewAirportId << endl;
1107     FG_FINALIZE_PUI_DIALOG( AptDialog );
1108 }
1109
1110 #ifdef FG_NETWORK_OLK
1111
1112 /// The beginnings of networking :-)
1113 //  Needs cleaning up but works
1114 //  These statics should disapear when this is a class
1115 static puDialogBox     *NetIdDialog = 0;
1116 static puFrame         *NetIdDialogFrame = 0;
1117 static puText          *NetIdDialogMessage = 0;
1118 static puInput         *NetIdDialogInput = 0;
1119
1120 static char NewNetId[16];
1121 static char NewNetIdLabel[] = "Enter New Callsign"; 
1122 extern char *fgd_callsign;
1123
1124 static puOneShot       *NetIdDialogOkButton = 0;
1125 static puOneShot       *NetIdDialogCancelButton = 0;
1126
1127 void NetIdDialog_Cancel(puObject *)
1128 {
1129     FG_POP_PUI_DIALOG( NetIdDialog );
1130 }
1131
1132 void NetIdDialog_OK (puObject *)
1133 {
1134     string NetId;
1135     
1136     bool freeze = globals->get_freeze();
1137     if(!freeze)
1138         globals->set_freeze( true );
1139 /*  
1140    The following needs some cleanup because 
1141    "string options.NetId" and "char *net_callsign" 
1142 */
1143     NetIdDialogInput->getValue(&net_callsign);
1144     NetId = net_callsign;
1145     
1146     NetIdDialog_Cancel( NULL );
1147     current_options.set_net_id( NetId.c_str() );
1148     strcpy( fgd_callsign, net_callsign);
1149 //    strcpy( fgd_callsign, current_options.get_net_id().c_str());
1150 /* Entering a callsign indicates : user wants Net HUD Info */
1151     net_hud_display = 1;
1152
1153     if(!freeze)
1154         globals->set_freeze( false );
1155 }
1156
1157 void NewCallSign(puObject *cb)
1158 {
1159     sprintf( NewNetId, "%s", current_options.get_net_id().c_str() );
1160 //    sprintf( NewNetId, "%s", fgd_callsign );
1161     NetIdDialogInput->setValue( NewNetId );
1162
1163     FG_PUSH_PUI_DIALOG( NetIdDialog );
1164 }
1165
1166 static void NewNetIdInit(void)
1167 {
1168     sprintf( NewNetId, "%s", current_options.get_net_id().c_str() );
1169 //    sprintf( NewNetId, "%s", fgd_callsign );
1170     int len = 150 - puGetStringWidth( puGetDefaultLabelFont(),
1171                                       NewNetIdLabel ) / 2;
1172
1173     NetIdDialog = new puDialogBox (150, 50);
1174     {
1175         NetIdDialogFrame   = new puFrame           (0,0,350, 150);
1176         NetIdDialogMessage = new puText            (len, 110);
1177         NetIdDialogMessage ->    setLabel          (NewNetIdLabel);
1178
1179         NetIdDialogInput   = new puInput           (50, 70, 300, 100);
1180         NetIdDialogInput   ->    setValue          (NewNetId);
1181         NetIdDialogInput   ->    acceptInput();
1182
1183         NetIdDialogOkButton     =  new puOneShot   (50, 10, 110, 50);
1184         NetIdDialogOkButton     ->     setLegend   (gui_msg_OK);
1185         NetIdDialogOkButton     ->     setCallback (NetIdDialog_OK);
1186         NetIdDialogOkButton     ->     makeReturnDefault(TRUE);
1187
1188         NetIdDialogCancelButton =  new puOneShot   (240, 10, 300, 50);
1189         NetIdDialogCancelButton ->     setLegend   (gui_msg_CANCEL);
1190         NetIdDialogCancelButton ->     setCallback (NetIdDialog_Cancel);
1191
1192     }
1193     FG_FINALIZE_PUI_DIALOG( NetIdDialog );
1194 }
1195
1196 static void net_display_toggle( puObject *cb)
1197 {
1198         net_hud_display = (net_hud_display) ? 0 : 1;
1199         printf("Toggle net_hud_display : %d\n", net_hud_display);
1200 }
1201
1202 static void net_register( puObject *cb)
1203 {
1204         fgd_send_com( "1", FGFS_host );
1205         net_is_registered = 0;
1206         printf("Registering to deamon\n");
1207 }
1208
1209 static void net_unregister( puObject *cb)
1210 {
1211         fgd_send_com( "8", FGFS_host );
1212         net_is_registered = -1;
1213         printf("Unregistering from deamon\n");
1214 }
1215
1216
1217 /*************** Deamon communication **********/
1218
1219 //  These statics should disapear when this is a class
1220 static puDialogBox     *NetFGDDialog = 0;
1221 static puFrame         *NetFGDDialogFrame = 0;
1222 static puText          *NetFGDDialogMessage = 0;
1223 //static puInput         *NetFGDDialogInput = 0;
1224
1225 //static char NewNetId[16];
1226 static char NewNetFGDLabel[] = "Scan for deamon                        "; 
1227 static char NewFGDHost[64] = "olk.mcp.de"; 
1228 static int  NewFGDPortLo = 10000;
1229 static int  NewFGDPortHi = 10001;
1230  
1231 //extern char *fgd_callsign;
1232 extern u_short base_port, end_port;
1233 extern int fgd_ip, verbose, current_port;
1234 extern char *fgd_host;
1235
1236
1237 static puOneShot       *NetFGDDialogOkButton = 0;
1238 static puOneShot       *NetFGDDialogCancelButton = 0;
1239 static puOneShot       *NetFGDDialogScanButton = 0;
1240
1241 static puInput         *NetFGDHostDialogInput = 0;
1242 static puInput         *NetFGDPortLoDialogInput = 0;
1243 static puInput         *NetFGDPortHiDialogInput = 0;
1244
1245 void NetFGDDialog_Cancel(puObject *)
1246 {
1247     FG_POP_PUI_DIALOG( NetFGDDialog );
1248 }
1249
1250 void NetFGDDialog_OK (puObject *)
1251 {
1252     char *NetFGD;    
1253
1254     bool freeze = globals->get_freeze();
1255     if(!freeze)
1256         globals->set_freeze( true );
1257     NetFGDHostDialogInput->getValue( &NetFGD );
1258     strcpy( fgd_host, NetFGD);
1259     NetFGDPortLoDialogInput->getValue( (int *) &base_port );
1260     NetFGDPortHiDialogInput->getValue( (int *) &end_port );
1261     NetFGDDialog_Cancel( NULL );
1262     if(!freeze)
1263         globals->set_freeze( false );
1264 }
1265
1266 void NetFGDDialog_SCAN (puObject *)
1267 {
1268     char *NetFGD;
1269     int fgd_port;
1270     
1271     bool freeze = globals->get_freeze();
1272     if(!freeze)
1273         globals->set_freeze( true );
1274 //    printf("Vor getvalue %s\n");
1275     NetFGDHostDialogInput->getValue( &NetFGD );
1276 //    printf("Vor strcpy %s\n", (char *) NetFGD);
1277     strcpy( fgd_host, NetFGD);
1278     NetFGDPortLoDialogInput->getValue( (int *) &base_port );
1279     NetFGDPortHiDialogInput->getValue( (int *) &end_port );
1280     printf("FGD: %s  Port-Start: %d Port-End: %d\n", fgd_host, 
1281                  base_port, end_port);
1282     net_resolv_fgd(fgd_host);
1283     printf("Resolve : %d\n", net_r);
1284     if(!freeze)
1285         globals->set_freeze( false );
1286     if ( net_r == 0 ) {
1287       fgd_port = 10000;
1288       strcpy( fgd_name, "");
1289       for( current_port = base_port; ( current_port <= end_port); current_port++) {
1290           fgd_send_com("0" , FGFS_host);
1291           sprintf( NewNetFGDLabel , "Scanning for deamon Port: %d", current_port); 
1292           printf("FGD: searching %s\n", fgd_name);
1293           if ( strcmp( fgd_name, "") != 0 ) {
1294              sprintf( NewNetFGDLabel , "Found %s at Port: %d", 
1295                                               fgd_name, current_port);
1296              fgd_port = current_port;
1297              current_port = end_port+1;
1298           }
1299       }
1300       current_port = end_port = base_port = fgd_port;
1301     }
1302     NetFGDDialog_Cancel( NULL );
1303 }
1304
1305
1306 void net_fgd_scan(puObject *cb)
1307 {
1308     NewFGDPortLo = base_port;
1309     NewFGDPortHi = end_port;
1310     strcpy( NewFGDHost, fgd_host);
1311     NetFGDPortLoDialogInput->setValue( NewFGDPortLo );
1312     NetFGDPortHiDialogInput->setValue( NewFGDPortHi );
1313     NetFGDHostDialogInput->setValue( NewFGDHost );
1314
1315     FG_PUSH_PUI_DIALOG( NetFGDDialog );
1316 }
1317
1318
1319 static void NewNetFGDInit(void)
1320 {
1321 //    sprintf( NewNetId, "%s", current_options.get_net_id().c_str() );
1322 //    sprintf( NewNetId, "%s", fgd_callsign );
1323     int len = 170 - puGetStringWidth( puGetDefaultLabelFont(),
1324                                       NewNetFGDLabel ) / 2;
1325
1326     NetFGDDialog = new puDialogBox (310, 30);
1327     {
1328         NetFGDDialogFrame   = new puFrame           (0,0,320, 170);
1329         NetFGDDialogMessage = new puText            (len, 140);
1330         NetFGDDialogMessage ->    setLabel          (NewNetFGDLabel);
1331
1332         NetFGDPortLoDialogInput   = new puInput           (50, 70, 127, 100);
1333         NetFGDPortLoDialogInput   ->    setValue          (NewFGDPortLo);
1334         NetFGDPortLoDialogInput   ->    acceptInput();
1335
1336         NetFGDPortHiDialogInput   = new puInput           (199, 70, 275, 100);
1337         NetFGDPortHiDialogInput   ->    setValue          (NewFGDPortHi);
1338         NetFGDPortHiDialogInput   ->    acceptInput();
1339
1340         NetFGDHostDialogInput   = new puInput           (50, 100, 275, 130);
1341         NetFGDHostDialogInput   ->    setValue          (NewFGDHost);
1342         NetFGDHostDialogInput   ->    acceptInput();
1343
1344         NetFGDDialogScanButton     =  new puOneShot   (130, 10, 200, 50);
1345         NetFGDDialogScanButton     ->     setLegend   ("Scan");
1346         NetFGDDialogScanButton     ->     setCallback (NetFGDDialog_SCAN);
1347         NetFGDDialogScanButton     ->     makeReturnDefault(FALSE);
1348
1349         NetFGDDialogOkButton     =  new puOneShot   (50, 10, 120, 50);
1350         NetFGDDialogOkButton     ->     setLegend   (gui_msg_OK);
1351         NetFGDDialogOkButton     ->     setCallback (NetFGDDialog_OK);
1352         NetFGDDialogOkButton     ->     makeReturnDefault(TRUE);
1353
1354         NetFGDDialogCancelButton =  new puOneShot   (210, 10, 280, 50);
1355         NetFGDDialogCancelButton ->     setLegend   (gui_msg_CANCEL);
1356         NetFGDDialogCancelButton ->     setCallback (NetFGDDialog_Cancel);
1357
1358     }
1359     FG_FINALIZE_PUI_DIALOG( NetFGDDialog );
1360 }
1361
1362 /*
1363 static void net_display_toggle( puObject *cb)
1364 {
1365         net_hud_display = (net_hud_display) ? 0 : 1;
1366         printf("Toggle net_hud_display : %d\n", net_hud_display);
1367 }
1368
1369 */
1370
1371 #endif
1372
1373 /***************  End Networking  **************/
1374
1375
1376
1377 /* -----------------------------------------------------------------------
1378 The menu stuff 
1379 ---------------------------------------------------------------------*/
1380 char *fileSubmenu               [] = {
1381     "Exit", /* "Close", "---------", */
1382 #if defined( WIN32 ) && !defined( __CYGWIN__)
1383     "Print",
1384 #endif
1385     "Snap Shot",
1386     "---------", 
1387     "Reset", 
1388     "Load flight",
1389     "Save flight",
1390     NULL
1391 };
1392 puCallback fileSubmenuCb        [] = {
1393     MayBeGoodBye, /* hideMenuCb, NULL, */
1394 #if defined( WIN32 ) && !defined( __CYGWIN__)
1395     printScreen, 
1396 #endif
1397     /* NULL, notCb, */
1398     dumpSnapShot,
1399     NULL,
1400     reInit, 
1401     loadFlight,
1402     saveFlight,
1403     NULL
1404 };
1405
1406 /*
1407 char *editSubmenu               [] = {
1408     "Edit text", NULL
1409 };
1410 puCallback editSubmenuCb        [] = {
1411     notCb, NULL
1412 };
1413 */
1414
1415 extern void fgHUDalphaAdjust( puObject * );
1416 char *viewSubmenu               [] = {
1417     "HUD Alpha",
1418     /* "Cockpit View > ", "View >","------------", */
1419     "Toggle Panel...", NULL
1420 };
1421 puCallback viewSubmenuCb        [] = {
1422     fgHUDalphaAdjust,
1423     /* notCb, notCb, NULL, */
1424     guiTogglePanel, NULL
1425 };
1426
1427 char *aircraftSubmenu           [] = {
1428     "Autopilot", "Heading", "Altitude", "Navigation", "Airport", 
1429     /* "Communication", */ NULL
1430 };
1431 puCallback aircraftSubmenuCb    [] = {
1432     fgAPAdjust, NewHeading, NewAltitude, fgLatLonFormatToggle, NewTgtAirport, 
1433     /* notCb, */ NULL
1434 };
1435
1436 char *environmentSubmenu        [] = {
1437     "Toggle Clouds",
1438     "Goto Airport", /* "Terrain", "Weather", */ NULL
1439 };
1440 puCallback environmentSubmenuCb [] = {
1441     toggleClouds,
1442     NewAirport, /* notCb, notCb, */ NULL
1443 };
1444
1445 /*
1446 char *optionsSubmenu            [] = {
1447     "Preferences", "Realism & Reliablity...", NULL
1448 };
1449 puCallback optionsSubmenuCb     [] = {
1450     notCb, notCb, NULL
1451 };
1452 */
1453
1454 #ifdef FG_NETWORK_OLK
1455 char *networkSubmenu            [] = {
1456     "Unregister from FGD ", /* "Send MSG to All", "Send MSG", "Show Pilots", */
1457     "Register to FGD",
1458     "Scan for Deamons", "Enter Callsign", /* "Display Netinfos", */
1459     "Toggle Display", NULL
1460 };
1461 puCallback networkSubmenuCb     [] = {
1462     /* notCb, notCb, notCb, notCb, */ 
1463     net_unregister, 
1464     net_register, 
1465     net_fgd_scan, NewCallSign, 
1466     net_display_toggle, NULL
1467 };
1468 #endif
1469
1470 char *helpSubmenu               [] = {
1471     /* "About...", */ "Help", NULL
1472 };
1473 puCallback helpSubmenuCb        [] = {
1474     /* notCb, */ helpCb, NULL
1475 };
1476
1477
1478 /* -------------------------------------------------------------------------
1479 init the gui
1480 _____________________________________________________________________*/
1481
1482
1483 void guiInit()
1484 {
1485     char *mesa_win_state;
1486
1487     // Initialize PUI
1488     puInit();
1489     puSetDefaultStyle         ( PUSTYLE_SMALL_BEVELLED ); //PUSTYLE_DEFAULT
1490     puSetDefaultColourScheme  (0.8, 0.8, 0.8, 0.4);
1491
1492     // Initialize our GLOBAL GUI STRINGS
1493     gui_msg_OK     = msg_OK;     // "OK"
1494     gui_msg_NO     = msg_NO;     // "NO"
1495     gui_msg_YES    = msg_YES;    // "YES"
1496     gui_msg_CANCEL = msg_CANCEL; // "CANCEL"
1497     gui_msg_RESET  = msg_RESET;  // "RESET"
1498
1499     // Next check home directory
1500     FGPath fntpath;
1501     char* envp = ::getenv( "FG_FONTS" );
1502     if ( envp != NULL ) {
1503         fntpath.set( envp );
1504     } else {
1505         fntpath.set( current_options.get_fg_root() );
1506         fntpath.append( "Fonts" );
1507     }
1508
1509     // Install our fast fonts
1510     fntpath.append( "typewriter.txf" );
1511     guiFntHandle = new fntTexFont ;
1512     guiFntHandle -> load ( (char *)fntpath.c_str() ) ;
1513     puFont GuiFont ( guiFntHandle, 15 ) ;
1514     puSetDefaultFonts( GuiFont, GuiFont ) ;
1515     guiFnt = puGetDefaultLabelFont();
1516   
1517     if ( current_options.get_mouse_pointer() == 0 ) {
1518         // no preference specified for mouse pointer, attempt to autodetect...
1519         // Determine if we need to render the cursor, or if the windowing
1520         // system will do it.  First test if we are rendering with glide.
1521         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1522             // Test for the MESA_GLX_FX env variable
1523             if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1524                 // test if we are fullscreen mesa/glide
1525                 if ( (mesa_win_state[0] == 'f') ||
1526                      (mesa_win_state[0] == 'F') ) {
1527                     puShowCursor ();
1528                 }
1529             }
1530         }
1531         mouse_active = ~mouse_active;
1532     } else if ( current_options.get_mouse_pointer() == 1 ) {
1533         // don't show pointer
1534     } else if ( current_options.get_mouse_pointer() == 2 ) {
1535         // force showing pointer
1536         puShowCursor();
1537         mouse_active = ~mouse_active;
1538     }
1539         
1540     // MOUSE_VIEW mode stuff
1541     trackball(_quat0, 0.0, 0.0, 0.0, 0.0);  
1542     Quat0();
1543     build_rotmatrix(quat_mat, curquat);
1544
1545     // Set up our Dialog Boxes
1546     ConfirmExitDialogInit();
1547     NewAirportInit();
1548 #ifdef FG_NETWORK_OLK
1549     NewNetIdInit();
1550     NewNetFGDInit();
1551 #endif
1552     mkDialogInit();
1553     
1554     // Make the menu bar
1555     mainMenuBar = new puMenuBar ();
1556     mainMenuBar -> add_submenu ("File", fileSubmenu, fileSubmenuCb);
1557     // mainMenuBar -> add_submenu ("Edit", editSubmenu, editSubmenuCb);
1558     mainMenuBar -> add_submenu ("View", viewSubmenu, viewSubmenuCb);
1559     mainMenuBar -> add_submenu ("Aircraft", aircraftSubmenu, aircraftSubmenuCb);
1560     mainMenuBar -> add_submenu ("Environment", environmentSubmenu, environmentSubmenuCb);
1561     // mainMenuBar -> add_submenu ("Options", optionsSubmenu, optionsSubmenuCb);
1562 #ifdef FG_NETWORK_OLK
1563     if ( current_options.get_network_olk() ) {
1564         mainMenuBar -> add_submenu ("Network", networkSubmenu, networkSubmenuCb);
1565     }
1566 #endif
1567     mainMenuBar -> add_submenu ("Help", helpSubmenu, helpSubmenuCb);
1568     mainMenuBar-> close ();
1569     // Set up menu bar toggle
1570     menu_on = ~0;
1571 }
1572
1573
1574
1575 /*
1576  * Trackball code:
1577  *
1578  * Implementation of a virtual trackball.
1579  * Implemented by Gavin Bell, lots of ideas from Thant Tessman and
1580  *   the August '88 issue of Siggraph's "Computer Graphics," pp. 121-129.
1581  *
1582  * Vector manip code:
1583  *
1584  * Original code from:
1585  * David M. Ciemiewicz, Mark Grossman, Henry Moreton, and Paul Haeberli
1586  *
1587  * Much mucking with by:
1588  * Gavin Bell
1589  */
1590 #if defined(_WIN32) && !defined( __CYGWIN32__ )
1591 #pragma warning (disable:4244)          /* disable bogus conversion warnings */
1592 #endif
1593 #include <math.h>
1594 #include <stdio.h>
1595 //#include "trackball.h"
1596
1597 /*
1598  * This size should really be based on the distance from the center of
1599  * rotation to the point on the object underneath the mouse.  That
1600  * point would then track the mouse as closely as possible.  This is a
1601  * simple example, though, so that is left as an Exercise for the
1602  * Programmer.
1603  */
1604 #define TRACKBALLSIZE  (0.8f)
1605 #define SQRT(x) sqrt(x)
1606
1607 /*
1608  * Local function prototypes (not defined in trackball.h)
1609  */
1610 static float tb_project_to_sphere(float, float, float);
1611 static void normalize_quat(float [4]);
1612
1613 static void
1614 vzero(float *v)
1615 {
1616     v[0] = 0.0;
1617     v[1] = 0.0;
1618     v[2] = 0.0;
1619 }
1620
1621 static void
1622 vset(float *v, float x, float y, float z)
1623 {
1624     v[0] = x;
1625     v[1] = y;
1626     v[2] = z;
1627 }
1628
1629 static void
1630 vsub(const float *src1, const float *src2, float *dst)
1631 {
1632     dst[0] = src1[0] - src2[0];
1633     dst[1] = src1[1] - src2[1];
1634     dst[2] = src1[2] - src2[2];
1635 }
1636
1637 static void
1638 vcopy(const float *v1, float *v2)
1639 {
1640     register int i;
1641     for (i = 0 ; i < 3 ; i++)
1642         v2[i] = v1[i];
1643 }
1644
1645 static void
1646 vcross(const float *v1, const float *v2, float *cross)
1647 {
1648     float temp[3];
1649
1650     temp[0] = (v1[1] * v2[2]) - (v1[2] * v2[1]);
1651     temp[1] = (v1[2] * v2[0]) - (v1[0] * v2[2]);
1652     temp[2] = (v1[0] * v2[1]) - (v1[1] * v2[0]);
1653     vcopy(temp, cross);
1654 }
1655
1656 static float
1657 vlength(const float *v)
1658 {
1659     float tmp = v[0] * v[0] + v[1] * v[1] + v[2] * v[2];
1660     return SQRT(tmp);
1661 }
1662
1663 static void
1664 vscale(float *v, float div)
1665 {
1666     v[0] *= div;
1667     v[1] *= div;
1668     v[2] *= div;
1669 }
1670
1671 static void
1672 vnormal(float *v)
1673 {
1674     vscale(v,1.0/vlength(v));
1675 }
1676
1677 static float
1678 vdot(const float *v1, const float *v2)
1679 {
1680     return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
1681 }
1682
1683 static void
1684 vadd(const float *src1, const float *src2, float *dst)
1685 {
1686     dst[0] = src1[0] + src2[0];
1687     dst[1] = src1[1] + src2[1];
1688     dst[2] = src1[2] + src2[2];
1689 }
1690
1691 /*
1692  *  Given an axis and angle, compute quaternion.
1693  */
1694 void
1695 axis_to_quat(float a[3], float phi, float q[4])
1696 {
1697     double sinphi2, cosphi2;
1698     double phi2 = phi/2.0;
1699     sinphi2 = sin(phi2);
1700     cosphi2 = cos(phi2);
1701     vnormal(a);
1702     vcopy(a,q);
1703     vscale(q,sinphi2);
1704     q[3] = cosphi2;
1705 }
1706
1707 /*
1708  * Project an x,y pair onto a sphere of radius r OR a hyperbolic sheet
1709  * if we are away from the center of the sphere.
1710  */
1711 static float
1712 tb_project_to_sphere(float r, float x, float y)
1713 {
1714     float d, t, z, tmp;
1715
1716     tmp = x*x + y*y;
1717     d = SQRT(tmp);
1718     if (d < r * 0.70710678118654752440) {    /* Inside sphere */
1719         tmp = r*r - d*d;
1720         z = SQRT(tmp);
1721     } else {           /* On hyperbola */
1722         t = r / 1.41421356237309504880;
1723         z = t*t / d;
1724     }
1725     return z;
1726 }
1727
1728 /*
1729  * Quaternions always obey:  a^2 + b^2 + c^2 + d^2 = 1.0
1730  * If they don't add up to 1.0, dividing by their magnitued will
1731  * renormalize them.
1732  *
1733  * Note: See the following for more information on quaternions:
1734  *
1735  * - Shoemake, K., Animating rotation with quaternion curves, Computer
1736  *   Graphics 19, No 3 (Proc. SIGGRAPH'85), 245-254, 1985.
1737  * - Pletinckx, D., Quaternion calculus as a basic tool in computer
1738  *   graphics, The Visual Computer 5, 2-13, 1989.
1739  */
1740 static void
1741 normalize_quat(float q[4])
1742 {
1743     int i;
1744     float mag, tmp;
1745
1746     tmp = q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3];
1747     mag = 1.0 / SQRT(tmp);
1748     for (i = 0; i < 4; i++)
1749         q[i] *= mag;
1750 }
1751
1752 /*
1753  * Ok, simulate a track-ball.  Project the points onto the virtual
1754  * trackball, then figure out the axis of rotation, which is the cross
1755  * product of P1 P2 and O P1 (O is the center of the ball, 0,0,0)
1756  * Note:  This is a deformed trackball-- is a trackball in the center,
1757  * but is deformed into a hyperbolic sheet of rotation away from the
1758  * center.  This particular function was chosen after trying out
1759  * several variations.
1760  *
1761  * It is assumed that the arguments to this routine are in the range
1762  * (-1.0 ... 1.0)
1763  */
1764 void
1765 trackball(float q[4], float p1x, float p1y, float p2x, float p2y)
1766 {
1767     float a[3]; /* Axis of rotation */
1768     float phi;  /* how much to rotate about axis */
1769     float p1[3], p2[3], d[3];
1770     float t;
1771
1772     if (p1x == p2x && p1y == p2y) {
1773         /* Zero rotation */
1774         vzero(q);
1775         q[3] = 1.0;
1776         return;
1777     }
1778
1779     /*
1780      * First, figure out z-coordinates for projection of P1 and P2 to
1781      * deformed sphere
1782      */
1783     vset(p1,p1x,p1y,tb_project_to_sphere(TRACKBALLSIZE,p1x,p1y));
1784     vset(p2,p2x,p2y,tb_project_to_sphere(TRACKBALLSIZE,p2x,p2y));
1785
1786     /*
1787      *  Now, we want the cross product of P1 and P2
1788      */
1789     vcross(p2,p1,a);
1790
1791     /*
1792      *  Figure out how much to rotate around that axis.
1793      */
1794     vsub(p1,p2,d);
1795     t = vlength(d) / (2.0*TRACKBALLSIZE);
1796
1797     /*
1798      * Avoid problems with out-of-control values...
1799      */
1800     if (t > 1.0) t = 1.0;
1801     if (t < -1.0) t = -1.0;
1802     phi = 2.0 * asin(t);
1803
1804     axis_to_quat(a,phi,q);
1805 }
1806
1807 /*
1808  * Given two rotations, e1 and e2, expressed as quaternion rotations,
1809  * figure out the equivalent single rotation and stuff it into dest.
1810  *
1811  * This routine also normalizes the result every RENORMCOUNT times it is
1812  * called, to keep error from creeping in.
1813  *
1814  * NOTE: This routine is written so that q1 or q2 may be the same
1815  * as dest (or each other).
1816  */
1817
1818 #define RENORMCOUNT 97
1819
1820 void
1821 add_quats(float q1[4], float q2[4], float dest[4])
1822 {
1823     static int count=0;
1824     float t1[4], t2[4], t3[4];
1825     float tf[4];
1826
1827 #if 0
1828 printf("q1 = %f %f %f %f\n", q1[0], q1[1], q1[2], q1[3]);
1829 printf("q2 = %f %f %f %f\n", q2[0], q2[1], q2[2], q2[3]);
1830 #endif
1831
1832     vcopy(q1,t1);
1833     vscale(t1,q2[3]);
1834
1835     vcopy(q2,t2);
1836     vscale(t2,q1[3]);
1837
1838     vcross(q2,q1,t3);
1839     vadd(t1,t2,tf);
1840     vadd(t3,tf,tf);
1841     tf[3] = q1[3] * q2[3] - vdot(q1,q2);
1842
1843 #if 0
1844 printf("tf = %f %f %f %f\n", tf[0], tf[1], tf[2], tf[3]);
1845 #endif
1846
1847     dest[0] = tf[0];
1848     dest[1] = tf[1];
1849     dest[2] = tf[2];
1850     dest[3] = tf[3];
1851
1852     if (++count > RENORMCOUNT) {
1853         count = 0;
1854         normalize_quat(dest);
1855     }
1856 }
1857
1858 /*
1859  * Build a rotation matrix, given a quaternion rotation.
1860  *
1861  */
1862 void
1863 build_rotmatrix(float m[4][4], float q[4])
1864 {
1865 //#define TRANSPOSED_QUAT
1866 #ifndef TRANSPOSED_QUAT
1867     m[0][0] = 1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2]);
1868     m[0][1] = 2.0 * (q[0] * q[1] - q[2] * q[3]);
1869     m[0][2] = 2.0 * (q[2] * q[0] + q[1] * q[3]);
1870     m[0][3] = 0.0;
1871
1872     m[1][0] = 2.0 * (q[0] * q[1] + q[2] * q[3]);
1873     m[1][1]= 1.0 - 2.0 * (q[2] * q[2] + q[0] * q[0]);
1874     m[1][2] = 2.0 * (q[1] * q[2] - q[0] * q[3]);
1875     m[1][3] = 0.0;
1876
1877     m[2][0] = 2.0 * (q[2] * q[0] - q[1] * q[3]);
1878     m[2][1] = 2.0 * (q[1] * q[2] + q[0] * q[3]);
1879     m[2][2] = 1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0]);
1880     
1881     m[2][3] = 0.0;
1882     m[3][0] = 0.0;
1883     m[3][1] = 0.0;
1884     m[3][2] = 0.0;
1885     m[3][3] = 1.0;
1886 #else //  TRANSPOSED_QUAT
1887     m[0][0] = 1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2]);
1888     m[0][1] = 2.0 * (q[0] * q[1] + q[2] * q[3]);
1889     m[0][2] = 2.0 * (q[2] * q[0] - q[1] * q[3]);
1890     m[0][3] = 0.0;
1891
1892     m[1][0] = 2.0 * (q[0] * q[1] - q[2] * q[3]);
1893     m[1][1] = 1.0 - 2.0 * (q[2] * q[2] + q[0] * q[0]);
1894     m[1][2] = 2.0 * (q[1] * q[2] + q[0] * q[3]);
1895     m[1][3] = 0.0;
1896
1897     m[2][0] = 2.0 * (q[2] * q[0] + q[1] * q[3]);
1898     m[2][1] = 2.0 * (q[1] * q[2] - q[0] * q[3]);
1899     m[2][2] = 1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0]);
1900     m[2][3] = 0.0;
1901     
1902     m[3][0] = 0.0;
1903     m[3][1] = 0.0;
1904     m[3][2] = 0.0;
1905     m[3][3] = 1.0;
1906 #endif // 0
1907 }
1908