]> git.mxchange.org Git - flightgear.git/blob - src/Cockpit/panel.cxx
Merge commit 'refs/merge-requests/1551' of git://gitorious.org/fg/flightgear into...
[flightgear.git] / src / Cockpit / panel.cxx
1 //  panel.cxx - default, 2D single-engine prop instrument panel
2 //
3 //  Written by David Megginson, started January 2000.
4 //
5 //  This program is free software; you can redistribute it and/or
6 //  modify it under the terms of the GNU General Public License as
7 //  published by the Free Software Foundation; either version 2 of the
8 //  License, or (at your option) any later version.
9 // 
10 //  This program is distributed in the hope that it will be useful, but
11 //  WITHOUT ANY WARRANTY; without even the implied warranty of
12 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 //  General Public License for more details.
14 //
15 //  You should have received a copy of the GNU General Public License
16 //  along with this program; if not, write to the Free Software
17 //  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 //
19 //  $Id$
20
21 //JVK
22 // On 2D panels all instruments include light sources were in night displayed
23 // with a red mask (instrument light). It is not correct for light sources
24 // (bulbs). There is added new layer property "emissive" (boolean) (only for
25 // textured layers).
26 // If a layer has to shine set it in the "instrument_def_file.xml" inside the
27 // <layer> tag by adding <emissive>true</emissive> tag. When omitted the default
28 // value is for backward compatibility set to false.
29
30 #ifdef HAVE_CONFIG_H
31 #  include <config.h>
32 #endif
33
34 #include "panel.hxx"
35
36 #include <stdio.h>      // sprintf
37 #include <string.h>
38 #include <iostream>
39
40 #include <osg/CullFace>
41 #include <osg/Depth>
42 #include <osg/Material>
43 #include <osg/TexEnv>
44 #include <osg/PolygonOffset>
45
46 #include <simgear/compiler.h>
47
48 #include <plib/fnt.h>
49
50 #include <simgear/debug/logstream.hxx>
51 #include <simgear/misc/sg_path.hxx>
52 #include <simgear/scene/model/model.hxx>
53 #include <osg/GLU>
54
55 #include <Main/globals.hxx>
56 #include <Main/fg_props.hxx>
57 #include <Main/viewmgr.hxx>
58 #include <Time/light.hxx>
59 #include <GUI/new_gui.hxx>      // FGFontCache
60 #include <Main/viewer.hxx>
61 #include <Instrumentation/dclgps.hxx>
62
63 #include "hud.hxx"
64
65
66 #define WIN_X 0
67 #define WIN_Y 0
68 #define WIN_W 1024
69 #define WIN_H 768
70
71 // The number of polygon-offset "units" to place between layers.  In
72 // principle, one is supposed to be enough.  In practice, I find that
73 // my hardware/driver requires many more.
74 #define POFF_UNITS 8
75
76 ////////////////////////////////////////////////////////////////////////
77 // Local functions.
78 ////////////////////////////////////////////////////////////////////////
79
80
81 /**
82  * Calculate the aspect adjustment for the panel.
83  */
84 static float
85 get_aspect_adjust (int xsize, int ysize)
86 {
87   float ideal_aspect = float(WIN_W) / float(WIN_H);
88   float real_aspect = float(xsize) / float(ysize);
89   return (real_aspect / ideal_aspect);
90 }
91
92
93 \f
94 ////////////////////////////////////////////////////////////////////////
95 // Global functions.
96 ////////////////////////////////////////////////////////////////////////
97
98 bool
99 fgPanelVisible ()
100 {
101      const FGPanel* current = globals->get_current_panel();
102      if (current == 0)
103         return false;
104      if (current->getVisibility() == 0)
105         return false;
106      if (globals->get_viewmgr()->get_current() != 0)
107         return false;
108      if (current->getAutohide() && globals->get_current_view()->getHeadingOffset_deg() * SGD_DEGREES_TO_RADIANS != 0)
109         return false;
110      return true;
111 }
112
113 \f
114 ////////////////////////////////////////////////////////////////////////
115 // Implementation of FGTextureManager.
116 ////////////////////////////////////////////////////////////////////////
117
118 map<string,osg::ref_ptr<osg::Texture2D> > FGTextureManager::_textureMap;
119
120 osg::Texture2D*
121 FGTextureManager::createTexture (const string &relativePath, bool staticTexture)
122 {
123   osg::Texture2D* texture = _textureMap[relativePath].get();
124   if (texture == 0) {
125     SGPath tpath = globals->resolve_aircraft_path(relativePath);
126     texture = SGLoadTexture2D(staticTexture, tpath);
127
128     _textureMap[relativePath] = texture;
129     if (!_textureMap[relativePath].valid()) 
130       SG_LOG( SG_COCKPIT, SG_ALERT, "Texture *still* doesn't exist" );
131     SG_LOG( SG_COCKPIT, SG_DEBUG, "Created texture " << relativePath );
132   }
133
134   return texture;
135 }
136
137
138 void FGTextureManager::addTexture(const string &relativePath,
139                                   osg::Texture2D* texture)
140 {
141     _textureMap[relativePath] = texture;
142 }
143 \f
144 ////////////////////////////////////////////////////////////////////////
145 // Implementation of FGCropped Texture.
146 ////////////////////////////////////////////////////////////////////////
147
148
149 FGCroppedTexture::FGCroppedTexture ()
150   : _path(""), _texture(0),
151     _minX(0.0), _minY(0.0), _maxX(1.0), _maxY(1.0)
152 {
153 }
154
155
156 FGCroppedTexture::FGCroppedTexture (const string &path,
157                                     float minX, float minY,
158                                     float maxX, float maxY)
159   : _path(path), _texture(0),
160     _minX(minX), _minY(minY), _maxX(maxX), _maxY(maxY)
161 {
162 }
163
164
165 FGCroppedTexture::~FGCroppedTexture ()
166 {
167 }
168
169
170 osg::StateSet*
171 FGCroppedTexture::getTexture ()
172 {
173   if (_texture == 0) {
174     _texture = new osg::StateSet;
175     _texture->setTextureAttribute(0, FGTextureManager::createTexture(_path));
176     _texture->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
177     _texture->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
178   }
179   return _texture.get();
180 }
181
182
183 \f
184 ////////////////////////////////////////////////////////////////////////
185 // Implementation of FGPanel.
186 ////////////////////////////////////////////////////////////////////////
187
188 static fntRenderer text_renderer;
189 static sgVec4 panel_color;
190 static sgVec4 emissive_panel_color = {1,1,1,1};
191
192 /**
193  * Constructor.
194  */
195 FGPanel::FGPanel ()
196   : _mouseDown(false),
197     _mouseInstrument(0),
198     _width(WIN_W), _height(int(WIN_H * 0.5768 + 1)),
199     _view_height(int(WIN_H * 0.4232)),
200     _visibility(fgGetNode("/sim/panel/visibility", true)),
201     _x_offset(fgGetNode("/sim/panel/x-offset", true)),
202     _y_offset(fgGetNode("/sim/panel/y-offset", true)),
203     _jitter(fgGetNode("/sim/panel/jitter", true)),
204     _flipx(fgGetNode("/sim/panel/flip-x", true)),
205     _xsize_node(fgGetNode("/sim/startup/xsize", true)),
206     _ysize_node(fgGetNode("/sim/startup/ysize", true)),
207     _enable_depth_test(false)
208 {
209 }
210
211
212 /**
213  * Destructor.
214  */
215 FGPanel::~FGPanel ()
216 {
217   for (instrument_list_type::iterator it = _instruments.begin();
218        it != _instruments.end();
219        it++) {
220     delete *it;
221     *it = 0;
222   }
223 }
224
225
226 /**
227  * Add an instrument to the panel.
228  */
229 void
230 FGPanel::addInstrument (FGPanelInstrument * instrument)
231 {
232   _instruments.push_back(instrument);
233 }
234
235
236 /**
237  * Initialize the panel.
238  */
239 void
240 FGPanel::init ()
241 {
242 }
243
244
245 /**
246  * Bind panel properties.
247  */
248 void
249 FGPanel::bind ()
250 {
251   fgSetArchivable("/sim/panel/visibility");
252   fgSetArchivable("/sim/panel/x-offset");
253   fgSetArchivable("/sim/panel/y-offset");
254   fgSetArchivable("/sim/panel/jitter");
255 }
256
257
258 /**
259  * Unbind panel properties.
260  */
261 void
262 FGPanel::unbind ()
263 {
264 }
265
266
267 void
268 FGPanel::update (double dt)
269 {
270   std::cout << "OSGFIXME" << std::endl;
271 }
272
273 void
274 FGPanel::update (osg::State& state, GLfloat winx, GLfloat winw, GLfloat winy, GLfloat winh)
275 {
276                                // Calculate accelerations
277                                // and jiggle the panel accordingly
278                                // The factors and bounds are just
279                                // initial guesses; using sqrt smooths
280                                // out the spikes.
281   double x_offset = _x_offset->getIntValue();
282   double y_offset = _y_offset->getIntValue();
283
284
285   glMatrixMode(GL_PROJECTION);
286   glPushMatrix();
287   glLoadIdentity();
288   if ( _flipx->getBoolValue() ) {
289     gluOrtho2D(winx + winw, winx, winy + winh, winy); /* up side down */
290   } else {
291     gluOrtho2D(winx, winx + winw, winy, winy + winh); /* right side up */
292   }
293   
294   glMatrixMode(GL_MODELVIEW);
295   glPushMatrix();
296   glLoadIdentity();
297   
298   glTranslated(x_offset, y_offset, 0);
299   
300   draw(state);
301
302   glMatrixMode(GL_PROJECTION);
303   glPopMatrix();
304   glMatrixMode(GL_MODELVIEW);
305   glPopMatrix();
306 }
307
308 /**
309  * Update the panel.
310  */
311 void
312 FGPanel::update (osg::State& state)
313 {
314                                 // Do nothing if the panel isn't visible.
315     if ( !fgPanelVisible() ) {
316         return;
317     }
318
319     updateMouseDelay();
320
321                                 // Now, draw the panel
322     float aspect_adjust = get_aspect_adjust(_xsize_node->getIntValue(),
323                                             _ysize_node->getIntValue());
324     if (aspect_adjust <1.0)
325         update(state, WIN_X, int(WIN_W * aspect_adjust), WIN_Y, WIN_H);
326     else
327         update(state, WIN_X, WIN_W, WIN_Y, int(WIN_H / aspect_adjust));
328 }
329
330 /**
331  * Handle repeatable mouse events.  Called from update() and from
332  * fgUpdate3DPanels().  This functionality needs to move into the
333  * input subsystem.  Counting a tick every two frames is clumsy...
334  */
335 void FGPanel::updateMouseDelay()
336 {
337     if (_mouseDown) {
338         _mouseDelay--;
339         if (_mouseDelay < 0) {
340             _mouseInstrument->doMouseAction(_mouseButton, 0, _mouseX, _mouseY);
341             _mouseDelay = 2;
342         }
343     }
344 }
345
346
347 void
348 FGPanel::draw(osg::State& state)
349 {
350   // In 3D mode, it's possible that we are being drawn exactly on top
351   // of an existing polygon.  Use an offset to prevent z-fighting.  In
352   // 2D mode, this is a no-op.
353   static osg::ref_ptr<osg::StateSet> panelStateSet;
354   if (!panelStateSet.valid()) {
355     panelStateSet = new osg::StateSet;
356     panelStateSet->setAttributeAndModes(new osg::PolygonOffset(-1, -POFF_UNITS));
357     panelStateSet->setTextureAttribute(0, new osg::TexEnv);
358
359     // Draw the background
360     panelStateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
361     panelStateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
362     panelStateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
363     panelStateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
364     osg::Material* material = new osg::Material;
365     material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
366     material->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1));
367     material->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1));
368     material->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
369     material->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
370     panelStateSet->setAttribute(material);
371     panelStateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
372     panelStateSet->setAttributeAndModes(new osg::CullFace(osg::CullFace::BACK));
373     panelStateSet->setAttributeAndModes(new osg::Depth(osg::Depth::LEQUAL));
374   }
375   if ( _enable_depth_test )
376     panelStateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
377   else
378     panelStateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
379   state.pushStateSet(panelStateSet.get());
380   state.apply();
381   state.setActiveTextureUnit(0);
382   state.setClientActiveTextureUnit(0);
383
384   FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
385   sgCopyVec4( panel_color, l->scene_diffuse().data());
386   if ( fgGetDouble("/systems/electrical/outputs/instrument-lights") > 1.0 ) {
387       if ( panel_color[0] < 0.7 ) panel_color[0] = 0.7;
388       if ( panel_color[1] < 0.2 ) panel_color[1] = 0.2;
389       if ( panel_color[2] < 0.2 ) panel_color[2] = 0.2;
390   }
391   glColor4fv( panel_color );
392   if (_bg != 0) {
393     state.pushStateSet(_bg.get());
394     state.apply();
395     state.setActiveTextureUnit(0);
396     state.setClientActiveTextureUnit(0);
397
398     glBegin(GL_POLYGON);
399     glTexCoord2f(0.0, 0.0); glVertex2f(WIN_X, WIN_Y);
400     glTexCoord2f(1.0, 0.0); glVertex2f(WIN_X + _width, WIN_Y);
401     glTexCoord2f(1.0, 1.0); glVertex2f(WIN_X + _width, WIN_Y + _height);
402     glTexCoord2f(0.0, 1.0); glVertex2f(WIN_X, WIN_Y + _height);
403     glEnd();
404     state.popStateSet();
405     state.apply();
406     state.setActiveTextureUnit(0);
407     state.setClientActiveTextureUnit(0);
408
409   } else {
410     for (int i = 0; i < 4; i ++) {
411       // top row of textures...(1,3,5,7)
412       state.pushStateSet(_mbg[i*2].get());
413       state.apply();
414       state.setActiveTextureUnit(0);
415       state.setClientActiveTextureUnit(0);
416
417       glBegin(GL_POLYGON);
418       glTexCoord2f(0.0, 0.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y + (_height/2));
419       glTexCoord2f(1.0, 0.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y + (_height/2));
420       glTexCoord2f(1.0, 1.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y + _height);
421       glTexCoord2f(0.0, 1.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y + _height);
422       glEnd();
423       state.popStateSet();
424       state.apply();
425       state.setActiveTextureUnit(0);
426       state.setClientActiveTextureUnit(0);
427
428       // bottom row of textures...(2,4,6,8)
429       state.pushStateSet(_mbg[i*2+1].get());
430       state.apply();
431       state.setActiveTextureUnit(0);
432       state.setClientActiveTextureUnit(0);
433
434       glBegin(GL_POLYGON);
435       glTexCoord2f(0.0, 0.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y);
436       glTexCoord2f(1.0, 0.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y);
437       glTexCoord2f(1.0, 1.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y + (_height/2));
438       glTexCoord2f(0.0, 1.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y + (_height/2));
439       glEnd();
440       state.popStateSet();
441       state.apply();
442       state.setActiveTextureUnit(0);
443       state.setClientActiveTextureUnit(0);
444
445     }
446   }
447
448   // Draw the instruments.
449   // Syd Adams: added instrument clipping
450   instrument_list_type::const_iterator current = _instruments.begin();
451   instrument_list_type::const_iterator end = _instruments.end();
452
453   GLdouble blx[4]={1.0,0.0,0.0,0.0};
454   GLdouble bly[4]={0.0,1.0,0.0,0.0};
455   GLdouble urx[4]={-1.0,0.0,0.0,0.0};
456   GLdouble ury[4]={0.0,-1.0,0.0,0.0};
457
458   for ( ; current != end; current++) {
459     FGPanelInstrument * instr = *current;
460     glPushMatrix();
461     glTranslated(instr->getXPos(), instr->getYPos(), 0);
462
463     int ix= instr->getWidth();
464     int iy= instr->getHeight();
465     glPushMatrix();
466     glTranslated(-ix/2,-iy/2,0);
467     glClipPlane(GL_CLIP_PLANE0,blx);
468     glClipPlane(GL_CLIP_PLANE1,bly);
469     glEnable(GL_CLIP_PLANE0);
470     glEnable(GL_CLIP_PLANE1);
471
472     glTranslated(ix,iy,0);
473     glClipPlane(GL_CLIP_PLANE2,urx);
474     glClipPlane(GL_CLIP_PLANE3,ury);
475     glEnable(GL_CLIP_PLANE2);
476     glEnable(GL_CLIP_PLANE3);
477     glPopMatrix();
478     instr->draw(state);
479
480     glPopMatrix();
481   }
482
483   glDisable(GL_CLIP_PLANE0);
484   glDisable(GL_CLIP_PLANE1);
485   glDisable(GL_CLIP_PLANE2);
486   glDisable(GL_CLIP_PLANE3);
487
488   state.popStateSet();
489   state.apply();
490   state.setActiveTextureUnit(0);
491   state.setClientActiveTextureUnit(0);
492
493
494   // Draw yellow "hotspots" if directed to.  This is a panel authoring
495   // feature; not intended to be high performance or to look good.
496   if ( fgGetBool("/sim/panel-hotspots") ) {
497     static osg::ref_ptr<osg::StateSet> hotspotStateSet;
498     if (!hotspotStateSet.valid()) {
499       hotspotStateSet = new osg::StateSet;
500       hotspotStateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
501       hotspotStateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
502     }
503
504     state.pushStateSet(hotspotStateSet.get());
505     state.apply();
506     state.setActiveTextureUnit(0);
507     state.setClientActiveTextureUnit(0);
508
509
510     glPushAttrib(GL_ENABLE_BIT);
511     glDisable(GL_COLOR_MATERIAL);
512     glColor3f(1, 1, 0);
513     
514     for ( unsigned int i = 0; i < _instruments.size(); i++ )
515       _instruments[i]->drawHotspots(state);
516
517     glPopAttrib();
518
519     state.popStateSet();
520     state.apply();
521     state.setActiveTextureUnit(0);
522     state.setClientActiveTextureUnit(0);
523
524   }
525 }
526
527 /**
528  * Set the panel's visibility.
529  */
530 void
531 FGPanel::setVisibility (bool visibility)
532 {
533   _visibility->setBoolValue( visibility );
534 }
535
536
537 /**
538  * Return true if the panel is visible.
539  */
540 bool
541 FGPanel::getVisibility () const
542 {
543   return _visibility->getBoolValue();
544 }
545
546
547 /**
548  * Set the panel's background texture.
549  */
550 void
551 FGPanel::setBackground (osg::Texture2D* texture)
552 {
553   osg::StateSet* stateSet = new osg::StateSet;
554   stateSet->setTextureAttribute(0, texture);
555   stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
556   stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
557   _bg = stateSet;
558 }
559
560 /**
561  * Set the panel's multiple background textures.
562  */
563 void
564 FGPanel::setMultiBackground (osg::Texture2D* texture, int idx)
565 {
566   _bg = 0;
567
568   osg::StateSet* stateSet = new osg::StateSet;
569   stateSet->setTextureAttribute(0, texture);
570   stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
571   stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
572   _mbg[idx] = stateSet;
573 }
574
575 /**
576  * Set the panel's x-offset.
577  */
578 void
579 FGPanel::setXOffset (int offset)
580 {
581   if (offset <= 0 && offset >= -_width + WIN_W)
582     _x_offset->setIntValue( offset );
583 }
584
585
586 /**
587  * Set the panel's y-offset.
588  */
589 void
590 FGPanel::setYOffset (int offset)
591 {
592   if (offset <= 0 && offset >= -_height)
593     _y_offset->setIntValue( offset );
594 }
595
596 /**
597  * Handle a mouse action in panel-local (not screen) coordinates.
598  * Used by the 3D panel code in Model/panelnode.cxx, in situations
599  * where the panel doesn't control its own screen location.
600  */
601 bool
602 FGPanel::doLocalMouseAction(int button, int updown, int x, int y)
603 {
604   // Note a released button and return
605   if (updown == 1) {
606     if (_mouseInstrument != 0)
607         _mouseInstrument->doMouseAction(_mouseButton, 1, _mouseX, _mouseY);
608     _mouseDown = false;
609     _mouseInstrument = 0;
610     return false;
611   }
612
613   // Search for a matching instrument.
614   for (int i = 0; i < (int)_instruments.size(); i++) {
615     FGPanelInstrument *inst = _instruments[i];
616     int ix = inst->getXPos();
617     int iy = inst->getYPos();
618     int iw = inst->getWidth() / 2;
619     int ih = inst->getHeight() / 2;
620     if (x >= ix - iw && x < ix + iw && y >= iy - ih && y < iy + ih) {
621       _mouseDown = true;
622       _mouseDelay = 20;
623       _mouseInstrument = inst;
624       _mouseButton = button;
625       _mouseX = x - ix;
626       _mouseY = y - iy;
627       // Always do the action once.
628       return _mouseInstrument->doMouseAction(_mouseButton, 0,
629                                              _mouseX, _mouseY);
630     }
631   }
632   return false;
633 }
634
635 /**
636  * Perform a mouse action.
637  */
638 bool
639 FGPanel::doMouseAction (int button, int updown, int x, int y)
640 {
641                                 // FIXME: this same code appears in update()
642   int xsize = _xsize_node->getIntValue();
643   int ysize = _ysize_node->getIntValue();
644   float aspect_adjust = get_aspect_adjust(xsize, ysize);
645
646                                 // Scale for the real window size.
647   if (aspect_adjust < 1.0) {
648     x = int(((float)x / xsize) * WIN_W * aspect_adjust);
649     y = int(WIN_H - ((float(y) / ysize) * WIN_H));
650   } else {
651     x = int(((float)x / xsize) * WIN_W);
652     y = int((WIN_H - ((float(y) / ysize) * WIN_H)) / aspect_adjust);
653   }
654
655                                 // Adjust for offsets.
656   x -= _x_offset->getIntValue();
657   y -= _y_offset->getIntValue();
658
659   // Having fixed up the coordinates, fall through to the local
660   // coordinate handler.
661   return doLocalMouseAction(button, updown, x, y);
662
663
664 void FGPanel::setDepthTest (bool enable) {
665     _enable_depth_test = enable;
666 }
667
668
669 \f
670 ////////////////////////////////////////////////////////////////////////.
671 // Implementation of FGPanelAction.
672 ////////////////////////////////////////////////////////////////////////
673
674 FGPanelAction::FGPanelAction ()
675 {
676 }
677
678 FGPanelAction::FGPanelAction (int button, int x, int y, int w, int h,
679                               bool repeatable)
680     : _button(button), _x(x), _y(y), _w(w), _h(h), _repeatable(repeatable)
681 {
682 }
683
684 FGPanelAction::~FGPanelAction ()
685 {
686   for (unsigned int i = 0; i < 2; i++) {
687       for (unsigned int j = 0; j < _bindings[i].size(); j++)
688           delete _bindings[i][j];
689   }
690 }
691
692 void
693 FGPanelAction::addBinding (SGBinding * binding, int updown)
694 {
695   _bindings[updown].push_back(binding);
696 }
697
698 bool
699 FGPanelAction::doAction (int updown)
700 {
701   if (test()) {
702     if ((updown != _last_state) || (updown == 0 && _repeatable)) {
703         int nBindings = _bindings[updown].size();
704         for (int i = 0; i < nBindings; i++)
705             _bindings[updown][i]->fire();
706     }
707     _last_state = updown;
708     return true;
709   } else {
710     return false;
711   }
712 }
713
714
715 \f
716 ////////////////////////////////////////////////////////////////////////
717 // Implementation of FGPanelTransformation.
718 ////////////////////////////////////////////////////////////////////////
719
720 FGPanelTransformation::FGPanelTransformation ()
721   : table(0)
722 {
723 }
724
725 FGPanelTransformation::~FGPanelTransformation ()
726 {
727   delete table;
728 }
729
730
731 \f
732 ////////////////////////////////////////////////////////////////////////
733 // Implementation of FGPanelInstrument.
734 ////////////////////////////////////////////////////////////////////////
735
736
737 FGPanelInstrument::FGPanelInstrument ()
738 {
739   setPosition(0, 0);
740   setSize(0, 0);
741 }
742
743 FGPanelInstrument::FGPanelInstrument (int x, int y, int w, int h)
744 {
745   setPosition(x, y);
746   setSize(w, h);
747 }
748
749 FGPanelInstrument::~FGPanelInstrument ()
750 {
751   for (action_list_type::iterator it = _actions.begin();
752        it != _actions.end();
753        it++) {
754     delete *it;
755     *it = 0;
756   }
757 }
758
759 void
760 FGPanelInstrument::drawHotspots(osg::State& state)
761 {
762   for ( unsigned int i = 0; i < _actions.size(); i++ ) {
763     FGPanelAction* a = _actions[i];
764     float x1 = getXPos() + a->getX();
765     float x2 = x1 + a->getWidth();
766     float y1 = getYPos() + a->getY();
767     float y2 = y1 + a->getHeight();
768
769     glBegin(GL_LINE_LOOP);
770     glVertex2f(x1, y1);
771     glVertex2f(x1, y2);
772     glVertex2f(x2, y2);
773     glVertex2f(x2, y1);
774     glEnd();
775   }
776 }
777
778 void
779 FGPanelInstrument::setPosition (int x, int y)
780 {
781   _x = x;
782   _y = y;
783 }
784
785 void
786 FGPanelInstrument::setSize (int w, int h)
787 {
788   _w = w;
789   _h = h;
790 }
791
792 int
793 FGPanelInstrument::getXPos () const
794 {
795   return _x;
796 }
797
798 int
799 FGPanelInstrument::getYPos () const
800 {
801   return _y;
802 }
803
804 int
805 FGPanelInstrument::getWidth () const
806 {
807   return _w;
808 }
809
810 int
811 FGPanelInstrument::getHeight () const
812 {
813   return _h;
814 }
815
816 void
817 FGPanelInstrument::addAction (FGPanelAction * action)
818 {
819   _actions.push_back(action);
820 }
821
822                                 // Coordinates relative to centre.
823 bool
824 FGPanelInstrument::doMouseAction (int button, int updown, int x, int y)
825 {
826   if (test()) {
827     action_list_type::iterator it = _actions.begin();
828     action_list_type::iterator last = _actions.end();
829     for ( ; it != last; it++) {
830       if ((*it)->inArea(button, x, y) &&
831           (*it)->doAction(updown))
832         return true;
833     }
834   }
835   return false;
836 }
837
838
839 \f
840 ////////////////////////////////////////////////////////////////////////
841 // Implementation of FGLayeredInstrument.
842 ////////////////////////////////////////////////////////////////////////
843
844 FGLayeredInstrument::FGLayeredInstrument (int x, int y, int w, int h)
845   : FGPanelInstrument(x, y, w, h)
846 {
847 }
848
849 FGLayeredInstrument::~FGLayeredInstrument ()
850 {
851   for (layer_list::iterator it = _layers.begin(); it != _layers.end(); it++) {
852     delete *it;
853     *it = 0;
854   }
855 }
856
857 void
858 FGLayeredInstrument::draw (osg::State& state)
859 {
860   if (!test())
861     return;
862   
863   for (int i = 0; i < (int)_layers.size(); i++) {
864     glPushMatrix();
865     _layers[i]->draw(state);
866     glPopMatrix();
867   }
868 }
869
870 int
871 FGLayeredInstrument::addLayer (FGInstrumentLayer *layer)
872 {
873   int n = _layers.size();
874   if (layer->getWidth() == -1) {
875     layer->setWidth(getWidth());
876   }
877   if (layer->getHeight() == -1) {
878     layer->setHeight(getHeight());
879   }
880   _layers.push_back(layer);
881   return n;
882 }
883
884 int
885 FGLayeredInstrument::addLayer (const FGCroppedTexture &texture,
886                                int w, int h)
887 {
888   return addLayer(new FGTexturedLayer(texture, w, h));
889 }
890
891 void
892 FGLayeredInstrument::addTransformation (FGPanelTransformation * transformation)
893 {
894   int layer = _layers.size() - 1;
895   _layers[layer]->addTransformation(transformation);
896 }
897
898
899 \f
900 ////////////////////////////////////////////////////////////////////////
901 // Implementation of FGSpecialInstrument.
902 ////////////////////////////////////////////////////////////////////////
903
904 FGSpecialInstrument::FGSpecialInstrument (DCLGPS* sb)
905   : FGPanelInstrument()
906 {
907   complex = sb;
908 }
909
910 FGSpecialInstrument::~FGSpecialInstrument ()
911 {
912 }
913
914 void
915 FGSpecialInstrument::draw (osg::State& state)
916 {
917   complex->draw(state);
918 }
919
920
921 \f
922 ////////////////////////////////////////////////////////////////////////
923 // Implementation of FGInstrumentLayer.
924 ////////////////////////////////////////////////////////////////////////
925
926 FGInstrumentLayer::FGInstrumentLayer (int w, int h)
927   : _w(w),
928     _h(h)
929 {
930 }
931
932 FGInstrumentLayer::~FGInstrumentLayer ()
933 {
934   for (transformation_list::iterator it = _transformations.begin();
935        it != _transformations.end();
936        it++) {
937     delete *it;
938     *it = 0;
939   }
940 }
941
942 void
943 FGInstrumentLayer::transform () const
944 {
945   transformation_list::const_iterator it = _transformations.begin();
946   transformation_list::const_iterator last = _transformations.end();
947   while (it != last) {
948     FGPanelTransformation *t = *it;
949     if (t->test()) {
950       float val = (t->node == 0 ? 0.0 : t->node->getFloatValue());
951
952       if (t->has_mod)
953           val = fmod(val, t->mod);
954       if (val < t->min) {
955         val = t->min;
956       } else if (val > t->max) {
957         val = t->max;
958       }
959
960       if (t->table==0) {
961         val = val * t->factor + t->offset;
962       } else {
963         val = t->table->interpolate(val) * t->factor + t->offset;
964       }
965       
966       switch (t->type) {
967       case FGPanelTransformation::XSHIFT:
968         glTranslatef(val, 0.0, 0.0);
969         break;
970       case FGPanelTransformation::YSHIFT:
971         glTranslatef(0.0, val, 0.0);
972         break;
973       case FGPanelTransformation::ROTATION:
974         glRotatef(-val, 0.0, 0.0, 1.0);
975         break;
976       }
977     }
978     it++;
979   }
980 }
981
982 void
983 FGInstrumentLayer::addTransformation (FGPanelTransformation * transformation)
984 {
985   _transformations.push_back(transformation);
986 }
987
988
989 \f
990 ////////////////////////////////////////////////////////////////////////
991 // Implementation of FGGroupLayer.
992 ////////////////////////////////////////////////////////////////////////
993
994 FGGroupLayer::FGGroupLayer ()
995 {
996 }
997
998 FGGroupLayer::~FGGroupLayer ()
999 {
1000   for (unsigned int i = 0; i < _layers.size(); i++)
1001     delete _layers[i];
1002 }
1003
1004 void
1005 FGGroupLayer::draw (osg::State& state)
1006 {
1007   if (test()) {
1008     transform();
1009     int nLayers = _layers.size();
1010     for (int i = 0; i < nLayers; i++)
1011       _layers[i]->draw(state);
1012   }
1013 }
1014
1015 void
1016 FGGroupLayer::addLayer (FGInstrumentLayer * layer)
1017 {
1018   _layers.push_back(layer);
1019 }
1020
1021
1022 \f
1023 ////////////////////////////////////////////////////////////////////////
1024 // Implementation of FGTexturedLayer.
1025 ////////////////////////////////////////////////////////////////////////
1026
1027
1028 FGTexturedLayer::FGTexturedLayer (const FGCroppedTexture &texture, int w, int h)
1029   : FGInstrumentLayer(w, h),
1030     _emissive(false)
1031 {
1032   setTexture(texture);
1033 }
1034
1035
1036 FGTexturedLayer::~FGTexturedLayer ()
1037 {
1038 }
1039
1040
1041 void
1042 FGTexturedLayer::draw (osg::State& state)
1043 {
1044   if (test()) {
1045     int w2 = _w / 2;
1046     int h2 = _h / 2;
1047     
1048     transform();
1049     state.pushStateSet(_texture.getTexture());
1050     state.apply();
1051     state.setActiveTextureUnit(0);
1052     state.setClientActiveTextureUnit(0);
1053
1054     glBegin(GL_POLYGON);
1055
1056     if (_emissive) {
1057       glColor4fv( emissive_panel_color );
1058     } else {
1059                                 // From Curt: turn on the panel
1060                                 // lights after sundown.
1061       glColor4fv( panel_color );
1062     }
1063
1064     glTexCoord2f(_texture.getMinX(), _texture.getMinY()); glVertex2f(-w2, -h2);
1065     glTexCoord2f(_texture.getMaxX(), _texture.getMinY()); glVertex2f(w2, -h2);
1066     glTexCoord2f(_texture.getMaxX(), _texture.getMaxY()); glVertex2f(w2, h2);
1067     glTexCoord2f(_texture.getMinX(), _texture.getMaxY()); glVertex2f(-w2, h2);
1068     glEnd();
1069     state.popStateSet();
1070     state.apply();
1071     state.setActiveTextureUnit(0);
1072     state.setClientActiveTextureUnit(0);
1073
1074   }
1075 }
1076
1077
1078 \f
1079 ////////////////////////////////////////////////////////////////////////
1080 // Implementation of FGTextLayer.
1081 ////////////////////////////////////////////////////////////////////////
1082
1083 FGTextLayer::FGTextLayer (int w, int h)
1084   : FGInstrumentLayer(w, h), _pointSize(14.0), _font_name("Helvetica.txf")
1085 {
1086   _then.stamp();
1087   _color[0] = _color[1] = _color[2] = 0.0;
1088   _color[3] = 1.0;
1089 }
1090
1091 FGTextLayer::~FGTextLayer ()
1092 {
1093   chunk_list::iterator it = _chunks.begin();
1094   chunk_list::iterator last = _chunks.end();
1095   for ( ; it != last; it++) {
1096     delete *it;
1097   }
1098 }
1099
1100 void
1101 FGTextLayer::draw (osg::State& state)
1102 {
1103   if (test()) {
1104     glColor4fv(_color);
1105     transform();
1106
1107     FGFontCache *fc = globals->get_fontcache();
1108     fntFont* font = fc->getTexFont(_font_name.c_str());
1109     if (!font) {
1110         return; // don't crash on missing fonts
1111     }
1112     
1113     text_renderer.setFont(font);
1114
1115     text_renderer.setPointSize(_pointSize);
1116     text_renderer.begin();
1117     text_renderer.start3f(0, 0, 0);
1118
1119     _now.stamp();
1120     double diff = (_now - _then).toUSecs();
1121
1122     if (diff > 100000 || diff < 0 ) {
1123       // ( diff < 0 ) is a sanity check and indicates our time stamp
1124       // difference math probably overflowed.  We can handle a max
1125       // difference of 35.8 minutes since the returned value is in
1126       // usec.  So if the panel is left off longer than that we can
1127       // over flow the math with it is turned back on.  This (diff <
1128       // 0) catches that situation, get's us out of trouble, and
1129       // back on track.
1130       recalc_value();
1131       _then = _now;
1132     }
1133
1134     // Something is goofy.  The code in this file renders only CCW
1135     // polygons, and I have verified that the font code in plib
1136     // renders only CCW trianbles.  Yet they come out backwards.
1137     // Something around here or in plib is either changing the winding
1138     // order or (more likely) pushing a left-handed matrix onto the
1139     // stack.  But I can't find it; get out the chainsaw...
1140     glFrontFace(GL_CW);
1141     text_renderer.puts((char *)(_value.c_str()));
1142     glFrontFace(GL_CCW);
1143
1144     text_renderer.end();
1145     glColor4f(1.0, 1.0, 1.0, 1.0);      // FIXME
1146   }
1147 }
1148
1149 void
1150 FGTextLayer::addChunk (FGTextLayer::Chunk * chunk)
1151 {
1152   _chunks.push_back(chunk);
1153 }
1154
1155 void
1156 FGTextLayer::setColor (float r, float g, float b)
1157 {
1158   _color[0] = r;
1159   _color[1] = g;
1160   _color[2] = b;
1161   _color[3] = 1.0;
1162 }
1163
1164 void
1165 FGTextLayer::setPointSize (float size)
1166 {
1167   _pointSize = size;
1168 }
1169
1170 void
1171 FGTextLayer::setFontName(const string &name)
1172 {
1173   _font_name = name + ".txf";
1174   FGFontCache *fc = globals->get_fontcache();
1175   fntFont* font = fc->getTexFont(_font_name.c_str());
1176   if (!font) {
1177       SG_LOG(SG_GENERAL, SG_WARN, "unable to find font:" << name);
1178   }
1179 }
1180
1181
1182 void
1183 FGTextLayer::setFont(fntFont * font)
1184 {
1185   text_renderer.setFont(font);
1186 }
1187
1188
1189 void
1190 FGTextLayer::recalc_value () const
1191 {
1192   _value = "";
1193   chunk_list::const_iterator it = _chunks.begin();
1194   chunk_list::const_iterator last = _chunks.end();
1195   for ( ; it != last; it++) {
1196     _value += (*it)->getValue();
1197   }
1198 }
1199
1200
1201 \f
1202 ////////////////////////////////////////////////////////////////////////
1203 // Implementation of FGTextLayer::Chunk.
1204 ////////////////////////////////////////////////////////////////////////
1205
1206 FGTextLayer::Chunk::Chunk (const string &text, const string &fmt)
1207   : _type(FGTextLayer::TEXT), _fmt(fmt)
1208 {
1209   _text = text;
1210   if (_fmt.empty()) 
1211     _fmt = "%s";
1212 }
1213
1214 FGTextLayer::Chunk::Chunk (ChunkType type, const SGPropertyNode * node,
1215                            const string &fmt, float mult, float offs,
1216                            bool truncation)
1217   : _type(type), _fmt(fmt), _mult(mult), _offs(offs), _trunc(truncation)
1218 {
1219   if (_fmt.empty()) {
1220     if (type == TEXT_VALUE)
1221       _fmt = "%s";
1222     else
1223       _fmt = "%.2f";
1224   }
1225   _node = node;
1226 }
1227
1228 const char *
1229 FGTextLayer::Chunk::getValue () const
1230 {
1231   if (test()) {
1232     _buf[0] = '\0';
1233     switch (_type) {
1234     case TEXT:
1235       sprintf(_buf, _fmt.c_str(), _text.c_str());
1236       return _buf;
1237     case TEXT_VALUE:
1238       sprintf(_buf, _fmt.c_str(), _node->getStringValue());
1239       break;
1240     case DOUBLE_VALUE:
1241       double d = _offs + _node->getFloatValue() * _mult;
1242       if (_trunc)  d = (d < 0) ? -floor(-d) : floor(d);
1243       sprintf(_buf, _fmt.c_str(), d);
1244       break;
1245     }
1246     return _buf;
1247   } else {
1248     return "";
1249   }
1250 }
1251
1252
1253 \f
1254 ////////////////////////////////////////////////////////////////////////
1255 // Implementation of FGSwitchLayer.
1256 ////////////////////////////////////////////////////////////////////////
1257
1258 FGSwitchLayer::FGSwitchLayer ()
1259   : FGGroupLayer()
1260 {
1261 }
1262
1263 void
1264 FGSwitchLayer::draw (osg::State& state)
1265 {
1266   if (test()) {
1267     transform();
1268     int nLayers = _layers.size();
1269     for (int i = 0; i < nLayers; i++) {
1270       if (_layers[i]->test()) {
1271           _layers[i]->draw(state);
1272           return;
1273       }
1274     }
1275   }
1276 }
1277
1278 \f
1279 // end of panel.cxx