]> git.mxchange.org Git - flightgear.git/blob - src/Cockpit/panel.cxx
Remove hard-coded values wherever possible;
[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/Matrixf>
44 #include <osg/TexEnv>
45 #include <osg/PolygonOffset>
46
47 #include <simgear/compiler.h>
48
49 #include <plib/fnt.h>
50
51 #include <simgear/debug/logstream.hxx>
52 #include <simgear/misc/sg_path.hxx>
53 #include <simgear/scene/model/model.hxx>
54 #include <osg/GLU>
55
56 #include <Main/globals.hxx>
57 #include <Main/fg_props.hxx>
58 #include <Main/viewmgr.hxx>
59 #include <Time/light.hxx>
60 #include <GUI/FGFontCache.hxx>  
61 #include <Main/viewer.hxx>
62 #include <Instrumentation/dclgps.hxx>
63
64 #define WIN_X 0
65 #define WIN_Y 0
66 #define WIN_W 1024
67 #define WIN_H 768
68
69 // The number of polygon-offset "units" to place between layers.  In
70 // principle, one is supposed to be enough.  In practice, I find that
71 // my hardware/driver requires many more.
72 #define POFF_UNITS 8
73
74 using std::map;
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   using namespace osg;
277                                // Calculate accelerations
278                                // and jiggle the panel accordingly
279                                // The factors and bounds are just
280                                // initial guesses; using sqrt smooths
281                                // out the spikes.
282   double x_offset = _x_offset->getIntValue();
283   double y_offset = _y_offset->getIntValue();
284
285
286   glMatrixMode(GL_PROJECTION);
287   glPushMatrix();
288   Matrixf proj;
289   if ( _flipx->getBoolValue() ) {
290       proj = Matrixf::ortho2D(winx + winw, winx, winy + winh, winy); /* up side down */
291   } else {
292       proj = Matrixf::ortho2D(winx, winx + winw, winy, winy + winh); /* right side up */
293   }
294   glLoadMatrix(proj.ptr());
295   
296   glMatrixMode(GL_MODELVIEW);
297   glPushMatrix();
298   glLoadIdentity();
299   
300   glTranslated(x_offset, y_offset, 0);
301   
302   draw(state);
303
304   glMatrixMode(GL_PROJECTION);
305   glPopMatrix();
306   glMatrixMode(GL_MODELVIEW);
307   glPopMatrix();
308 }
309
310 /**
311  * Update the panel.
312  */
313 void
314 FGPanel::update (osg::State& state)
315 {
316                                 // Do nothing if the panel isn't visible.
317     if ( !fgPanelVisible() ) {
318         return;
319     }
320
321     updateMouseDelay();
322
323                                 // Now, draw the panel
324     float aspect_adjust = get_aspect_adjust(_xsize_node->getIntValue(),
325                                             _ysize_node->getIntValue());
326     if (aspect_adjust <1.0)
327         update(state, WIN_X, int(WIN_W * aspect_adjust), WIN_Y, WIN_H);
328     else
329         update(state, WIN_X, WIN_W, WIN_Y, int(WIN_H / aspect_adjust));
330 }
331
332 /**
333  * Handle repeatable mouse events.  Called from update() and from
334  * fgUpdate3DPanels().  This functionality needs to move into the
335  * input subsystem.  Counting a tick every two frames is clumsy...
336  */
337 void FGPanel::updateMouseDelay()
338 {
339     if (_mouseDown) {
340         _mouseDelay--;
341         if (_mouseDelay < 0) {
342             _mouseInstrument->doMouseAction(_mouseButton, 0, _mouseX, _mouseY);
343             _mouseDelay = 2;
344         }
345     }
346 }
347
348
349 void
350 FGPanel::draw(osg::State& state)
351 {
352   // In 3D mode, it's possible that we are being drawn exactly on top
353   // of an existing polygon.  Use an offset to prevent z-fighting.  In
354   // 2D mode, this is a no-op.
355   static osg::ref_ptr<osg::StateSet> panelStateSet;
356   if (!panelStateSet.valid()) {
357     panelStateSet = new osg::StateSet;
358     panelStateSet->setAttributeAndModes(new osg::PolygonOffset(-1, -POFF_UNITS));
359     panelStateSet->setTextureAttribute(0, new osg::TexEnv);
360
361     // Draw the background
362     panelStateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
363     panelStateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
364     panelStateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
365     panelStateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
366     osg::Material* material = new osg::Material;
367     material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
368     material->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1));
369     material->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1));
370     material->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
371     material->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
372     panelStateSet->setAttribute(material);
373     panelStateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
374     panelStateSet->setAttributeAndModes(new osg::CullFace(osg::CullFace::BACK));
375     panelStateSet->setAttributeAndModes(new osg::Depth(osg::Depth::LEQUAL));
376   }
377   if ( _enable_depth_test )
378     panelStateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
379   else
380     panelStateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
381   state.pushStateSet(panelStateSet.get());
382   state.apply();
383   state.setActiveTextureUnit(0);
384   state.setClientActiveTextureUnit(0);
385
386   FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
387   sgCopyVec4( panel_color, l->scene_diffuse().data());
388   if ( fgGetDouble("/systems/electrical/outputs/instrument-lights") > 1.0 ) {
389       if ( panel_color[0] < 0.7 ) panel_color[0] = 0.7;
390       if ( panel_color[1] < 0.2 ) panel_color[1] = 0.2;
391       if ( panel_color[2] < 0.2 ) panel_color[2] = 0.2;
392   }
393   glColor4fv( panel_color );
394   if (_bg != 0) {
395     state.pushStateSet(_bg.get());
396     state.apply();
397     state.setActiveTextureUnit(0);
398     state.setClientActiveTextureUnit(0);
399
400     glBegin(GL_POLYGON);
401     glTexCoord2f(0.0, 0.0); glVertex2f(WIN_X, WIN_Y);
402     glTexCoord2f(1.0, 0.0); glVertex2f(WIN_X + _width, WIN_Y);
403     glTexCoord2f(1.0, 1.0); glVertex2f(WIN_X + _width, WIN_Y + _height);
404     glTexCoord2f(0.0, 1.0); glVertex2f(WIN_X, WIN_Y + _height);
405     glEnd();
406     state.popStateSet();
407     state.apply();
408     state.setActiveTextureUnit(0);
409     state.setClientActiveTextureUnit(0);
410
411   } else {
412     for (int i = 0; i < 4; i ++) {
413       // top row of textures...(1,3,5,7)
414       state.pushStateSet(_mbg[i*2].get());
415       state.apply();
416       state.setActiveTextureUnit(0);
417       state.setClientActiveTextureUnit(0);
418
419       glBegin(GL_POLYGON);
420       glTexCoord2f(0.0, 0.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y + (_height/2));
421       glTexCoord2f(1.0, 0.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y + (_height/2));
422       glTexCoord2f(1.0, 1.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y + _height);
423       glTexCoord2f(0.0, 1.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y + _height);
424       glEnd();
425       state.popStateSet();
426       state.apply();
427       state.setActiveTextureUnit(0);
428       state.setClientActiveTextureUnit(0);
429
430       // bottom row of textures...(2,4,6,8)
431       state.pushStateSet(_mbg[i*2+1].get());
432       state.apply();
433       state.setActiveTextureUnit(0);
434       state.setClientActiveTextureUnit(0);
435
436       glBegin(GL_POLYGON);
437       glTexCoord2f(0.0, 0.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y);
438       glTexCoord2f(1.0, 0.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y);
439       glTexCoord2f(1.0, 1.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y + (_height/2));
440       glTexCoord2f(0.0, 1.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y + (_height/2));
441       glEnd();
442       state.popStateSet();
443       state.apply();
444       state.setActiveTextureUnit(0);
445       state.setClientActiveTextureUnit(0);
446
447     }
448   }
449
450   // Draw the instruments.
451   // Syd Adams: added instrument clipping
452   instrument_list_type::const_iterator current = _instruments.begin();
453   instrument_list_type::const_iterator end = _instruments.end();
454
455   GLdouble blx[4]={1.0,0.0,0.0,0.0};
456   GLdouble bly[4]={0.0,1.0,0.0,0.0};
457   GLdouble urx[4]={-1.0,0.0,0.0,0.0};
458   GLdouble ury[4]={0.0,-1.0,0.0,0.0};
459
460   for ( ; current != end; current++) {
461     FGPanelInstrument * instr = *current;
462     glPushMatrix();
463     glTranslated(instr->getXPos(), instr->getYPos(), 0);
464
465     int ix= instr->getWidth();
466     int iy= instr->getHeight();
467     glPushMatrix();
468     glTranslated(-ix/2,-iy/2,0);
469     glClipPlane(GL_CLIP_PLANE0,blx);
470     glClipPlane(GL_CLIP_PLANE1,bly);
471     glEnable(GL_CLIP_PLANE0);
472     glEnable(GL_CLIP_PLANE1);
473
474     glTranslated(ix,iy,0);
475     glClipPlane(GL_CLIP_PLANE2,urx);
476     glClipPlane(GL_CLIP_PLANE3,ury);
477     glEnable(GL_CLIP_PLANE2);
478     glEnable(GL_CLIP_PLANE3);
479     glPopMatrix();
480     instr->draw(state);
481
482     glPopMatrix();
483   }
484
485   glDisable(GL_CLIP_PLANE0);
486   glDisable(GL_CLIP_PLANE1);
487   glDisable(GL_CLIP_PLANE2);
488   glDisable(GL_CLIP_PLANE3);
489
490   state.popStateSet();
491   state.apply();
492   state.setActiveTextureUnit(0);
493   state.setClientActiveTextureUnit(0);
494
495
496   // Draw yellow "hotspots" if directed to.  This is a panel authoring
497   // feature; not intended to be high performance or to look good.
498   if ( fgGetBool("/sim/panel-hotspots") ) {
499     static osg::ref_ptr<osg::StateSet> hotspotStateSet;
500     if (!hotspotStateSet.valid()) {
501       hotspotStateSet = new osg::StateSet;
502       hotspotStateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
503       hotspotStateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
504     }
505
506     state.pushStateSet(hotspotStateSet.get());
507     state.apply();
508     state.setActiveTextureUnit(0);
509     state.setClientActiveTextureUnit(0);
510
511
512     glPushAttrib(GL_ENABLE_BIT);
513     glDisable(GL_COLOR_MATERIAL);
514     glColor3f(1, 1, 0);
515     
516     for ( unsigned int i = 0; i < _instruments.size(); i++ )
517       _instruments[i]->drawHotspots(state);
518
519     glPopAttrib();
520
521     state.popStateSet();
522     state.apply();
523     state.setActiveTextureUnit(0);
524     state.setClientActiveTextureUnit(0);
525
526   }
527 }
528
529 /**
530  * Set the panel's visibility.
531  */
532 void
533 FGPanel::setVisibility (bool visibility)
534 {
535   _visibility->setBoolValue( visibility );
536 }
537
538
539 /**
540  * Return true if the panel is visible.
541  */
542 bool
543 FGPanel::getVisibility () const
544 {
545   return _visibility->getBoolValue();
546 }
547
548
549 /**
550  * Set the panel's background texture.
551  */
552 void
553 FGPanel::setBackground (osg::Texture2D* texture)
554 {
555   osg::StateSet* stateSet = new osg::StateSet;
556   stateSet->setTextureAttribute(0, texture);
557   stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
558   stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
559   _bg = stateSet;
560 }
561
562 /**
563  * Set the panel's multiple background textures.
564  */
565 void
566 FGPanel::setMultiBackground (osg::Texture2D* texture, int idx)
567 {
568   _bg = 0;
569
570   osg::StateSet* stateSet = new osg::StateSet;
571   stateSet->setTextureAttribute(0, texture);
572   stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
573   stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
574   _mbg[idx] = stateSet;
575 }
576
577 /**
578  * Set the panel's x-offset.
579  */
580 void
581 FGPanel::setXOffset (int offset)
582 {
583   if (offset <= 0 && offset >= -_width + WIN_W)
584     _x_offset->setIntValue( offset );
585 }
586
587
588 /**
589  * Set the panel's y-offset.
590  */
591 void
592 FGPanel::setYOffset (int offset)
593 {
594   if (offset <= 0 && offset >= -_height)
595     _y_offset->setIntValue( offset );
596 }
597
598 /**
599  * Handle a mouse action in panel-local (not screen) coordinates.
600  * Used by the 3D panel code in Model/panelnode.cxx, in situations
601  * where the panel doesn't control its own screen location.
602  */
603 bool
604 FGPanel::doLocalMouseAction(int button, int updown, int x, int y)
605 {
606   // Note a released button and return
607   if (updown == 1) {
608     if (_mouseInstrument != 0)
609         _mouseInstrument->doMouseAction(_mouseButton, 1, _mouseX, _mouseY);
610     _mouseDown = false;
611     _mouseInstrument = 0;
612     return false;
613   }
614
615   // Search for a matching instrument.
616   for (int i = 0; i < (int)_instruments.size(); i++) {
617     FGPanelInstrument *inst = _instruments[i];
618     int ix = inst->getXPos();
619     int iy = inst->getYPos();
620     int iw = inst->getWidth() / 2;
621     int ih = inst->getHeight() / 2;
622     if (x >= ix - iw && x < ix + iw && y >= iy - ih && y < iy + ih) {
623       _mouseDown = true;
624       _mouseDelay = 20;
625       _mouseInstrument = inst;
626       _mouseButton = button;
627       _mouseX = x - ix;
628       _mouseY = y - iy;
629       // Always do the action once.
630       return _mouseInstrument->doMouseAction(_mouseButton, 0,
631                                              _mouseX, _mouseY);
632     }
633   }
634   return false;
635 }
636
637 /**
638  * Perform a mouse action.
639  */
640 bool
641 FGPanel::doMouseAction (int button, int updown, int x, int y)
642 {
643                                 // FIXME: this same code appears in update()
644   int xsize = _xsize_node->getIntValue();
645   int ysize = _ysize_node->getIntValue();
646   float aspect_adjust = get_aspect_adjust(xsize, ysize);
647
648                                 // Scale for the real window size.
649   if (aspect_adjust < 1.0) {
650     x = int(((float)x / xsize) * WIN_W * aspect_adjust);
651     y = int(WIN_H - ((float(y) / ysize) * WIN_H));
652   } else {
653     x = int(((float)x / xsize) * WIN_W);
654     y = int((WIN_H - ((float(y) / ysize) * WIN_H)) / aspect_adjust);
655   }
656
657                                 // Adjust for offsets.
658   x -= _x_offset->getIntValue();
659   y -= _y_offset->getIntValue();
660
661   // Having fixed up the coordinates, fall through to the local
662   // coordinate handler.
663   return doLocalMouseAction(button, updown, x, y);
664
665
666 void FGPanel::setDepthTest (bool enable) {
667     _enable_depth_test = enable;
668 }
669
670
671 \f
672 ////////////////////////////////////////////////////////////////////////.
673 // Implementation of FGPanelAction.
674 ////////////////////////////////////////////////////////////////////////
675
676 FGPanelAction::FGPanelAction ()
677 {
678 }
679
680 FGPanelAction::FGPanelAction (int button, int x, int y, int w, int h,
681                               bool repeatable)
682     : _button(button), _x(x), _y(y), _w(w), _h(h), _repeatable(repeatable)
683 {
684 }
685
686 FGPanelAction::~FGPanelAction ()
687 {
688   for (unsigned int i = 0; i < 2; i++) {
689       for (unsigned int j = 0; j < _bindings[i].size(); j++)
690           delete _bindings[i][j];
691   }
692 }
693
694 void
695 FGPanelAction::addBinding (SGBinding * binding, int updown)
696 {
697   _bindings[updown].push_back(binding);
698 }
699
700 bool
701 FGPanelAction::doAction (int updown)
702 {
703   if (test()) {
704     if ((updown != _last_state) || (updown == 0 && _repeatable)) {
705         int nBindings = _bindings[updown].size();
706         for (int i = 0; i < nBindings; i++)
707             _bindings[updown][i]->fire();
708     }
709     _last_state = updown;
710     return true;
711   } else {
712     return false;
713   }
714 }
715
716
717 \f
718 ////////////////////////////////////////////////////////////////////////
719 // Implementation of FGPanelTransformation.
720 ////////////////////////////////////////////////////////////////////////
721
722 FGPanelTransformation::FGPanelTransformation ()
723   : table(0)
724 {
725 }
726
727 FGPanelTransformation::~FGPanelTransformation ()
728 {
729   delete table;
730 }
731
732
733 \f
734 ////////////////////////////////////////////////////////////////////////
735 // Implementation of FGPanelInstrument.
736 ////////////////////////////////////////////////////////////////////////
737
738
739 FGPanelInstrument::FGPanelInstrument ()
740 {
741   setPosition(0, 0);
742   setSize(0, 0);
743 }
744
745 FGPanelInstrument::FGPanelInstrument (int x, int y, int w, int h)
746 {
747   setPosition(x, y);
748   setSize(w, h);
749 }
750
751 FGPanelInstrument::~FGPanelInstrument ()
752 {
753   for (action_list_type::iterator it = _actions.begin();
754        it != _actions.end();
755        it++) {
756     delete *it;
757     *it = 0;
758   }
759 }
760
761 void
762 FGPanelInstrument::drawHotspots(osg::State& state)
763 {
764   for ( unsigned int i = 0; i < _actions.size(); i++ ) {
765     FGPanelAction* a = _actions[i];
766     float x1 = getXPos() + a->getX();
767     float x2 = x1 + a->getWidth();
768     float y1 = getYPos() + a->getY();
769     float y2 = y1 + a->getHeight();
770
771     glBegin(GL_LINE_LOOP);
772     glVertex2f(x1, y1);
773     glVertex2f(x1, y2);
774     glVertex2f(x2, y2);
775     glVertex2f(x2, y1);
776     glEnd();
777   }
778 }
779
780 void
781 FGPanelInstrument::setPosition (int x, int y)
782 {
783   _x = x;
784   _y = y;
785 }
786
787 void
788 FGPanelInstrument::setSize (int w, int h)
789 {
790   _w = w;
791   _h = h;
792 }
793
794 int
795 FGPanelInstrument::getXPos () const
796 {
797   return _x;
798 }
799
800 int
801 FGPanelInstrument::getYPos () const
802 {
803   return _y;
804 }
805
806 int
807 FGPanelInstrument::getWidth () const
808 {
809   return _w;
810 }
811
812 int
813 FGPanelInstrument::getHeight () const
814 {
815   return _h;
816 }
817
818 void
819 FGPanelInstrument::addAction (FGPanelAction * action)
820 {
821   _actions.push_back(action);
822 }
823
824                                 // Coordinates relative to centre.
825 bool
826 FGPanelInstrument::doMouseAction (int button, int updown, int x, int y)
827 {
828   if (test()) {
829     action_list_type::iterator it = _actions.begin();
830     action_list_type::iterator last = _actions.end();
831     for ( ; it != last; it++) {
832       if ((*it)->inArea(button, x, y) &&
833           (*it)->doAction(updown))
834         return true;
835     }
836   }
837   return false;
838 }
839
840
841 \f
842 ////////////////////////////////////////////////////////////////////////
843 // Implementation of FGLayeredInstrument.
844 ////////////////////////////////////////////////////////////////////////
845
846 FGLayeredInstrument::FGLayeredInstrument (int x, int y, int w, int h)
847   : FGPanelInstrument(x, y, w, h)
848 {
849 }
850
851 FGLayeredInstrument::~FGLayeredInstrument ()
852 {
853   for (layer_list::iterator it = _layers.begin(); it != _layers.end(); it++) {
854     delete *it;
855     *it = 0;
856   }
857 }
858
859 void
860 FGLayeredInstrument::draw (osg::State& state)
861 {
862   if (!test())
863     return;
864   
865   for (int i = 0; i < (int)_layers.size(); i++) {
866     glPushMatrix();
867     _layers[i]->draw(state);
868     glPopMatrix();
869   }
870 }
871
872 int
873 FGLayeredInstrument::addLayer (FGInstrumentLayer *layer)
874 {
875   int n = _layers.size();
876   if (layer->getWidth() == -1) {
877     layer->setWidth(getWidth());
878   }
879   if (layer->getHeight() == -1) {
880     layer->setHeight(getHeight());
881   }
882   _layers.push_back(layer);
883   return n;
884 }
885
886 int
887 FGLayeredInstrument::addLayer (const FGCroppedTexture &texture,
888                                int w, int h)
889 {
890   return addLayer(new FGTexturedLayer(texture, w, h));
891 }
892
893 void
894 FGLayeredInstrument::addTransformation (FGPanelTransformation * transformation)
895 {
896   int layer = _layers.size() - 1;
897   _layers[layer]->addTransformation(transformation);
898 }
899
900
901 \f
902 ////////////////////////////////////////////////////////////////////////
903 // Implementation of FGSpecialInstrument.
904 ////////////////////////////////////////////////////////////////////////
905
906 FGSpecialInstrument::FGSpecialInstrument (DCLGPS* sb)
907   : FGPanelInstrument()
908 {
909   complex = sb;
910 }
911
912 FGSpecialInstrument::~FGSpecialInstrument ()
913 {
914 }
915
916 void
917 FGSpecialInstrument::draw (osg::State& state)
918 {
919   complex->draw(state);
920 }
921
922
923 \f
924 ////////////////////////////////////////////////////////////////////////
925 // Implementation of FGInstrumentLayer.
926 ////////////////////////////////////////////////////////////////////////
927
928 FGInstrumentLayer::FGInstrumentLayer (int w, int h)
929   : _w(w),
930     _h(h)
931 {
932 }
933
934 FGInstrumentLayer::~FGInstrumentLayer ()
935 {
936   for (transformation_list::iterator it = _transformations.begin();
937        it != _transformations.end();
938        it++) {
939     delete *it;
940     *it = 0;
941   }
942 }
943
944 void
945 FGInstrumentLayer::transform () const
946 {
947   transformation_list::const_iterator it = _transformations.begin();
948   transformation_list::const_iterator last = _transformations.end();
949   while (it != last) {
950     FGPanelTransformation *t = *it;
951     if (t->test()) {
952       float val = (t->node == 0 ? 0.0 : t->node->getFloatValue());
953
954       if (t->has_mod)
955           val = fmod(val, t->mod);
956       if (val < t->min) {
957         val = t->min;
958       } else if (val > t->max) {
959         val = t->max;
960       }
961
962       if (t->table==0) {
963         val = val * t->factor + t->offset;
964       } else {
965         val = t->table->interpolate(val) * t->factor + t->offset;
966       }
967       
968       switch (t->type) {
969       case FGPanelTransformation::XSHIFT:
970         glTranslatef(val, 0.0, 0.0);
971         break;
972       case FGPanelTransformation::YSHIFT:
973         glTranslatef(0.0, val, 0.0);
974         break;
975       case FGPanelTransformation::ROTATION:
976         glRotatef(-val, 0.0, 0.0, 1.0);
977         break;
978       }
979     }
980     it++;
981   }
982 }
983
984 void
985 FGInstrumentLayer::addTransformation (FGPanelTransformation * transformation)
986 {
987   _transformations.push_back(transformation);
988 }
989
990
991 \f
992 ////////////////////////////////////////////////////////////////////////
993 // Implementation of FGGroupLayer.
994 ////////////////////////////////////////////////////////////////////////
995
996 FGGroupLayer::FGGroupLayer ()
997 {
998 }
999
1000 FGGroupLayer::~FGGroupLayer ()
1001 {
1002   for (unsigned int i = 0; i < _layers.size(); i++)
1003     delete _layers[i];
1004 }
1005
1006 void
1007 FGGroupLayer::draw (osg::State& state)
1008 {
1009   if (test()) {
1010     transform();
1011     int nLayers = _layers.size();
1012     for (int i = 0; i < nLayers; i++)
1013       _layers[i]->draw(state);
1014   }
1015 }
1016
1017 void
1018 FGGroupLayer::addLayer (FGInstrumentLayer * layer)
1019 {
1020   _layers.push_back(layer);
1021 }
1022
1023
1024 \f
1025 ////////////////////////////////////////////////////////////////////////
1026 // Implementation of FGTexturedLayer.
1027 ////////////////////////////////////////////////////////////////////////
1028
1029
1030 FGTexturedLayer::FGTexturedLayer (const FGCroppedTexture &texture, int w, int h)
1031   : FGInstrumentLayer(w, h),
1032     _emissive(false)
1033 {
1034   setTexture(texture);
1035 }
1036
1037
1038 FGTexturedLayer::~FGTexturedLayer ()
1039 {
1040 }
1041
1042
1043 void
1044 FGTexturedLayer::draw (osg::State& state)
1045 {
1046   if (test()) {
1047     int w2 = _w / 2;
1048     int h2 = _h / 2;
1049     
1050     transform();
1051     state.pushStateSet(_texture.getTexture());
1052     state.apply();
1053     state.setActiveTextureUnit(0);
1054     state.setClientActiveTextureUnit(0);
1055
1056     glBegin(GL_POLYGON);
1057
1058     if (_emissive) {
1059       glColor4fv( emissive_panel_color );
1060     } else {
1061                                 // From Curt: turn on the panel
1062                                 // lights after sundown.
1063       glColor4fv( panel_color );
1064     }
1065
1066     glTexCoord2f(_texture.getMinX(), _texture.getMinY()); glVertex2f(-w2, -h2);
1067     glTexCoord2f(_texture.getMaxX(), _texture.getMinY()); glVertex2f(w2, -h2);
1068     glTexCoord2f(_texture.getMaxX(), _texture.getMaxY()); glVertex2f(w2, h2);
1069     glTexCoord2f(_texture.getMinX(), _texture.getMaxY()); glVertex2f(-w2, h2);
1070     glEnd();
1071     state.popStateSet();
1072     state.apply();
1073     state.setActiveTextureUnit(0);
1074     state.setClientActiveTextureUnit(0);
1075
1076   }
1077 }
1078
1079
1080 \f
1081 ////////////////////////////////////////////////////////////////////////
1082 // Implementation of FGTextLayer.
1083 ////////////////////////////////////////////////////////////////////////
1084
1085 FGTextLayer::FGTextLayer (int w, int h)
1086   : FGInstrumentLayer(w, h), _pointSize(14.0), _font_name("Helvetica.txf")
1087 {
1088   _then.stamp();
1089   _color[0] = _color[1] = _color[2] = 0.0;
1090   _color[3] = 1.0;
1091 }
1092
1093 FGTextLayer::~FGTextLayer ()
1094 {
1095   chunk_list::iterator it = _chunks.begin();
1096   chunk_list::iterator last = _chunks.end();
1097   for ( ; it != last; it++) {
1098     delete *it;
1099   }
1100 }
1101
1102 void
1103 FGTextLayer::draw (osg::State& state)
1104 {
1105   if (test()) {
1106     glColor4fv(_color);
1107     transform();
1108
1109     FGFontCache *fc = globals->get_fontcache();
1110     fntFont* font = fc->getTexFont(_font_name.c_str());
1111     if (!font) {
1112         return; // don't crash on missing fonts
1113     }
1114     
1115     text_renderer.setFont(font);
1116
1117     text_renderer.setPointSize(_pointSize);
1118     text_renderer.begin();
1119     text_renderer.start3f(0, 0, 0);
1120
1121     _now.stamp();
1122     double diff = (_now - _then).toUSecs();
1123
1124     if (diff > 100000 || diff < 0 ) {
1125       // ( diff < 0 ) is a sanity check and indicates our time stamp
1126       // difference math probably overflowed.  We can handle a max
1127       // difference of 35.8 minutes since the returned value is in
1128       // usec.  So if the panel is left off longer than that we can
1129       // over flow the math with it is turned back on.  This (diff <
1130       // 0) catches that situation, get's us out of trouble, and
1131       // back on track.
1132       recalc_value();
1133       _then = _now;
1134     }
1135
1136     // Something is goofy.  The code in this file renders only CCW
1137     // polygons, and I have verified that the font code in plib
1138     // renders only CCW trianbles.  Yet they come out backwards.
1139     // Something around here or in plib is either changing the winding
1140     // order or (more likely) pushing a left-handed matrix onto the
1141     // stack.  But I can't find it; get out the chainsaw...
1142     glFrontFace(GL_CW);
1143     text_renderer.puts((char *)(_value.c_str()));
1144     glFrontFace(GL_CCW);
1145
1146     text_renderer.end();
1147     glColor4f(1.0, 1.0, 1.0, 1.0);      // FIXME
1148   }
1149 }
1150
1151 void
1152 FGTextLayer::addChunk (FGTextLayer::Chunk * chunk)
1153 {
1154   _chunks.push_back(chunk);
1155 }
1156
1157 void
1158 FGTextLayer::setColor (float r, float g, float b)
1159 {
1160   _color[0] = r;
1161   _color[1] = g;
1162   _color[2] = b;
1163   _color[3] = 1.0;
1164 }
1165
1166 void
1167 FGTextLayer::setPointSize (float size)
1168 {
1169   _pointSize = size;
1170 }
1171
1172 void
1173 FGTextLayer::setFontName(const string &name)
1174 {
1175   _font_name = name + ".txf";
1176   FGFontCache *fc = globals->get_fontcache();
1177   fntFont* font = fc->getTexFont(_font_name.c_str());
1178   if (!font) {
1179       SG_LOG(SG_GENERAL, SG_WARN, "unable to find font:" << name);
1180   }
1181 }
1182
1183
1184 void
1185 FGTextLayer::setFont(fntFont * font)
1186 {
1187   text_renderer.setFont(font);
1188 }
1189
1190
1191 void
1192 FGTextLayer::recalc_value () const
1193 {
1194   _value = "";
1195   chunk_list::const_iterator it = _chunks.begin();
1196   chunk_list::const_iterator last = _chunks.end();
1197   for ( ; it != last; it++) {
1198     _value += (*it)->getValue();
1199   }
1200 }
1201
1202
1203 \f
1204 ////////////////////////////////////////////////////////////////////////
1205 // Implementation of FGTextLayer::Chunk.
1206 ////////////////////////////////////////////////////////////////////////
1207
1208 FGTextLayer::Chunk::Chunk (const string &text, const string &fmt)
1209   : _type(FGTextLayer::TEXT), _fmt(fmt)
1210 {
1211   _text = text;
1212   if (_fmt.empty()) 
1213     _fmt = "%s";
1214 }
1215
1216 FGTextLayer::Chunk::Chunk (ChunkType type, const SGPropertyNode * node,
1217                            const string &fmt, float mult, float offs,
1218                            bool truncation)
1219   : _type(type), _fmt(fmt), _mult(mult), _offs(offs), _trunc(truncation)
1220 {
1221   if (_fmt.empty()) {
1222     if (type == TEXT_VALUE)
1223       _fmt = "%s";
1224     else
1225       _fmt = "%.2f";
1226   }
1227   _node = node;
1228 }
1229
1230 const char *
1231 FGTextLayer::Chunk::getValue () const
1232 {
1233   if (test()) {
1234     _buf[0] = '\0';
1235     switch (_type) {
1236     case TEXT:
1237       sprintf(_buf, _fmt.c_str(), _text.c_str());
1238       return _buf;
1239     case TEXT_VALUE:
1240       sprintf(_buf, _fmt.c_str(), _node->getStringValue());
1241       break;
1242     case DOUBLE_VALUE:
1243       double d = _offs + _node->getFloatValue() * _mult;
1244       if (_trunc)  d = (d < 0) ? -floor(-d) : floor(d);
1245       sprintf(_buf, _fmt.c_str(), d);
1246       break;
1247     }
1248     return _buf;
1249   } else {
1250     return "";
1251   }
1252 }
1253
1254
1255 \f
1256 ////////////////////////////////////////////////////////////////////////
1257 // Implementation of FGSwitchLayer.
1258 ////////////////////////////////////////////////////////////////////////
1259
1260 FGSwitchLayer::FGSwitchLayer ()
1261   : FGGroupLayer()
1262 {
1263 }
1264
1265 void
1266 FGSwitchLayer::draw (osg::State& state)
1267 {
1268   if (test()) {
1269     transform();
1270     int nLayers = _layers.size();
1271     for (int i = 0; i < nLayers; i++) {
1272       if (_layers[i]->test()) {
1273           _layers[i]->draw(state);
1274           return;
1275       }
1276     }
1277   }
1278 }
1279
1280 \f
1281 // end of panel.cxx