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