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