]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/HUD/HUD.cxx
Merge branch 'curt/replay'
[flightgear.git] / src / Instrumentation / HUD / HUD.cxx
1 // HUD.cxx -- Head Up Display
2 //
3 // Written by Michele America, started September 1997.
4 //
5 // Copyright (C) 1997  Michele F. America  [micheleamerica#geocities:com]
6 // Copyright (C) 2006  Melchior FRANZ  [mfranz#aon:at]
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21
22 #include <simgear/compiler.h>
23 #include <simgear/structure/exception.hxx>
24
25 #include <string>
26 #include <fstream>
27
28 #ifdef HAVE_CONFIG_H
29 #  include <config.h>
30 #endif
31
32 #include <simgear/constants.h>
33 #include <simgear/misc/sg_path.hxx>
34 #include <osg/GLU>
35
36 #include <Main/globals.hxx>
37 #include <Main/viewmgr.hxx>
38 #include <Main/viewer.hxx>
39
40 #include "HUD.hxx"
41
42
43 static float clamp(float f)
44 {
45     return f < 0.0f ? 0.0f : f > 1.0f ? 1.0f : f;
46 }
47
48
49 HUD::HUD() :
50     _path(fgGetNode("/sim/hud/path[1]", "Huds/default.xml")),
51     _current(fgGetNode("/sim/hud/current-color", true)),
52     _visibility(fgGetNode("/sim/hud/visibility[1]", true)),
53     _3DenabledN(fgGetNode("/sim/hud/enable3d[1]", true)),
54     _antialiasing(fgGetNode("/sim/hud/color/antialiased", true)),
55     _transparency(fgGetNode("/sim/hud/color/transparent", true)),
56     _red(fgGetNode("/sim/hud/color/red", true)),
57     _green(fgGetNode("/sim/hud/color/green", true)),
58     _blue(fgGetNode("/sim/hud/color/blue", true)),
59     _alpha(fgGetNode("/sim/hud/color/alpha", true)),
60     _alpha_clamp(fgGetNode("/sim/hud/color/alpha-clamp", true)),
61     _brightness(fgGetNode("/sim/hud/color/brightness", true)),
62     _visible(false),
63     _antialiased(false),
64     _transparent(false),
65     _a(0.67),                                                                   // FIXME better names
66     _cl(0.01),
67     //
68     _scr_widthN(fgGetNode("/sim/startup/xsize", true)),
69     _scr_heightN(fgGetNode("/sim/startup/ysize", true)),
70     _unitsN(fgGetNode("/sim/startup/units", true)),
71     _timer(0.0),
72     //
73     _font_renderer(new fntRenderer()),
74     _font(0),
75     _font_size(0.0),
76     _style(0),
77     _listener_active(false),
78     _clip_box(0)
79 {
80     SG_LOG(SG_COCKPIT, SG_INFO, "Initializing HUD Instrument");
81
82     _path->addChangeListener(this);
83     _visibility->addChangeListener(this);
84     _3DenabledN->addChangeListener(this);
85     _antialiasing->addChangeListener(this);
86     _transparency->addChangeListener(this);
87     _red->addChangeListener(this);
88     _green->addChangeListener(this);
89     _blue->addChangeListener(this);
90     _alpha->addChangeListener(this);
91     _alpha_clamp->addChangeListener(this);
92     _brightness->addChangeListener(this);
93     _current->addChangeListener(this);
94     _scr_widthN->addChangeListener(this);
95     _scr_heightN->addChangeListener(this);
96     _unitsN->addChangeListener(this, true);
97 }
98
99
100 HUD::~HUD()
101 {
102     _path->removeChangeListener(this);
103     _visibility->removeChangeListener(this);
104     _3DenabledN->removeChangeListener(this);
105     _antialiasing->removeChangeListener(this);
106     _transparency->removeChangeListener(this);
107     _red->removeChangeListener(this);
108     _green->removeChangeListener(this);
109     _blue->removeChangeListener(this);
110     _alpha->removeChangeListener(this);
111     _alpha_clamp->removeChangeListener(this);
112     _brightness->removeChangeListener(this);
113     _current->removeChangeListener(this);
114     _scr_widthN->removeChangeListener(this);
115     _scr_heightN->removeChangeListener(this);
116     _unitsN->removeChangeListener(this);
117     delete _font_renderer;
118     delete _clip_box;
119
120     deque<Item *>::const_iterator it, end = _items.end();
121     for (it = _items.begin(); it != end; ++it)
122         delete *it;
123     end = _ladders.end();
124     for (it = _ladders.begin(); it != end; ++it)
125         delete *it;
126 }
127
128
129 void HUD::init()
130 {
131     const char* fontName = 0;
132     _font_cache = globals->get_fontcache();
133     if (!_font) {
134         fontName = fgGetString("/sim/hud/font/name", "Helvetica.txf");
135         _font = _font_cache->getTexFont(fontName);
136     }
137     if (!_font)
138         throw sg_io_exception("/sim/hud/font/name is not a texture font",
139                               sg_location(fontName));
140
141     _font_size = fgGetFloat("/sim/hud/font/size", 8);
142     _font_renderer->setFont(_font);
143     _font_renderer->setPointSize(_font_size);
144     _text_list.setFont(_font_renderer);
145
146     _path->fireValueChanged();
147 }
148
149
150 void HUD::update(double dt)
151 {
152     _timer += dt;
153 }
154
155
156 void HUD::draw(osg::State&)
157 {
158     if (!isVisible())
159         return;
160
161     if (!_items.size() && !_ladders.size())
162         return;
163
164     if (is3D()) {
165         draw3D();
166         return;
167     }
168
169     const float normal_aspect = 640.0f / 480.0f;
170     // note: aspect_ratio is Y/X
171     float current_aspect = 1.0f / globals->get_current_view()->get_aspect_ratio();
172     if (current_aspect > normal_aspect) {
173         float aspect_adjust = current_aspect / normal_aspect;
174         float adjust = 320.0f * aspect_adjust - 320.0f;
175         draw2D(-adjust, 0.0f, 640.0f + adjust, 480.0f);
176
177     } else {
178         float aspect_adjust = normal_aspect / current_aspect;
179         float adjust = 240.0f * aspect_adjust - 240.0f;
180         draw2D(0.0f, -adjust, 640.0f, 480.0f + adjust);
181     }
182
183     glViewport(0, 0, _scr_width, _scr_height);
184 }
185
186
187 void HUD::draw3D()
188 {
189     FGViewer* view = globals->get_current_view();
190
191     // Standard fgfs projection, with essentially meaningless clip
192     // planes (we'll map the whole HUD plane to z=-1)
193     glMatrixMode(GL_PROJECTION);
194     glPushMatrix();
195     glLoadIdentity();
196     gluPerspective(view->get_v_fov(), 1.0 / view->get_aspect_ratio(), 0.1, 10);
197
198     glMatrixMode(GL_MODELVIEW);
199     glPushMatrix();
200     glLoadIdentity();
201
202     // Standard fgfs view direction computation
203     float lookat[3];
204     lookat[0] = -sin(SG_DEGREES_TO_RADIANS * view->getHeadingOffset_deg());
205     lookat[1] = tan(SG_DEGREES_TO_RADIANS * view->getPitchOffset_deg());
206     lookat[2] = -cos(SG_DEGREES_TO_RADIANS * view->getHeadingOffset_deg());
207     if (fabs(lookat[1]) > 9999)
208         lookat[1] = 9999; // FPU sanity
209     gluLookAt(0, 0, 0, lookat[0], lookat[1], lookat[2], 0, 1, 0);
210
211     // Map the -1:1 square to a 55.0x41.25 degree wide patch at z=1.
212     // This is the default fgfs field of view, which the HUD files are
213     // written to assume.
214     float dx = 0.52056705; // tan(55/2)
215     float dy = dx * 0.75;  // assumes 4:3 aspect ratio
216     float m[16];
217     m[0] = dx, m[4] =  0, m[ 8] = 0, m[12] = 0;
218     m[1] =  0, m[5] = dy, m[ 9] = 0, m[13] = 0;
219     m[2] =  0, m[6] =  0, m[10] = 1, m[14] = 0;
220     m[3] =  0, m[7] =  0, m[11] = 0, m[15] = 1;
221     glMultMatrixf(m);
222
223     // Convert the 640x480 "HUD standard" coordinate space to a square
224     // about the origin in the range [-1:1] at depth of -1
225     glScalef(1.0 / 320, 1.0 / 240, 1);
226     glTranslatef(-320, -240, -1);
227
228     common_draw();
229
230     glMatrixMode(GL_PROJECTION);
231     glPopMatrix();
232     glMatrixMode(GL_MODELVIEW);
233     glPopMatrix();
234 }
235
236
237 void HUD::draw2D(GLfloat x_start, GLfloat y_start, GLfloat x_end, GLfloat y_end)
238 {
239     glMatrixMode(GL_PROJECTION);
240     glPushMatrix();
241     glLoadIdentity();
242     gluOrtho2D(x_start, x_end, y_start, y_end);
243
244     glMatrixMode(GL_MODELVIEW);
245     glPushMatrix();
246     glLoadIdentity();
247
248     common_draw();
249
250     glMatrixMode(GL_PROJECTION);
251     glPopMatrix();
252     glMatrixMode(GL_MODELVIEW);
253     glPopMatrix();
254 }
255
256
257 void HUD::common_draw()
258 {
259     _text_list.erase();
260     _line_list.erase();
261     _stipple_line_list.erase();
262
263     glDisable(GL_DEPTH_TEST);
264     glDisable(GL_LIGHTING);
265
266     glEnable(GL_BLEND);
267     if (isTransparent())
268         glBlendFunc(GL_SRC_ALPHA, GL_ONE);
269     else
270         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
271
272     if (isAntialiased()) {
273         glEnable(GL_LINE_SMOOTH);
274         glAlphaFunc(GL_GREATER, alphaClamp());
275         glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
276         //glLineWidth(1.5);
277     } else {
278         //glLineWidth(1.0);
279     }
280
281     setColor();
282     _clip_box->set();
283
284     deque<Item *>::const_iterator it, end = _items.end();
285     for (it = _items.begin(); it != end; ++it)
286         if ((*it)->isEnabled())
287             (*it)->draw();
288
289     _text_list.draw();
290     _line_list.draw();
291
292     if (_stipple_line_list.size()) {
293         glEnable(GL_LINE_STIPPLE);
294         glLineStipple(1, 0x00FF);
295         _stipple_line_list.draw();
296         glDisable(GL_LINE_STIPPLE);
297     }
298
299     // ladders last, as they can have their own clip planes
300     end = _ladders.end();
301     for (it = _ladders.begin(); it != end; ++it)
302         if ((*it)->isEnabled())
303             (*it)->draw();
304
305     _clip_box->unset();
306
307     if (isAntialiased()) {
308         glDisable(GL_ALPHA_TEST);
309         glDisable(GL_LINE_SMOOTH);
310         //glLineWidth(1.0);
311     }
312
313     if (isTransparent())
314         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
315
316     glEnable(GL_DEPTH_TEST);
317     glEnable(GL_LIGHTING);
318 }
319
320
321 int HUD::load(const char *file, float x, float y, int level, const string& indent)
322 {
323     const sgDebugPriority TREE = SG_INFO;
324     const int MAXNEST = 10;
325
326     SGPath path(globals->get_fg_root());
327     path.append(file);
328
329     if (!level) {
330         SG_LOG(SG_INPUT, TREE, endl << "load " << file);
331         _items.erase(_items.begin(), _items.end());
332         _ladders.erase(_ladders.begin(), _ladders.end());
333     } else if (level > MAXNEST) {
334         SG_LOG(SG_INPUT, SG_ALERT, "HUD: files nested more than " << MAXNEST << " levels");
335         return 0x1;
336     } else if (!file || !file[0]) {
337         SG_LOG(SG_INPUT, SG_ALERT, "HUD: invalid filename ");
338         return 0x2;
339     }
340
341     int ret = 0;
342     ifstream input(path.c_str());
343     if (!input.good()) {
344         SG_LOG(SG_INPUT, SG_ALERT, "HUD: Cannot read configuration from " << path.str());
345         return 0x4;
346     }
347
348     SGPropertyNode root;
349     try {
350         readProperties(input, &root);
351     } catch (const sg_exception &e) {
352         input.close();
353         guiErrorMessage("HUD: Error ", e);
354         return 0x8;
355     }
356
357     delete _clip_box;
358     _clip_box = new ClipBox(fgGetNode("/sim/hud/clipping"), x, y);
359
360     for (int i = 0; i < root.nChildren(); i++) {
361         SGPropertyNode *n = root.getChild(i);
362         const char *d = n->getStringValue("name", 0);
363         string desc;
364         if (d)
365             desc = string(": \"") + d + '"';
366
367         const char *name = n->getName();
368         if (!strcmp(name, "name")) {
369             continue;
370
371         } else if (!strcmp(name, "enable3d")) {
372             // set in the tree so that valueChanged() picks it up
373             _3DenabledN->setBoolValue(n->getBoolValue());
374             continue;
375
376         } else if (!strcmp(name, "import")) {
377             const char *fn = n->getStringValue("path", "");
378             float xoffs = n->getFloatValue("x-offset", 0.0f);
379             float yoffs = n->getFloatValue("y-offset", 0.0f);
380
381             SG_LOG(SG_INPUT, TREE, indent << "|__import " << fn << desc);
382
383             string ind = indent + string(i + 1 < root.nChildren() ? "|    " : "     ");
384             ret |= load(fn, x + xoffs, y + yoffs, level + 1, ind);
385             continue;
386         }
387
388         SG_LOG(SG_INPUT, TREE, indent << "|__" << name << desc);
389
390         Item *item;
391         if (!strcmp(name, "label")) {
392             item = static_cast<Item *>(new Label(this, n, x, y));
393         } else if (!strcmp(name, "gauge")) {
394             item = static_cast<Item *>(new Gauge(this, n, x, y));
395         } else if (!strcmp(name, "tape")) {
396             item = static_cast<Item *>(new Tape(this, n, x, y));
397         } else if (!strcmp(name, "dial")) {
398             item = static_cast<Item *>(new Dial(this, n, x, y));
399         } else if (!strcmp(name, "turn-bank-indicator")) {
400             item = static_cast<Item *>(new TurnBankIndicator(this, n, x, y));
401         } else if (!strcmp(name, "ladder")) {
402             item = static_cast<Item *>(new Ladder(this, n, x, y));
403             _ladders.insert(_ladders.begin(), item);
404             continue;
405         } else if (!strcmp(name, "runway")) {
406             item = static_cast<Item *>(new Runway(this, n, x, y));
407         } else if (!strcmp(name, "aiming-reticle")) {
408             item = static_cast<Item *>(new AimingReticle(this, n, x, y));
409         } else {
410             SG_LOG(SG_INPUT, TREE, indent << "      \\...unsupported!");
411             continue;
412         }
413         _items.insert(_items.begin(), item);
414     }
415     input.close();
416     SG_LOG(SG_INPUT, TREE, indent);
417     return ret;
418 }
419
420
421 void HUD::valueChanged(SGPropertyNode *node)
422 {
423     if (_listener_active)
424         return;
425     _listener_active = true;
426     if (!strcmp(node->getName(), "path"))
427         load(fgGetString("/sim/hud/path[1]", "Huds/default.xml"));
428
429     if (!strcmp(node->getName(), "current-color")) {
430         int i = node->getIntValue();
431         if (i < 0)
432             i = 0;
433         SGPropertyNode *n = fgGetNode("/sim/hud/palette", true);
434         if ((n = n->getChild("color", i, false))) {
435             if (n->hasValue("red"))
436                 _red->setFloatValue(n->getFloatValue("red", 1.0));
437             if (n->hasValue("green"))
438                 _green->setFloatValue(n->getFloatValue("green", 1.0));
439             if (n->hasValue("blue"))
440                 _blue->setFloatValue(n->getFloatValue("blue", 1.0));
441             if (n->hasValue("alpha"))
442                 _alpha->setFloatValue(n->getFloatValue("alpha", 0.67));
443             if (n->hasValue("alpha-clamp"))
444                 _alpha_clamp->setFloatValue(n->getFloatValue("alpha-clamp", 0.01));
445             if (n->hasValue("brightness"))
446                 _brightness->setFloatValue(n->getFloatValue("brightness", 0.75));
447             if (n->hasValue("antialiased"))
448                 _antialiasing->setBoolValue(n->getBoolValue("antialiased", false));
449             if (n->hasValue("transparent"))
450                 _transparency->setBoolValue(n->getBoolValue("transparent", false));
451         }
452     }
453     _scr_width = _scr_widthN->getIntValue();
454     _scr_height = _scr_heightN->getIntValue();
455
456     _visible = _visibility->getBoolValue();
457     _3Denabled = _3DenabledN->getBoolValue();
458     _transparent = _transparency->getBoolValue();
459     _antialiased = _antialiasing->getBoolValue();
460     float brt = _brightness->getFloatValue();
461     _r = clamp(brt * _red->getFloatValue());
462     _g = clamp(brt * _green->getFloatValue());
463     _b = clamp(brt * _blue->getFloatValue());
464     _a = clamp(_alpha->getFloatValue());
465     _cl = clamp(_alpha_clamp->getFloatValue());
466
467     _units = strcmp(_unitsN->getStringValue(), "feet") ? METER : FEET;
468     _listener_active = false;
469 }
470
471
472 void HUD::setColor() const
473 {
474     if (_antialiased)
475         glColor4f(_r, _g, _b, _a);
476     else
477         glColor3f(_r, _g, _b);
478 }
479
480
481 void HUD::textAlign(fntRenderer *rend, const char *s, int align,
482         float *x, float *y, float *l, float *r, float *b, float *t)
483 {
484     fntFont *font = rend->getFont();
485     float gap = font->getGap();
486     float left, right, bot, top;
487     font->getBBox(s, rend->getPointSize(), rend->getSlant(), &left, &right, &bot, &top);
488
489     if (align & HUD::HCENTER)
490         *x -= left - gap + (right - left - gap) / 2.0;
491     else if (align & HUD::RIGHT)
492         *x -= right;
493     else if (align & HUD::LEFT)
494         *x -= left;
495
496     if (align & HUD::VCENTER)
497         *y -= bot + (top - bot) / 2.0;
498     else if (align & HUD::TOP)
499         *y -= top;
500     else if (align & HUD::BOTTOM)
501         *y -= bot;
502
503     *l = *x + left;
504     *r = *x + right;
505     *b = *y + bot;
506     *t = *y + top;
507 }
508
509
510
511
512 // HUDText -- text container for TextList vector
513
514
515 HUDText::HUDText(fntRenderer *fnt, float x, float y, const char *s, int align, int d) :
516     _fnt(fnt),
517     _x(x),
518     _y(y),
519     _digits(d)
520 {
521     strncpy(_msg, s, BUFSIZE);
522     if (!align || !s[0])
523         return;
524     float ign;
525     HUD::textAlign(fnt, s, align, &_x, &_y, &ign, &ign, &ign, &ign);
526 }
527
528
529 void HUDText::draw()
530 {
531     if (!_digits) { // show all digits in same size
532         _fnt->start2f(_x, _y);
533         _fnt->puts(_msg);
534         return;
535     }
536
537     // FIXME
538     // this code is changed to display Numbers with big/small digits
539     // according to MIL Standards for example Altitude above 10000 ft
540     // is shown as 10ooo.
541
542     int c = 0, i = 0;
543     char *t = _msg;
544     int p = 4;
545
546     if (t[0] == '-') {
547         //if negative value then increase the c and p values
548         //for '-' sign.
549         c++; // was moved to the comment. Unintentionally?   TODO
550         p++;
551     }
552     char *tmp = _msg;
553     while (tmp[i] != '\0') {
554         if ((tmp[i] >= '0') && (tmp[i] <= '9'))
555             c++;
556         i++;
557     }
558
559     float orig_size = _fnt->getPointSize();
560     if (c > p) {
561         _fnt->setPointSize(orig_size * 0.8);
562         int p1 = c - 3;
563         char *tmp1 = _msg + p1;
564         int p2 = p1 * 8;
565
566         _fnt->start2f(_x + p2, _y);
567         _fnt->puts(tmp1);
568
569         _fnt->setPointSize(orig_size * 1.2);
570         char tmp2[BUFSIZE];
571         strncpy(tmp2, _msg, p1);
572         tmp2[p1] = '\0';
573
574         _fnt->start2f(_x, _y);
575         _fnt->puts(tmp2);
576     } else {
577         _fnt->setPointSize(orig_size * 1.2);
578         _fnt->start2f(_x, _y);
579         _fnt->puts(tmp);
580     }
581     _fnt->setPointSize(orig_size);
582 }
583
584
585 void TextList::align(const char *s, int align, float *x, float *y,
586         float *l, float *r, float *b, float *t) const
587 {
588     HUD::textAlign(_font, s, align, x, y, l, r, b, t);
589 }
590
591
592 void TextList::draw()
593 {
594     assert(_font);
595
596     // FIXME
597     glPushAttrib(GL_COLOR_BUFFER_BIT);
598     glEnable(GL_BLEND);
599
600     _font->begin();
601     vector<HUDText>::iterator it, end = _list.end();
602     for (it = _list.begin(); it != end; ++it)
603         it->draw();
604     _font->end();
605
606     glDisable(GL_TEXTURE_2D);
607     glPopAttrib();
608 }
609
610
611 ClipBox::ClipBox(const SGPropertyNode *n, float xoffset, float yoffset) :
612     _active(false),
613     _xoffs(xoffset),
614     _yoffs(yoffset)
615 {
616     if (!n)
617         return;
618
619     // const_cast is necessary because ATM there's no matching getChild(const ...)
620     // prototype and getNode(const ..., <bool>) is wrongly interpreted as
621     // getNode(const ..., <int>)
622     _top_node = (const_cast<SGPropertyNode *>(n))->getChild("top", 0, true);
623     _bot_node = (const_cast<SGPropertyNode *>(n))->getChild("bottom", 0, true);
624     _left_node = (const_cast<SGPropertyNode *>(n))->getChild("left", 0, true);
625     _right_node = (const_cast<SGPropertyNode *>(n))->getChild("right", 0, true);
626
627     _left[0] = 1.0, _left[1] = _left[2] = 0.0;
628     _right[0] = -1.0, _right[1] = _right[2] = 0.0;
629     _top[0] = 0.0, _top[1] = -1.0, _top[2] = 0.0;
630     _bot[0] = 0.0, _bot[1] = 1.0, _bot[2] = 0.0;
631     _active = true;
632 }
633
634
635 void ClipBox::set()
636 {
637     if (!_active)
638         return;
639
640     _left[3] = -_left_node->getDoubleValue() - _xoffs;
641     _right[3] = _right_node->getDoubleValue() + _xoffs;
642     _bot[3] = -_bot_node->getDoubleValue() - _yoffs;
643     _top[3] = _top_node->getDoubleValue() + _yoffs;
644
645     glClipPlane(GL_CLIP_PLANE0, _top);
646     glEnable(GL_CLIP_PLANE0);
647     glClipPlane(GL_CLIP_PLANE1, _bot);
648     glEnable(GL_CLIP_PLANE1);
649     glClipPlane(GL_CLIP_PLANE2, _left);
650     glEnable(GL_CLIP_PLANE2);
651     glClipPlane(GL_CLIP_PLANE3, _right);
652     glEnable(GL_CLIP_PLANE3);
653 }
654
655
656 void ClipBox::unset()
657 {
658     if (_active) {
659         glDisable(GL_CLIP_PLANE0);
660         glDisable(GL_CLIP_PLANE1);
661         glDisable(GL_CLIP_PLANE2);
662         glDisable(GL_CLIP_PLANE3);
663     }
664 }