]> git.mxchange.org Git - flightgear.git/blob - src/Cockpit/panel.cxx
Modified Files:
[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 #ifdef HAVE_WINDOWS_H          
35 #  include <windows.h>
36 #endif
37
38 #include <stdio.h>      // sprintf
39 #include <string.h>
40
41 #include <osg/CullFace>
42 #include <osg/Depth>
43 #include <osg/Material>
44 #include <osg/TexEnv>
45 #include <osg/PolygonOffset>
46
47 #include <simgear/compiler.h>
48
49 #include SG_GLU_H
50
51 #include <plib/fnt.h>
52
53 #include <simgear/debug/logstream.hxx>
54 #include <simgear/misc/sg_path.hxx>
55 #include <simgear/scene/model/model.hxx>
56
57 #include <Main/globals.hxx>
58 #include <Main/fg_props.hxx>
59 #include <Main/viewmgr.hxx>
60 #include <Time/light.hxx>
61 #include <GUI/new_gui.hxx>      // FGFontCache
62
63 #include "hud.hxx"
64 #include "panel.hxx"
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      if (globals->get_current_panel() == 0)
102         return false;
103      if (globals->get_current_panel()->getVisibility() == 0)
104         return false;
105      if (globals->get_viewmgr()->get_current() != 0)
106         return false;
107      if (globals->get_current_view()->getHeadingOffset_deg() * SGD_DEGREES_TO_RADIANS != 0)
108         return false;
109      return true;
110 }
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)
122 {
123   osg::Texture2D* texture = _textureMap[relativePath].get();
124   if (texture == 0) {
125     SG_LOG( SG_COCKPIT, SG_DEBUG,
126             "Texture " << relativePath << " does not yet exist" );
127     SGPath tpath(globals->get_fg_root());
128     tpath.append(relativePath);
129
130     texture = SGLoadTexture2D(tpath);
131
132     _textureMap[relativePath] = texture;
133     if (!_textureMap[relativePath].valid()) 
134       SG_LOG( SG_COCKPIT, SG_ALERT, "Texture *still* doesn't exist" );
135     SG_LOG( SG_COCKPIT, SG_DEBUG, "Created texture " << relativePath );
136   }
137
138   return texture;
139 }
140
141
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
382   FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
383   sgCopyVec4( panel_color, l->scene_diffuse().data());
384   if ( fgGetDouble("/systems/electrical/outputs/instrument-lights") > 1.0 ) {
385       if ( panel_color[0] < 0.7 ) panel_color[0] = 0.7;
386       if ( panel_color[1] < 0.2 ) panel_color[1] = 0.2;
387       if ( panel_color[2] < 0.2 ) panel_color[2] = 0.2;
388   }
389   glColor4fv( panel_color );
390   if (_bg != 0) {
391     state.pushStateSet(_bg.get());
392     state.apply();
393     glBegin(GL_POLYGON);
394     glTexCoord2f(0.0, 0.0); glVertex2f(WIN_X, WIN_Y);
395     glTexCoord2f(1.0, 0.0); glVertex2f(WIN_X + _width, WIN_Y);
396     glTexCoord2f(1.0, 1.0); glVertex2f(WIN_X + _width, WIN_Y + _height);
397     glTexCoord2f(0.0, 1.0); glVertex2f(WIN_X, WIN_Y + _height);
398     glEnd();
399     state.popStateSet();
400     state.apply();
401   } else {
402     for (int i = 0; i < 4; i ++) {
403       // top row of textures...(1,3,5,7)
404       state.pushStateSet(_mbg[i*2].get());
405       state.apply();
406       glBegin(GL_POLYGON);
407       glTexCoord2f(0.0, 0.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y + (_height/2));
408       glTexCoord2f(1.0, 0.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y + (_height/2));
409       glTexCoord2f(1.0, 1.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y + _height);
410       glTexCoord2f(0.0, 1.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y + _height);
411       glEnd();
412       state.popStateSet();
413       state.apply();
414       // bottom row of textures...(2,4,6,8)
415       state.pushStateSet(_mbg[i*2+1].get());
416       state.apply();
417       glBegin(GL_POLYGON);
418       glTexCoord2f(0.0, 0.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y);
419       glTexCoord2f(1.0, 0.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y);
420       glTexCoord2f(1.0, 1.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y + (_height/2));
421       glTexCoord2f(0.0, 1.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y + (_height/2));
422       glEnd();
423       state.popStateSet();
424       state.apply();
425     }
426   }
427
428   // Draw the instruments.
429   // Syd Adams: added instrument clipping
430   instrument_list_type::const_iterator current = _instruments.begin();
431   instrument_list_type::const_iterator end = _instruments.end();
432
433   GLdouble blx[4]={1.0,0.0,0.0,0.0};
434   GLdouble bly[4]={0.0,1.0,0.0,0.0};
435   GLdouble urx[4]={-1.0,0.0,0.0,0.0};
436   GLdouble ury[4]={0.0,-1.0,0.0,0.0};
437
438   for ( ; current != end; current++) {
439     FGPanelInstrument * instr = *current;
440     glPushMatrix();
441     glTranslated(instr->getXPos(), instr->getYPos(), 0);
442
443     int ix= instr->getWidth();
444     int iy= instr->getHeight();
445     glPushMatrix();
446     glTranslated(-ix/2,-iy/2,0);
447     glClipPlane(GL_CLIP_PLANE0,blx);
448     glClipPlane(GL_CLIP_PLANE1,bly);
449     glEnable(GL_CLIP_PLANE0);
450     glEnable(GL_CLIP_PLANE1);
451
452     glTranslated(ix,iy,0);
453     glClipPlane(GL_CLIP_PLANE2,urx);
454     glClipPlane(GL_CLIP_PLANE3,ury);
455     glEnable(GL_CLIP_PLANE2);
456     glEnable(GL_CLIP_PLANE3);
457     glPopMatrix();
458     instr->draw(state);
459
460     glPopMatrix();
461   }
462
463   glDisable(GL_CLIP_PLANE0);
464   glDisable(GL_CLIP_PLANE1);
465   glDisable(GL_CLIP_PLANE2);
466   glDisable(GL_CLIP_PLANE3);
467
468   state.popStateSet();
469   state.apply();
470
471   // Draw yellow "hotspots" if directed to.  This is a panel authoring
472   // feature; not intended to be high performance or to look good.
473   if ( fgGetBool("/sim/panel-hotspots") ) {
474     static osg::ref_ptr<osg::StateSet> hotspotStateSet;
475     if (!hotspotStateSet.valid()) {
476       hotspotStateSet = new osg::StateSet;
477       hotspotStateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
478       hotspotStateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
479     }
480
481     state.pushStateSet(hotspotStateSet.get());
482     state.apply();
483
484     glPushAttrib(GL_ENABLE_BIT);
485     glDisable(GL_COLOR_MATERIAL);
486     glColor3f(1, 1, 0);
487     
488     for ( unsigned int i = 0; i < _instruments.size(); i++ )
489       _instruments[i]->drawHotspots(state);
490
491     glPopAttrib();
492
493     state.popStateSet();
494     state.apply();
495   }
496 }
497
498 /**
499  * Set the panel's visibility.
500  */
501 void
502 FGPanel::setVisibility (bool visibility)
503 {
504   _visibility->setBoolValue( visibility );
505 }
506
507
508 /**
509  * Return true if the panel is visible.
510  */
511 bool
512 FGPanel::getVisibility () const
513 {
514   return _visibility->getBoolValue();
515 }
516
517
518 /**
519  * Set the panel's background texture.
520  */
521 void
522 FGPanel::setBackground (osg::Texture2D* texture)
523 {
524   osg::StateSet* stateSet = new osg::StateSet;
525   stateSet->setTextureAttribute(0, texture);
526   stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
527   stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
528   _bg = stateSet;
529 }
530
531 /**
532  * Set the panel's multiple background textures.
533  */
534 void
535 FGPanel::setMultiBackground (osg::Texture2D* texture, int idx)
536 {
537   _bg = 0;
538
539   osg::StateSet* stateSet = new osg::StateSet;
540   stateSet->setTextureAttribute(0, texture);
541   stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
542   stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
543   _mbg[idx] = stateSet;
544 }
545
546 /**
547  * Set the panel's x-offset.
548  */
549 void
550 FGPanel::setXOffset (int offset)
551 {
552   if (offset <= 0 && offset >= -_width + WIN_W)
553     _x_offset->setIntValue( offset );
554 }
555
556
557 /**
558  * Set the panel's y-offset.
559  */
560 void
561 FGPanel::setYOffset (int offset)
562 {
563   if (offset <= 0 && offset >= -_height)
564     _y_offset->setIntValue( offset );
565 }
566
567 /**
568  * Handle a mouse action in panel-local (not screen) coordinates.
569  * Used by the 3D panel code in Model/panelnode.cxx, in situations
570  * where the panel doesn't control its own screen location.
571  */
572 bool
573 FGPanel::doLocalMouseAction(int button, int updown, int x, int y)
574 {
575   // Note a released button and return
576   if (updown == 1) {
577     if (_mouseInstrument != 0)
578         _mouseInstrument->doMouseAction(_mouseButton, 1, _mouseX, _mouseY);
579     _mouseDown = false;
580     _mouseInstrument = 0;
581     return false;
582   }
583
584   // Search for a matching instrument.
585   for (int i = 0; i < (int)_instruments.size(); i++) {
586     FGPanelInstrument *inst = _instruments[i];
587     int ix = inst->getXPos();
588     int iy = inst->getYPos();
589     int iw = inst->getWidth() / 2;
590     int ih = inst->getHeight() / 2;
591     if (x >= ix - iw && x < ix + iw && y >= iy - ih && y < iy + ih) {
592       _mouseDown = true;
593       _mouseDelay = 20;
594       _mouseInstrument = inst;
595       _mouseButton = button;
596       _mouseX = x - ix;
597       _mouseY = y - iy;
598       // Always do the action once.
599       return _mouseInstrument->doMouseAction(_mouseButton, 0,
600                                              _mouseX, _mouseY);
601     }
602   }
603   return false;
604 }
605
606 /**
607  * Perform a mouse action.
608  */
609 bool
610 FGPanel::doMouseAction (int button, int updown, int x, int y)
611 {
612                                 // FIXME: this same code appears in update()
613   int xsize = _xsize_node->getIntValue();
614   int ysize = _ysize_node->getIntValue();
615   float aspect_adjust = get_aspect_adjust(xsize, ysize);
616
617                                 // Scale for the real window size.
618   if (aspect_adjust < 1.0) {
619     x = int(((float)x / xsize) * WIN_W * aspect_adjust);
620     y = int(WIN_H - ((float(y) / ysize) * WIN_H));
621   } else {
622     x = int(((float)x / xsize) * WIN_W);
623     y = int((WIN_H - ((float(y) / ysize) * WIN_H)) / aspect_adjust);
624   }
625
626                                 // Adjust for offsets.
627   x -= _x_offset->getIntValue();
628   y -= _y_offset->getIntValue();
629
630   // Having fixed up the coordinates, fall through to the local
631   // coordinate handler.
632   return doLocalMouseAction(button, updown, x, y);
633
634
635 void FGPanel::setDepthTest (bool enable) {
636     _enable_depth_test = enable;
637 }
638
639
640 \f
641 ////////////////////////////////////////////////////////////////////////.
642 // Implementation of FGPanelAction.
643 ////////////////////////////////////////////////////////////////////////
644
645 FGPanelAction::FGPanelAction ()
646 {
647 }
648
649 FGPanelAction::FGPanelAction (int button, int x, int y, int w, int h,
650                               bool repeatable)
651     : _button(button), _x(x), _y(y), _w(w), _h(h), _repeatable(repeatable)
652 {
653 }
654
655 FGPanelAction::~FGPanelAction ()
656 {
657   for (unsigned int i = 0; i < 2; i++) {
658       for (unsigned int j = 0; j < _bindings[i].size(); j++)
659           delete _bindings[i][j];
660   }
661 }
662
663 void
664 FGPanelAction::addBinding (FGBinding * binding, int updown)
665 {
666   _bindings[updown].push_back(binding);
667 }
668
669 bool
670 FGPanelAction::doAction (int updown)
671 {
672   if (test()) {
673     if ((updown != _last_state) || (updown == 0 && _repeatable)) {
674         int nBindings = _bindings[updown].size();
675         for (int i = 0; i < nBindings; i++)
676             _bindings[updown][i]->fire();
677     }
678     _last_state = updown;
679     return true;
680   } else {
681     return false;
682   }
683 }
684
685
686 \f
687 ////////////////////////////////////////////////////////////////////////
688 // Implementation of FGPanelTransformation.
689 ////////////////////////////////////////////////////////////////////////
690
691 FGPanelTransformation::FGPanelTransformation ()
692   : table(0)
693 {
694 }
695
696 FGPanelTransformation::~FGPanelTransformation ()
697 {
698   delete table;
699 }
700
701
702 \f
703 ////////////////////////////////////////////////////////////////////////
704 // Implementation of FGPanelInstrument.
705 ////////////////////////////////////////////////////////////////////////
706
707
708 FGPanelInstrument::FGPanelInstrument ()
709 {
710   setPosition(0, 0);
711   setSize(0, 0);
712 }
713
714 FGPanelInstrument::FGPanelInstrument (int x, int y, int w, int h)
715 {
716   setPosition(x, y);
717   setSize(w, h);
718 }
719
720 FGPanelInstrument::~FGPanelInstrument ()
721 {
722   for (action_list_type::iterator it = _actions.begin();
723        it != _actions.end();
724        it++) {
725     delete *it;
726     *it = 0;
727   }
728 }
729
730 void
731 FGPanelInstrument::drawHotspots(osg::State& state)
732 {
733   for ( unsigned int i = 0; i < _actions.size(); i++ ) {
734     FGPanelAction* a = _actions[i];
735     float x1 = getXPos() + a->getX();
736     float x2 = x1 + a->getWidth();
737     float y1 = getYPos() + a->getY();
738     float y2 = y1 + a->getHeight();
739
740     glBegin(GL_LINE_LOOP);
741     glVertex2f(x1, y1);
742     glVertex2f(x1, y2);
743     glVertex2f(x2, y2);
744     glVertex2f(x2, y1);
745     glEnd();
746   }
747 }
748
749 void
750 FGPanelInstrument::setPosition (int x, int y)
751 {
752   _x = x;
753   _y = y;
754 }
755
756 void
757 FGPanelInstrument::setSize (int w, int h)
758 {
759   _w = w;
760   _h = h;
761 }
762
763 int
764 FGPanelInstrument::getXPos () const
765 {
766   return _x;
767 }
768
769 int
770 FGPanelInstrument::getYPos () const
771 {
772   return _y;
773 }
774
775 int
776 FGPanelInstrument::getWidth () const
777 {
778   return _w;
779 }
780
781 int
782 FGPanelInstrument::getHeight () const
783 {
784   return _h;
785 }
786
787 void
788 FGPanelInstrument::addAction (FGPanelAction * action)
789 {
790   _actions.push_back(action);
791 }
792
793                                 // Coordinates relative to centre.
794 bool
795 FGPanelInstrument::doMouseAction (int button, int updown, int x, int y)
796 {
797   if (test()) {
798     action_list_type::iterator it = _actions.begin();
799     action_list_type::iterator last = _actions.end();
800     for ( ; it != last; it++) {
801       if ((*it)->inArea(button, x, y) &&
802           (*it)->doAction(updown))
803         return true;
804     }
805   }
806   return false;
807 }
808
809
810 \f
811 ////////////////////////////////////////////////////////////////////////
812 // Implementation of FGLayeredInstrument.
813 ////////////////////////////////////////////////////////////////////////
814
815 FGLayeredInstrument::FGLayeredInstrument (int x, int y, int w, int h)
816   : FGPanelInstrument(x, y, w, h)
817 {
818 }
819
820 FGLayeredInstrument::~FGLayeredInstrument ()
821 {
822   for (layer_list::iterator it = _layers.begin(); it != _layers.end(); it++) {
823     delete *it;
824     *it = 0;
825   }
826 }
827
828 void
829 FGLayeredInstrument::draw (osg::State& state)
830 {
831   if (!test())
832     return;
833   
834   for (int i = 0; i < (int)_layers.size(); i++) {
835     glPushMatrix();
836     _layers[i]->draw(state);
837     glPopMatrix();
838   }
839 }
840
841 int
842 FGLayeredInstrument::addLayer (FGInstrumentLayer *layer)
843 {
844   int n = _layers.size();
845   if (layer->getWidth() == -1) {
846     layer->setWidth(getWidth());
847   }
848   if (layer->getHeight() == -1) {
849     layer->setHeight(getHeight());
850   }
851   _layers.push_back(layer);
852   return n;
853 }
854
855 int
856 FGLayeredInstrument::addLayer (const FGCroppedTexture &texture,
857                                int w, int h)
858 {
859   return addLayer(new FGTexturedLayer(texture, w, h));
860 }
861
862 void
863 FGLayeredInstrument::addTransformation (FGPanelTransformation * transformation)
864 {
865   int layer = _layers.size() - 1;
866   _layers[layer]->addTransformation(transformation);
867 }
868
869
870 \f
871 ////////////////////////////////////////////////////////////////////////
872 // Implementation of FGSpecialInstrument.
873 ////////////////////////////////////////////////////////////////////////
874
875 FGSpecialInstrument::FGSpecialInstrument (DCLGPS* sb)
876   : FGPanelInstrument()
877 {
878   complex = sb;
879 }
880
881 FGSpecialInstrument::~FGSpecialInstrument ()
882 {
883 }
884
885 void
886 FGSpecialInstrument::draw (osg::State& state)
887 {
888   complex->draw();
889 }
890
891
892 \f
893 ////////////////////////////////////////////////////////////////////////
894 // Implementation of FGInstrumentLayer.
895 ////////////////////////////////////////////////////////////////////////
896
897 FGInstrumentLayer::FGInstrumentLayer (int w, int h)
898   : _w(w),
899     _h(h)
900 {
901 }
902
903 FGInstrumentLayer::~FGInstrumentLayer ()
904 {
905   for (transformation_list::iterator it = _transformations.begin();
906        it != _transformations.end();
907        it++) {
908     delete *it;
909     *it = 0;
910   }
911 }
912
913 void
914 FGInstrumentLayer::transform () const
915 {
916   transformation_list::const_iterator it = _transformations.begin();
917   transformation_list::const_iterator last = _transformations.end();
918   while (it != last) {
919     FGPanelTransformation *t = *it;
920     if (t->test()) {
921       float val = (t->node == 0 ? 0.0 : t->node->getFloatValue());
922
923       if (t->has_mod)
924           val = fmod(val, t->mod);
925       if (val < t->min) {
926         val = t->min;
927       } else if (val > t->max) {
928         val = t->max;
929       }
930
931       if (t->table==0) {
932         val = val * t->factor + t->offset;
933       } else {
934         val = t->table->interpolate(val) * t->factor + t->offset;
935       }
936       
937       switch (t->type) {
938       case FGPanelTransformation::XSHIFT:
939         glTranslatef(val, 0.0, 0.0);
940         break;
941       case FGPanelTransformation::YSHIFT:
942         glTranslatef(0.0, val, 0.0);
943         break;
944       case FGPanelTransformation::ROTATION:
945         glRotatef(-val, 0.0, 0.0, 1.0);
946         break;
947       }
948     }
949     it++;
950   }
951 }
952
953 void
954 FGInstrumentLayer::addTransformation (FGPanelTransformation * transformation)
955 {
956   _transformations.push_back(transformation);
957 }
958
959
960 \f
961 ////////////////////////////////////////////////////////////////////////
962 // Implementation of FGGroupLayer.
963 ////////////////////////////////////////////////////////////////////////
964
965 FGGroupLayer::FGGroupLayer ()
966 {
967 }
968
969 FGGroupLayer::~FGGroupLayer ()
970 {
971   for (unsigned int i = 0; i < _layers.size(); i++)
972     delete _layers[i];
973 }
974
975 void
976 FGGroupLayer::draw (osg::State& state)
977 {
978   if (test()) {
979     transform();
980     int nLayers = _layers.size();
981     for (int i = 0; i < nLayers; i++)
982       _layers[i]->draw(state);
983   }
984 }
985
986 void
987 FGGroupLayer::addLayer (FGInstrumentLayer * layer)
988 {
989   _layers.push_back(layer);
990 }
991
992
993 \f
994 ////////////////////////////////////////////////////////////////////////
995 // Implementation of FGTexturedLayer.
996 ////////////////////////////////////////////////////////////////////////
997
998
999 FGTexturedLayer::FGTexturedLayer (const FGCroppedTexture &texture, int w, int h)
1000   : FGInstrumentLayer(w, h),
1001     _emissive(false)
1002 {
1003   setTexture(texture);
1004 }
1005
1006
1007 FGTexturedLayer::~FGTexturedLayer ()
1008 {
1009 }
1010
1011
1012 void
1013 FGTexturedLayer::draw (osg::State& state)
1014 {
1015   if (test()) {
1016     int w2 = _w / 2;
1017     int h2 = _h / 2;
1018     
1019     transform();
1020     state.pushStateSet(_texture.getTexture());
1021     state.apply();
1022     glBegin(GL_POLYGON);
1023
1024     if (_emissive) {
1025       glColor4fv( emissive_panel_color );
1026     } else {
1027                                 // From Curt: turn on the panel
1028                                 // lights after sundown.
1029       glColor4fv( panel_color );
1030     }
1031
1032     glTexCoord2f(_texture.getMinX(), _texture.getMinY()); glVertex2f(-w2, -h2);
1033     glTexCoord2f(_texture.getMaxX(), _texture.getMinY()); glVertex2f(w2, -h2);
1034     glTexCoord2f(_texture.getMaxX(), _texture.getMaxY()); glVertex2f(w2, h2);
1035     glTexCoord2f(_texture.getMinX(), _texture.getMaxY()); glVertex2f(-w2, h2);
1036     glEnd();
1037     state.popStateSet();
1038     state.apply();
1039   }
1040 }
1041
1042
1043 \f
1044 ////////////////////////////////////////////////////////////////////////
1045 // Implementation of FGTextLayer.
1046 ////////////////////////////////////////////////////////////////////////
1047
1048 FGTextLayer::FGTextLayer (int w, int h)
1049   : FGInstrumentLayer(w, h), _pointSize(14.0), _font_name("Helvetica.txf")
1050 {
1051   _then.stamp();
1052   _color[0] = _color[1] = _color[2] = 0.0;
1053   _color[3] = 1.0;
1054 }
1055
1056 FGTextLayer::~FGTextLayer ()
1057 {
1058   chunk_list::iterator it = _chunks.begin();
1059   chunk_list::iterator last = _chunks.end();
1060   for ( ; it != last; it++) {
1061     delete *it;
1062   }
1063 }
1064
1065 void
1066 FGTextLayer::draw (osg::State& state)
1067 {
1068   if (test()) {
1069     glColor4fv(_color);
1070     transform();
1071
1072     FGFontCache *fc = globals->get_fontcache();
1073     text_renderer.setFont(fc->getTexFont(_font_name.c_str()));
1074
1075     text_renderer.setPointSize(_pointSize);
1076     text_renderer.begin();
1077     text_renderer.start3f(0, 0, 0);
1078
1079     _now.stamp();
1080     long diff = _now - _then;
1081
1082     if (diff > 100000 || diff < 0 ) {
1083       // ( diff < 0 ) is a sanity check and indicates our time stamp
1084       // difference math probably overflowed.  We can handle a max
1085       // difference of 35.8 minutes since the returned value is in
1086       // usec.  So if the panel is left off longer than that we can
1087       // over flow the math with it is turned back on.  This (diff <
1088       // 0) catches that situation, get's us out of trouble, and
1089       // back on track.
1090       recalc_value();
1091       _then = _now;
1092     }
1093
1094     // Something is goofy.  The code in this file renders only CCW
1095     // polygons, and I have verified that the font code in plib
1096     // renders only CCW trianbles.  Yet they come out backwards.
1097     // Something around here or in plib is either changing the winding
1098     // order or (more likely) pushing a left-handed matrix onto the
1099     // stack.  But I can't find it; get out the chainsaw...
1100     glFrontFace(GL_CW);
1101     text_renderer.puts((char *)(_value.c_str()));
1102     glFrontFace(GL_CCW);
1103
1104     text_renderer.end();
1105     glColor4f(1.0, 1.0, 1.0, 1.0);      // FIXME
1106   }
1107 }
1108
1109 void
1110 FGTextLayer::addChunk (FGTextLayer::Chunk * chunk)
1111 {
1112   _chunks.push_back(chunk);
1113 }
1114
1115 void
1116 FGTextLayer::setColor (float r, float g, float b)
1117 {
1118   _color[0] = r;
1119   _color[1] = g;
1120   _color[2] = b;
1121   _color[3] = 1.0;
1122 }
1123
1124 void
1125 FGTextLayer::setPointSize (float size)
1126 {
1127   _pointSize = size;
1128 }
1129
1130 void
1131 FGTextLayer::setFontName(const string &name)
1132 {
1133   _font_name = name + ".txf";
1134 }
1135
1136
1137 void
1138 FGTextLayer::setFont(fntFont * font)
1139 {
1140   text_renderer.setFont(font);
1141 }
1142
1143
1144 void
1145 FGTextLayer::recalc_value () const
1146 {
1147   _value = "";
1148   chunk_list::const_iterator it = _chunks.begin();
1149   chunk_list::const_iterator last = _chunks.end();
1150   for ( ; it != last; it++) {
1151     _value += (*it)->getValue();
1152   }
1153 }
1154
1155
1156 \f
1157 ////////////////////////////////////////////////////////////////////////
1158 // Implementation of FGTextLayer::Chunk.
1159 ////////////////////////////////////////////////////////////////////////
1160
1161 FGTextLayer::Chunk::Chunk (const string &text, const string &fmt)
1162   : _type(FGTextLayer::TEXT), _fmt(fmt)
1163 {
1164   _text = text;
1165   if (_fmt.empty()) 
1166     _fmt = "%s";
1167 }
1168
1169 FGTextLayer::Chunk::Chunk (ChunkType type, const SGPropertyNode * node,
1170                            const string &fmt, float mult, float offs,
1171                            bool truncation)
1172   : _type(type), _fmt(fmt), _mult(mult), _offs(offs), _trunc(truncation)
1173 {
1174   if (_fmt.empty()) {
1175     if (type == TEXT_VALUE)
1176       _fmt = "%s";
1177     else
1178       _fmt = "%.2f";
1179   }
1180   _node = node;
1181 }
1182
1183 const char *
1184 FGTextLayer::Chunk::getValue () const
1185 {
1186   if (test()) {
1187     _buf[0] = '\0';
1188     switch (_type) {
1189     case TEXT:
1190       sprintf(_buf, _fmt.c_str(), _text.c_str());
1191       return _buf;
1192     case TEXT_VALUE:
1193       sprintf(_buf, _fmt.c_str(), _node->getStringValue());
1194       break;
1195     case DOUBLE_VALUE:
1196       double d = _offs + _node->getFloatValue() * _mult;
1197       if (_trunc)  d = (d < 0) ? -floor(-d) : floor(d);
1198       sprintf(_buf, _fmt.c_str(), d);
1199       break;
1200     }
1201     return _buf;
1202   } else {
1203     return "";
1204   }
1205 }
1206
1207
1208 \f
1209 ////////////////////////////////////////////////////////////////////////
1210 // Implementation of FGSwitchLayer.
1211 ////////////////////////////////////////////////////////////////////////
1212
1213 FGSwitchLayer::FGSwitchLayer ()
1214   : FGGroupLayer()
1215 {
1216 }
1217
1218 void
1219 FGSwitchLayer::draw (osg::State& state)
1220 {
1221   if (test()) {
1222     transform();
1223     int nLayers = _layers.size();
1224     for (int i = 0; i < nLayers; i++) {
1225       if (_layers[i]->test()) {
1226           _layers[i]->draw(state);
1227           return;
1228       }
1229     }
1230   }
1231 }
1232
1233 \f
1234 // end of panel.cxx