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