]> git.mxchange.org Git - flightgear.git/blob - src/Viewer/view.cxx
Code cleanups, code updates and fix at least on (possible) devide-by-zero
[flightgear.git] / src / Viewer / view.cxx
1 // view.cxx -- class for managing a view in the flightgear world.
2 //
3 // Written by Curtis Olson, started August 1997.
4 //                          overhaul started October 2000.
5 //   partially rewritten by Jim Wilson jim@kelcomaine.com using interface
6 //                          by David Megginson March 2002
7 //
8 // Copyright (C) 1997 - 2000  Curtis L. Olson  - http://www.flightgear.org/~curt
9 //
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
14 //
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 // General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
23 //
24 // $Id$
25
26 #ifdef HAVE_CONFIG_H
27 #  include "config.h"
28 #endif
29
30 #include "view.hxx"
31
32 #include <simgear/compiler.h>
33 #include <cassert>
34
35 #include <simgear/debug/logstream.hxx>
36 #include <simgear/constants.h>
37 #include <simgear/scene/model/placement.hxx>
38 #include <simgear/scene/util/OsgMath.hxx>
39
40 #include <Main/fg_props.hxx>
41 #include <Main/globals.hxx>
42 #include "CameraGroup.hxx"
43
44 using namespace flightgear;
45 \f
46 ////////////////////////////////////////////////////////////////////////
47 // Implementation of FGViewer.
48 ////////////////////////////////////////////////////////////////////////
49
50 // Constructor...
51 View::View( ViewType Type, bool from_model, int from_model_index,
52                     bool at_model, int at_model_index,
53                     double damp_roll, double damp_pitch, double damp_heading,
54                     double x_offset_m, double y_offset_m, double z_offset_m,
55                     double heading_offset_deg, double pitch_offset_deg,
56                     double roll_offset_deg,
57                     double fov_deg, double aspect_ratio_multiplier,
58                     double target_x_offset_m, double target_y_offset_m,
59                     double target_z_offset_m, double near_m, bool internal ):
60     _dirty(true),
61     _roll_deg(0),
62     _pitch_deg(0),
63     _heading_deg(0),
64     _target_roll_deg(0),
65     _target_pitch_deg(0),
66     _target_heading_deg(0),
67     _scaling_type(FG_SCALING_MAX)
68 {
69     _absolute_view_pos = SGVec3d(0, 0, 0);
70     _type = Type;
71     _from_model = from_model;
72     _from_model_index = from_model_index;
73     _at_model = at_model;
74     _at_model_index = at_model_index;
75
76     _internal = internal;
77
78     _dampFactor = SGVec3d::zeros();
79     _dampOutput = SGVec3d::zeros();
80     _dampTarget = SGVec3d::zeros();
81
82     if (damp_roll > 0.0)
83       _dampFactor[0] = 1.0 / pow(10.0, fabs(damp_roll));
84     if (damp_pitch > 0.0)
85       _dampFactor[1] = 1.0 / pow(10.0, fabs(damp_pitch));
86     if (damp_heading > 0.0)
87       _dampFactor[2] = 1.0 / pow(10.0, fabs(damp_heading));
88
89     _offset_m.x() = x_offset_m;
90     _offset_m.y() = y_offset_m;
91     _offset_m.z() = z_offset_m;
92     _configOffset_m = _offset_m;
93
94     _heading_offset_deg = heading_offset_deg;
95     _pitch_offset_deg = pitch_offset_deg;
96     _roll_offset_deg = roll_offset_deg;
97     _goal_heading_offset_deg = heading_offset_deg;
98     _goal_pitch_offset_deg = pitch_offset_deg;
99     _goal_roll_offset_deg = roll_offset_deg;
100
101     _configHeadingOffsetDeg = heading_offset_deg;
102     _configPitchOffsetDeg = pitch_offset_deg;
103     _configRollOffsetDeg = roll_offset_deg;
104
105     if (fov_deg > 0) {
106       _fov_deg = fov_deg;
107     } else {
108       _fov_deg = 55;
109     }
110
111     _configFOV_deg = _fov_deg;
112
113     _aspect_ratio_multiplier = aspect_ratio_multiplier;
114     _target_offset_m.x() = target_x_offset_m;
115     _target_offset_m.y() = target_y_offset_m;
116     _target_offset_m.z() = target_z_offset_m;
117     _configTargetOffset_m = _target_offset_m;
118
119     _ground_level_nearplane_m = near_m;
120     // a reasonable guess for init, so that the math doesn't blow up
121 }
122
123 View* View::createFromProperties(SGPropertyNode_ptr config)
124 {
125     double aspect_ratio_multiplier
126         = fgGetDouble("/sim/current-view/aspect-ratio-multiplier");
127
128     // find out if this is an internal view (e.g. in cockpit, low near plane)
129     // FIXME : should be a child of config
130     bool internal = config->getParent()->getBoolValue("internal", false);
131
132
133     // FIXME:
134     // this is assumed to be an aircraft model...we will need to read
135     // model-from-type as well.
136
137     // find out if this is a model we are looking from...
138     bool from_model = config->getBoolValue("from-model");
139     int from_model_index = config->getIntValue("from-model-idx");
140
141     double x_offset_m = config->getDoubleValue("x-offset-m");
142     double y_offset_m = config->getDoubleValue("y-offset-m");
143     double z_offset_m = config->getDoubleValue("z-offset-m");
144
145     double heading_offset_deg = config->getDoubleValue("heading-offset-deg");
146   //  config->setDoubleValue("heading-offset-deg", heading_offset_deg);
147     double pitch_offset_deg = config->getDoubleValue("pitch-offset-deg");
148   //  config->setDoubleValue("pitch-offset-deg", pitch_offset_deg);
149     double roll_offset_deg = config->getDoubleValue("roll-offset-deg");
150    // config->setDoubleValue("roll-offset-deg", roll_offset_deg);
151
152     double fov_deg = config->getDoubleValue("default-field-of-view-deg");
153     double near_m = config->getDoubleValue("ground-level-nearplane-m");
154
155     View* v = 0;
156     // supporting two types "lookat" = 1 and "lookfrom" = 0
157     const char *type = config->getParent()->getStringValue("type");
158     if (!strcmp(type, "lookat")) {
159         bool at_model = config->getBoolValue("at-model");
160         int at_model_index = config->getIntValue("at-model-idx");
161
162         double damp_roll = config->getDoubleValue("at-model-roll-damping");
163         double damp_pitch = config->getDoubleValue("at-model-pitch-damping");
164         double damp_heading = config->getDoubleValue("at-model-heading-damping");
165
166         double target_x_offset_m = config->getDoubleValue("target-x-offset-m");
167         double target_y_offset_m = config->getDoubleValue("target-y-offset-m");
168         double target_z_offset_m = config->getDoubleValue("target-z-offset-m");
169
170         v = new View ( FG_LOOKAT, from_model, from_model_index,
171                            at_model, at_model_index,
172                            damp_roll, damp_pitch, damp_heading,
173                            x_offset_m, y_offset_m,z_offset_m,
174                            heading_offset_deg, pitch_offset_deg,
175                            roll_offset_deg, fov_deg, aspect_ratio_multiplier,
176                            target_x_offset_m, target_y_offset_m,
177                          target_z_offset_m, near_m, internal );
178         if (!from_model) {
179             v->_targetProperties.init(config, "target-");
180         }
181     } else {
182         v = new View ( FG_LOOKFROM, from_model, from_model_index,
183                        false, 0, 0.0, 0.0, 0.0,
184                        x_offset_m, y_offset_m, z_offset_m,
185                        heading_offset_deg, pitch_offset_deg,
186                        roll_offset_deg, fov_deg, aspect_ratio_multiplier,
187                          0, 0, 0, near_m, internal );
188     }
189
190     if (!from_model) {
191         v->_eyeProperties.init(config, "eye-");
192     }
193
194     v->_name = config->getParent()->getStringValue("name");
195     v->_typeString = type;
196     v->_configHeadingOffsetDeg = config->getDoubleValue("default-heading-offset-deg");
197
198     return v;
199 }
200
201
202 // Destructor
203 View::~View( void )
204 {
205     _tiedProperties.Untie();
206 }
207
208 void
209 View::init ()
210 {
211 }
212
213 void
214 View::bind ()
215 {
216     _tiedProperties.setRoot(fgGetNode("/sim/current-view", true));
217     _tiedProperties.Tie("heading-offset-deg", this,
218                          &View::getHeadingOffset_deg,
219                          &View::setHeadingOffset_deg_property,
220                         false /* do not set current property value */);
221
222      fgSetArchivable("/sim/current-view/heading-offset-deg");
223
224     _tiedProperties.Tie("goal-heading-offset-deg", this,
225                         &View::getGoalHeadingOffset_deg,
226                         &View::setGoalHeadingOffset_deg,
227                         false /* do not set current property value */);
228
229     fgSetArchivable("/sim/current-view/goal-heading-offset-deg");
230
231     _tiedProperties.Tie("pitch-offset-deg", this,
232                         &View::getPitchOffset_deg,
233                         &View::setPitchOffset_deg_property,
234                         false /* do not set current property value */);
235     fgSetArchivable("/sim/current-view/pitch-offset-deg");
236     _tiedProperties.Tie("goal-pitch-offset-deg", this,
237                         &View::getGoalPitchOffset_deg,
238                         &View::setGoalPitchOffset_deg,
239                         false /* do not set current property value */);
240     fgSetArchivable("/sim/current-view/goal-pitch-offset-deg");
241     _tiedProperties.Tie("roll-offset-deg", this,
242                         &View::getRollOffset_deg,
243                         &View::setRollOffset_deg_property,
244                         false /* do not set current property value */);
245     fgSetArchivable("/sim/current-view/roll-offset-deg");
246     _tiedProperties.Tie("goal-roll-offset-deg", this,
247                         &View::getGoalRollOffset_deg,
248                         &View::setGoalRollOffset_deg,
249                         false /* do not set current property value */);
250     fgSetArchivable("/sim/current-view/goal-roll-offset-deg");
251
252
253     _tiedProperties.Tie("field-of-view", this,
254                         &View::get_fov, &View::set_fov,
255                         false);
256     fgSetArchivable("/sim/current-view/field-of-view");
257
258
259     _tiedProperties.Tie("aspect-ratio-multiplier", this,
260                         &View::get_aspect_ratio_multiplier,
261                         &View::set_aspect_ratio_multiplier,
262                         false);
263
264     _tiedProperties.Tie("ground-level-nearplane-m", this,
265                         &View::getNear_m, &View::setNear_m, false);
266     fgSetArchivable("/sim/current-view/ground-level-nearplane-m");
267
268
269     _tiedProperties.Tie("viewer-lon-deg", this, &View::getLon_deg);
270     _tiedProperties.Tie("viewer-lat-deg", this, &View::getLat_deg);
271     _tiedProperties.Tie("viewer-elev-ft", this, &View::getElev_ft);
272
273     _tiedProperties.Tie("x-offset-m", this, &View::getXOffset_m,
274                         &View::setXOffset_m, false);
275     _tiedProperties.Tie("y-offset-m", this, &View::getYOffset_m,
276                         &View::setYOffset_m, false);
277     _tiedProperties.Tie("z-offset-m", this, &View::getZOffset_m,
278                         &View::setZOffset_m, false);
279
280     _tiedProperties.Tie("target-x-offset-m", this, &View::getTargetXOffset_m,
281                         &View::setTargetXOffset_m, false);
282     _tiedProperties.Tie("target-y-offset-m", this, &View::getTargetYOffset_m,
283                         &View::setTargetYOffset_m, false);
284     _tiedProperties.Tie("target-z-offset-m", this, &View::getTargetZOffset_m,
285                         &View::setTargetZOffset_m, false);
286
287 // expose various quaternions under the debug/ subtree
288     _tiedProperties.Tie("debug/orientation-w", this, &View::getOrientation_w);
289     _tiedProperties.Tie("debug/orientation-x", this, &View::getOrientation_x);
290     _tiedProperties.Tie("debug/orientation-y", this, &View::getOrientation_y);
291     _tiedProperties.Tie("debug/orientation-z", this, &View::getOrientation_z);
292
293     _tiedProperties.Tie("debug/orientation_offset-w", this,
294                         &View::getOrOffset_w);
295     _tiedProperties.Tie("debug/orientation_offset-x", this,
296                         &View::getOrOffset_x);
297     _tiedProperties.Tie("debug/orientation_offset-y", this,
298                         &View::getOrOffset_y);
299     _tiedProperties.Tie("debug/orientation_offset-z", this,
300                         &View::getOrOffset_z);
301
302     _tiedProperties.Tie("debug/frame-w", this, &View::getFrame_w);
303     _tiedProperties.Tie("debug/frame-x", this, &View::getFrame_x);
304     _tiedProperties.Tie("debug/frame-y", this, &View::getFrame_y);
305     _tiedProperties.Tie("debug/frame-z", this, &View::getFrame_z);
306
307
308 // expose the raw (OpenGL) orientation to the property tree,
309 // for the sound-manager
310     _tiedProperties.Tie("raw-orientation", 0, this, &View::getRawOrientation_w);
311     _tiedProperties.Tie("raw-orientation", 1, this, &View::getRawOrientation_x);
312     _tiedProperties.Tie("raw-orientation", 2, this, &View::getRawOrientation_y);
313     _tiedProperties.Tie("raw-orientation", 3, this, &View::getRawOrientation_z);
314
315     _tiedProperties.Tie("viewer-x-m", this, &View::getAbsolutePosition_x);
316     _tiedProperties.Tie("viewer-y-m", this, &View::getAbsolutePosition_y);
317     _tiedProperties.Tie("viewer-z-m", this, &View::getAbsolutePosition_z);
318
319 // following config properties are exposed on current-view but don't change,
320 // so we can simply copy them here.
321     _tiedProperties.getRoot()->setStringValue("name", _name);
322     _tiedProperties.getRoot()->setStringValue("type", _typeString);
323     _tiedProperties.getRoot()->setBoolValue("internal", _internal);
324
325     SGPropertyNode_ptr config = _tiedProperties.getRoot()->getChild("config", 0, true);
326     config->setBoolValue("from-model", _from_model);
327     config->setDoubleValue("heading-offset-deg", _configHeadingOffsetDeg);
328     config->setDoubleValue("pitch-offset-deg", _configPitchOffsetDeg);
329     config->setDoubleValue("roll-offset-deg", _configRollOffsetDeg);
330     config->setDoubleValue("default-field-of-view-deg", _configFOV_deg);
331 }
332
333 void
334 View::unbind ()
335 {
336     _tiedProperties.Untie();
337 }
338
339 void View::resetOffsetsAndFOV()
340 {
341     _target_offset_m = _configTargetOffset_m;
342     _offset_m = _configOffset_m;
343     _pitch_offset_deg = _configPitchOffsetDeg;
344     _heading_offset_deg = _configHeadingOffsetDeg;
345     _roll_offset_deg = _configRollOffsetDeg;
346     _fov_deg = _configFOV_deg;
347 }
348
349 void
350 View::setType ( int type )
351 {
352   if (type == 0)
353     _type = FG_LOOKFROM;
354   if (type == 1)
355     _type = FG_LOOKAT;
356 }
357
358 void
359 View::setInternal ( bool internal )
360 {
361   _internal = internal;
362 }
363
364 void
365 View::setPosition (const SGGeod& geod)
366 {
367   _dirty = true;
368     _position = geod;
369 }
370
371 void
372 View::setTargetPosition (const SGGeod& geod)
373 {
374   _dirty = true;
375     _target = geod;
376 }
377
378 void
379 View::setRoll_deg (double roll_deg)
380 {
381   _dirty = true;
382   _roll_deg = roll_deg;
383 }
384
385 void
386 View::setPitch_deg (double pitch_deg)
387 {
388   _dirty = true;
389   _pitch_deg = pitch_deg;
390 }
391
392 void
393 View::setHeading_deg (double heading_deg)
394 {
395   _dirty = true;
396   _heading_deg = heading_deg;
397 }
398
399 void
400 View::setOrientation (double roll_deg, double pitch_deg, double heading_deg)
401 {
402   _dirty = true;
403   _roll_deg = roll_deg;
404   _pitch_deg = pitch_deg;
405   _heading_deg = heading_deg;
406 }
407
408 void
409 View::setTargetRoll_deg (double target_roll_deg)
410 {
411   _dirty = true;
412   _target_roll_deg = target_roll_deg;
413 }
414
415 void
416 View::setTargetPitch_deg (double target_pitch_deg)
417 {
418   _dirty = true;
419   _target_pitch_deg = target_pitch_deg;
420 }
421
422 void
423 View::setTargetHeading_deg (double target_heading_deg)
424 {
425   _dirty = true;
426   _target_heading_deg = target_heading_deg;
427 }
428
429 void
430 View::setTargetOrientation (double target_roll_deg, double target_pitch_deg, double target_heading_deg)
431 {
432   _dirty = true;
433   _target_roll_deg = target_roll_deg;
434   _target_pitch_deg = target_pitch_deg;
435   _target_heading_deg = target_heading_deg;
436 }
437
438 void
439 View::setXOffset_m (double x_offset_m)
440 {
441   _dirty = true;
442   _offset_m.x() = x_offset_m;
443 }
444
445 void
446 View::setYOffset_m (double y_offset_m)
447 {
448   _dirty = true;
449   _offset_m.y() = y_offset_m;
450 }
451
452 void
453 View::setZOffset_m (double z_offset_m)
454 {
455   _dirty = true;
456   _offset_m.z() = z_offset_m;
457 }
458
459 void
460 View::setTargetXOffset_m (double target_x_offset_m)
461 {
462   _dirty = true;
463   _target_offset_m.x() = target_x_offset_m;
464 }
465
466 void
467 View::setTargetYOffset_m (double target_y_offset_m)
468 {
469   _dirty = true;
470   _target_offset_m.y() = target_y_offset_m;
471 }
472
473 void
474 View::setTargetZOffset_m (double target_z_offset_m)
475 {
476   _dirty = true;
477   _target_offset_m.z() = target_z_offset_m;
478 }
479
480 void
481 View::setPositionOffsets (double x_offset_m, double y_offset_m, double z_offset_m)
482 {
483   _dirty = true;
484   _offset_m.x() = x_offset_m;
485   _offset_m.y() = y_offset_m;
486   _offset_m.z() = z_offset_m;
487 }
488
489 void
490 View::setRollOffset_deg (double roll_offset_deg)
491 {
492   _dirty = true;
493   _roll_offset_deg = roll_offset_deg;
494 }
495
496 void
497 View::setPitchOffset_deg (double pitch_offset_deg)
498 {
499   _dirty = true;
500   _pitch_offset_deg = pitch_offset_deg;
501 }
502
503 void
504 View::setHeadingOffset_deg (double heading_offset_deg)
505 {
506   _dirty = true;
507   if (_at_model && (_offset_m.x() == 0.0)&&(_offset_m.z() == 0.0))
508   {
509       /* avoid optical effects (e.g. rotating sky) when "looking at" with
510        * heading offsets x==z==0 (view heading cannot change). */
511       _heading_offset_deg = 0.0;
512   }
513   else
514       _heading_offset_deg = heading_offset_deg;
515 }
516
517 void
518 View::setHeadingOffset_deg_property (double heading_offset_deg)
519 {
520     setHeadingOffset_deg(heading_offset_deg);
521     setGoalHeadingOffset_deg(heading_offset_deg);
522 }
523
524 void
525 View::setPitchOffset_deg_property (double pitch_offset_deg)
526 {
527     setPitchOffset_deg(pitch_offset_deg);
528     setGoalPitchOffset_deg(pitch_offset_deg);
529 }
530
531 void
532 View::setRollOffset_deg_property (double roll_offset_deg)
533 {
534     setRollOffset_deg(roll_offset_deg);
535     setGoalRollOffset_deg(roll_offset_deg);
536 }
537
538 void
539 View::setGoalRollOffset_deg (double goal_roll_offset_deg)
540 {
541   _dirty = true;
542   _goal_roll_offset_deg = goal_roll_offset_deg;
543 }
544
545 void
546 View::setGoalPitchOffset_deg (double goal_pitch_offset_deg)
547 {
548   _dirty = true;
549   _goal_pitch_offset_deg = goal_pitch_offset_deg;
550   /* The angle is set to 1/1000th of a degree from the poles to avoid the
551    * singularity where the azimuthal angle becomes undefined, inducing optical
552    * artefacts.  The arbitrary angle offset is visually unnoticeable while
553    * avoiding any possible floating point truncation artefacts. */
554   if ( _goal_pitch_offset_deg < -89.999 ) {
555     _goal_pitch_offset_deg = -89.999;
556   }
557   if ( _goal_pitch_offset_deg > 89.999 ) {
558     _goal_pitch_offset_deg = 89.999;
559   }
560
561 }
562
563 void
564 View::setGoalHeadingOffset_deg (double goal_heading_offset_deg)
565 {
566   _dirty = true;
567   if (_at_model && (_offset_m.x() == 0.0)&&(_offset_m.z() == 0.0))
568   {
569       /* avoid optical effects (e.g. rotating sky) when "looking at" with
570        * heading offsets x==z==0 (view heading cannot change). */
571       _goal_heading_offset_deg = 0.0;
572       return;
573   }
574
575   _goal_heading_offset_deg = goal_heading_offset_deg;
576   while ( _goal_heading_offset_deg < 0.0 ) {
577     _goal_heading_offset_deg += 360;
578   }
579   while ( _goal_heading_offset_deg > 360 ) {
580     _goal_heading_offset_deg -= 360;
581   }
582 }
583
584 void
585 View::setOrientationOffsets (double roll_offset_deg, double pitch_offset_deg, double heading_offset_deg)
586 {
587   _dirty = true;
588   _roll_offset_deg = roll_offset_deg;
589   _pitch_offset_deg = pitch_offset_deg;
590   _heading_offset_deg = heading_offset_deg;
591 }
592
593 // recalc() is done every time one of the setters is called (making the
594 // cached data "dirty") on the next "get".  It calculates all the outputs
595 // for viewer.
596 void
597 View::recalc ()
598 {
599   if (_type == FG_LOOKFROM) {
600     recalcLookFrom();
601   } else {
602     recalcLookAt();
603   }
604
605   set_clean();
606 }
607
608 // recalculate for LookFrom view type...
609 void
610 View::recalcLookFrom ()
611 {
612   // Update location data ...
613   if ( _from_model ) {
614     _position = globals->get_aircraft_position();
615     globals->get_aircraft_orientation(_heading_deg, _pitch_deg, _roll_deg);
616   }
617
618   double head = _heading_deg;
619   double pitch = _pitch_deg;
620   double roll = _roll_deg;
621   if ( !_from_model ) {
622     // update from our own data...
623     setDampTarget(roll, pitch, head);
624     getDampOutput(roll, pitch, head);
625   }
626
627   // The rotation rotating from the earth centerd frame to
628   // the horizontal local frame
629   SGQuatd hlOr = SGQuatd::fromLonLat(_position);
630
631   // The rotation from the horizontal local frame to the basic view orientation
632   SGQuatd hlToBody = SGQuatd::fromYawPitchRollDeg(head, pitch, roll);
633
634   // The rotation offset, don't know why heading is negative here ...
635   mViewOffsetOr
636       = SGQuatd::fromYawPitchRollDeg(-_heading_offset_deg, _pitch_offset_deg,
637                                      _roll_offset_deg);
638
639   // Compute the eyepoints orientation and position
640   // wrt the earth centered frame - that is global coorinates
641   SGQuatd ec2body = hlOr*hlToBody;
642
643   // The cartesian position of the basic view coordinate
644   SGVec3d position = SGVec3d::fromGeod(_position);
645
646   // This is rotates the x-forward, y-right, z-down coordinate system the where
647   // simulation runs into the OpenGL camera system with x-right, y-up, z-back.
648   SGQuatd q(-0.5, -0.5, 0.5, 0.5);
649
650   _absolute_view_pos = position + (ec2body*q).backTransform(_offset_m);
651   mViewOrientation = ec2body*mViewOffsetOr*q;
652 }
653
654 void
655 View::recalcLookAt ()
656 {
657   // The geodetic position of our target to look at
658   if ( _at_model ) {
659     _target = globals->get_aircraft_position();
660     globals->get_aircraft_orientation(_target_heading_deg,
661                                       _target_pitch_deg,
662                                       _target_roll_deg);
663   } else {
664     // if not model then calculate our own target position...
665     setDampTarget(_target_roll_deg, _target_pitch_deg, _target_heading_deg);
666     getDampOutput(_target_roll_deg, _target_pitch_deg, _target_heading_deg);
667   }
668
669   SGQuatd geodTargetOr = SGQuatd::fromYawPitchRollDeg(_target_heading_deg,
670                                                    _target_pitch_deg,
671                                                    _target_roll_deg);
672   SGQuatd geodTargetHlOr = SGQuatd::fromLonLat(_target);
673
674
675   if ( _from_model ) {
676     _position = globals->get_aircraft_position();
677     globals->get_aircraft_orientation(_heading_deg, _pitch_deg, _roll_deg);
678   } else {
679     // update from our own data, just the rotation here...
680     setDampTarget(_roll_deg, _pitch_deg, _heading_deg);
681     getDampOutput(_roll_deg, _pitch_deg, _heading_deg);
682   }
683   SGQuatd geodEyeOr = SGQuatd::fromYawPitchRollDeg(_heading_deg, _pitch_deg, _roll_deg);
684   SGQuatd geodEyeHlOr = SGQuatd::fromLonLat(_position);
685
686   // the rotation offset, don't know why heading is negative here ...
687   mViewOffsetOr =
688     SGQuatd::fromYawPitchRollDeg(-_heading_offset_deg + 180, _pitch_offset_deg,
689                                  _roll_offset_deg);
690
691   // Offsets to the eye position
692   SGVec3d eyeOff(-_offset_m.z(), _offset_m.x(), -_offset_m.y());
693   SGQuatd ec2eye = geodEyeHlOr*geodEyeOr;
694   SGVec3d eyeCart = SGVec3d::fromGeod(_position);
695   eyeCart += (ec2eye*mViewOffsetOr).backTransform(eyeOff);
696
697   SGVec3d atCart = SGVec3d::fromGeod(_target);
698
699   // add target offsets to at_position...
700   SGVec3d target_pos_off(-_target_offset_m.z(), _target_offset_m.x(),
701                          -_target_offset_m.y());
702   target_pos_off = (geodTargetHlOr*geodTargetOr).backTransform(target_pos_off);
703   atCart += target_pos_off;
704   eyeCart += target_pos_off;
705
706   // Compute the eyepoints orientation and position
707   // wrt the earth centered frame - that is global coorinates
708   _absolute_view_pos = eyeCart;
709
710   // the view direction
711   SGVec3d dir = normalize(atCart - eyeCart);
712   // the up directon
713   SGVec3d up = ec2eye.backTransform(SGVec3d(0, 0, -1));
714   // rotate -dir to the 2-th unit vector
715   // rotate up to 1-th unit vector
716   // Note that this matches the OpenGL camera coordinate system
717   // with x-right, y-up, z-back.
718   mViewOrientation = SGQuatd::fromRotateTo(-dir, 2, up, 1);
719 }
720
721 void
722 View::setDampTarget(double roll, double pitch, double heading)
723 {
724   _dampTarget = SGVec3d(roll, pitch, heading);
725 }
726
727 void
728 View::getDampOutput(double& roll, double& pitch, double& heading)
729 {
730   roll = _dampOutput[0];
731   pitch = _dampOutput[1];
732   heading = _dampOutput[2];
733 }
734
735
736 void
737 View::updateDampOutput(double dt)
738 {
739   static View *last_view = 0;
740   if ((last_view != this) || (dt > 1.0)) {
741     _dampOutput = _dampTarget;
742     last_view = this;
743     return;
744   }
745
746   const double interval = 0.01;
747   while (dt > interval) {
748
749     for (unsigned int i=0; i<3; ++i) {
750       if (_dampFactor[i] <= 0.0) {
751         // axis is un-damped, set output to target directly
752         _dampOutput[i] = _dampTarget[i];
753         continue;
754       }
755
756       double d = _dampOutput[i] - _dampTarget[i];
757       if (d > 180.0) {
758         _dampOutput[i] -= 360.0;
759       } else if (d < -180.0) {
760         _dampOutput[i] += 360.0;
761       }
762
763       _dampOutput[i] = (_dampTarget[i] * _dampFactor[i]) +
764         (_dampOutput[i] * (1.0 - _dampFactor[i]));
765     } // of axis iteration
766
767     dt -= interval;
768   } // of dt subdivision by interval
769 }
770
771 double
772 View::get_h_fov()
773 {
774     double aspectRatio = get_aspect_ratio();
775     switch (_scaling_type) {
776     case FG_SCALING_WIDTH:  // h_fov == fov
777         return _fov_deg;
778     case FG_SCALING_MAX:
779         if (aspectRatio < 1.0) {
780             // h_fov == fov
781             return _fov_deg;
782         } else {
783             // v_fov == fov
784             return
785                 atan(tan(_fov_deg/2 * SG_DEGREES_TO_RADIANS)
786                      / (aspectRatio*_aspect_ratio_multiplier))
787                 * SG_RADIANS_TO_DEGREES * 2;
788         }
789     default:
790         assert(false);
791     }
792     return 0.0;
793 }
794
795
796
797 double
798 View::get_v_fov()
799 {
800     double aspectRatio = get_aspect_ratio();
801     switch (_scaling_type) {
802     case FG_SCALING_WIDTH:  // h_fov == fov
803         return
804             atan(tan(_fov_deg/2 * SG_DEGREES_TO_RADIANS)
805                  * (aspectRatio*_aspect_ratio_multiplier))
806             * SG_RADIANS_TO_DEGREES * 2;
807     case FG_SCALING_MAX:
808         if (aspectRatio < 1.0) {
809             // h_fov == fov
810             return
811                 atan(tan(_fov_deg/2 * SG_DEGREES_TO_RADIANS)
812                      * (aspectRatio*_aspect_ratio_multiplier))
813                 * SG_RADIANS_TO_DEGREES * 2;
814         } else {
815             // v_fov == fov
816             return _fov_deg;
817         }
818     default:
819         assert(false);
820     }
821     return 0.0;
822 }
823
824 void
825 View::updateData()
826 {
827     if (!_from_model) {
828         SGGeod pos = _eyeProperties.position();
829         SGVec3d att = _eyeProperties.attitude();
830         setPosition(pos);
831         setOrientation(att[2], att[1], att[0]);
832     } else {
833         set_dirty();
834     }
835
836     // if lookat (type 1) then get target data...
837     if (getType() == FG_LOOKAT) {
838         if (!_from_model) {
839             SGGeod pos = _targetProperties.position();
840             SGVec3d att = _targetProperties.attitude();
841             setTargetPosition(pos);
842             setTargetOrientation(att[2], att[1], att[0]);
843         } else {
844             set_dirty();
845         }
846     }
847 }
848
849 void
850 View::update (double dt)
851 {
852     updateData();
853     recalc();
854   updateDampOutput(dt);
855
856   int i;
857   int dt_ms = int(dt * 1000);
858   for ( i = 0; i < dt_ms; i++ ) {
859     if ( fabs( _goal_heading_offset_deg - _heading_offset_deg) < 1 ) {
860       setHeadingOffset_deg( _goal_heading_offset_deg );
861       break;
862     } else {
863       // move current_view.headingoffset towards
864       // current_view.goal_view_offset
865       if ( _goal_heading_offset_deg > _heading_offset_deg )
866         {
867           if ( _goal_heading_offset_deg - _heading_offset_deg < 180 ){
868             incHeadingOffset_deg( 0.5 );
869           } else {
870             incHeadingOffset_deg( -0.5 );
871           }
872         } else {
873           if ( _heading_offset_deg - _goal_heading_offset_deg < 180 ){
874             incHeadingOffset_deg( -0.5 );
875           } else {
876             incHeadingOffset_deg( 0.5 );
877           }
878         }
879       if ( _heading_offset_deg > 360 ) {
880         incHeadingOffset_deg( -360 );
881       } else if ( _heading_offset_deg < 0 ) {
882         incHeadingOffset_deg( 360 );
883       }
884     }
885   }
886
887   for ( i = 0; i < dt_ms; i++ ) {
888     if ( fabs( _goal_pitch_offset_deg - _pitch_offset_deg ) < 1 ) {
889       setPitchOffset_deg( _goal_pitch_offset_deg );
890       break;
891     } else {
892       // move current_view.pitch_offset_deg towards
893       // current_view.goal_pitch_offset
894       if ( _goal_pitch_offset_deg > _pitch_offset_deg )
895         {
896           incPitchOffset_deg( 1.0 );
897         } else {
898             incPitchOffset_deg( -1.0 );
899         }
900       if ( _pitch_offset_deg > 90 ) {
901         setPitchOffset_deg(90);
902       } else if ( _pitch_offset_deg < -90 ) {
903         setPitchOffset_deg( -90 );
904       }
905     }
906   }
907
908
909   for ( i = 0; i < dt_ms; i++ ) {
910     if ( fabs( _goal_roll_offset_deg - _roll_offset_deg ) < 1 ) {
911       setRollOffset_deg( _goal_roll_offset_deg );
912       break;
913     } else {
914       // move current_view.roll_offset_deg towards
915       // current_view.goal_roll_offset
916       if ( _goal_roll_offset_deg > _roll_offset_deg )
917         {
918           incRollOffset_deg( 1.0 );
919         } else {
920             incRollOffset_deg( -1.0 );
921         }
922       if ( _roll_offset_deg > 90 ) {
923         setRollOffset_deg(90);
924       } else if ( _roll_offset_deg < -90 ) {
925         setRollOffset_deg( -90 );
926       }
927     }
928   }
929   recalc();
930 }
931
932 double View::getAbsolutePosition_x() const
933 {
934     return _absolute_view_pos.x();
935 }
936
937 double View::getAbsolutePosition_y() const
938 {
939     return _absolute_view_pos.y();
940 }
941
942 double View::getAbsolutePosition_z() const
943 {
944     return _absolute_view_pos.z();
945 }
946
947 double View::getRawOrientation_w() const
948 {
949     return mViewOrientation.w();
950 }
951
952 double View::getRawOrientation_x() const
953 {
954     return mViewOrientation.x();
955 }
956
957 double View::getRawOrientation_y() const
958 {
959     return mViewOrientation.y();
960 }
961
962 double View::getRawOrientation_z() const
963 {
964     return mViewOrientation.z();
965 }
966
967 // This takes the conventional aviation XYZ body system
968 // i.e.  x=forward, y=starboard, z=bottom
969 // which is widely used in FGFS
970 // and rotates it into the OpenGL camera system
971 // i.e. Xprime=starboard, Yprime=top, Zprime=aft.
972 static const SGQuatd fsb2sta()
973 {
974     return SGQuatd(-0.5, -0.5, 0.5, 0.5);
975 }
976
977 // reference frame orientation.
978 // This is the view orientation you get when you have no
979 // view offset, i.e. the offset operator is the identity.
980 //
981 // For example, in the familiar "cockpit lookfrom" view,
982 // the reference frame is equal to the aircraft attitude,
983 // i.e. it is the view looking towards 12:00 straight ahead.
984 //
985 // FIXME:  Somebody needs to figure out what is the reference
986 // frame view for the other view modes.
987 //
988 // Conceptually, this quat represents a rotation relative
989 // to the ECEF reference orientation, as described at
990 //    http://www.av8n.com/physics/coords.htm#sec-orientation
991 //
992 // See the NOTE concerning reference orientations, below.
993 //
994 // The components of this quat are expressed in
995 // the conventional aviation basis set,
996 // i.e.  x=forward, y=starboard, z=bottom
997 double View::getFrame_w() const
998 {
999     return ((mViewOrientation*conj(fsb2sta())*conj(mViewOffsetOr))).w();
1000 }
1001
1002 double View::getFrame_x() const
1003 {
1004     return ((mViewOrientation*conj(fsb2sta())*conj(mViewOffsetOr))).x();
1005 }
1006
1007 double View::getFrame_y() const
1008 {
1009     return ((mViewOrientation*conj(fsb2sta())*conj(mViewOffsetOr))).y();
1010 }
1011
1012 double View::getFrame_z() const
1013 {
1014     return ((mViewOrientation*conj(fsb2sta())*conj(mViewOffsetOr))).z();
1015 }
1016
1017
1018 // view offset.
1019 // This rotation takes you from the aforementioned
1020 // reference frame view orientation to whatever
1021 // actual current view orientation is.
1022 //
1023 // The components of this quaternion are expressed in
1024 // the conventional aviation basis set,
1025 // i.e.  x=forward, y=starboard, z=bottom
1026 double View::getOrOffset_w() const{
1027     return mViewOffsetOr.w();
1028 }
1029 double View::getOrOffset_x() const{
1030     return mViewOffsetOr.x();
1031 }
1032 double View::getOrOffset_y() const{
1033     return mViewOffsetOr.y();
1034 }
1035 double View::getOrOffset_z() const{
1036     return mViewOffsetOr.z();
1037 }
1038
1039
1040 // current view orientation.
1041 // This is a rotation relative to the earth-centered (ec)
1042 // reference frame.
1043 //
1044 // NOTE: Here we remove a factor of fsb2sta so that
1045 // the components of this quat are displayed using the
1046 // conventional ECEF basis set.  This is *not* the way
1047 // the view orientation is stored in the views[] array,
1048 // but is easier for non-graphics hackers to understand.
1049 // If we did not remove this factor of fsb2sta here and
1050 // in getCurrentViewFrame, that would be equivalent to
1051 // the following peculiar reference orientation:
1052 // Suppose you are over the Gulf of Guinea, at (lat,lon) = (0,0).
1053 // Then the reference frame orientation can be achieved via:
1054 //    -- The aircraft X-axis (nose) headed south.
1055 //    -- The aircraft Y-axis (starboard wingtip) pointing up.
1056 //    -- The aircraft Z-axis (belly) pointing west.
1057 // To say the same thing in other words, and perhaps more to the
1058 // point:  If we use the OpenGL camera orientation conventions,
1059 // i.e. Xprime=starboard, Yprime=top, Zprime=aft, then the
1060 // aforementioned peculiar reference orientation at (lat,lon)
1061 //  = (0,0) can be described as:
1062 //    -- aircraft Xprime axis (starboard) pointed up
1063 //    -- aircraft Yprime axis (top) pointed east
1064 //    -- aircraft Zprime axis (aft) pointed north
1065 // meaning the OpenGL axes are aligned with the ECEF axes.
1066 double View::getOrientation_w() const{
1067     return (mViewOrientation * conj(fsb2sta())).w();
1068 }
1069 double View::getOrientation_x() const{
1070     return (mViewOrientation * conj(fsb2sta())).x();
1071 }
1072 double View::getOrientation_y() const{
1073     return (mViewOrientation * conj(fsb2sta())).y();
1074 }
1075 double View::getOrientation_z() const{
1076     return (mViewOrientation * conj(fsb2sta())).z();
1077 }
1078
1079 double View::get_aspect_ratio() const
1080 {
1081     return flightgear::CameraGroup::getDefault()->getMasterAspectRatio();
1082 }
1083
1084 double View::getLon_deg() const
1085 {
1086     return _position.getLongitudeDeg();
1087 }
1088
1089 double View::getLat_deg() const
1090 {
1091     return _position.getLatitudeDeg();
1092 }
1093
1094 double View::getElev_ft() const
1095 {
1096     return _position.getElevationFt();
1097 }
1098
1099 View::PositionAttitudeProperties::PositionAttitudeProperties()
1100 {
1101 }
1102
1103 View::PositionAttitudeProperties::~PositionAttitudeProperties()
1104 {
1105 }
1106
1107 void View::PositionAttitudeProperties::init(SGPropertyNode_ptr parent, const std::string& prefix)
1108 {
1109     _lonPathProp = parent->getNode(prefix + "lon-deg-path", true);
1110     _latPathProp = parent->getNode(prefix + "lat-deg-path", true);
1111     _altPathProp = parent->getNode(prefix + "alt-ft-path", true);
1112     _headingPathProp = parent->getNode(prefix + "heading-deg-path", true);
1113     _pitchPathProp = parent->getNode(prefix + "pitch-deg-path", true);
1114     _rollPathProp = parent->getNode(prefix + "roll-deg-path", true);
1115
1116     // update the real properties now
1117     valueChanged(NULL);
1118
1119     _lonPathProp->addChangeListener(this);
1120     _latPathProp->addChangeListener(this);
1121     _altPathProp->addChangeListener(this);
1122     _headingPathProp->addChangeListener(this);
1123     _pitchPathProp->addChangeListener(this);
1124     _rollPathProp->addChangeListener(this);
1125 }
1126
1127 void View::PositionAttitudeProperties::valueChanged(SGPropertyNode* node)
1128 {
1129     _lonProp = resolvePathProperty(_lonPathProp);
1130     _latProp = resolvePathProperty(_latPathProp);
1131     _altProp = resolvePathProperty(_altPathProp);
1132     _headingProp = resolvePathProperty(_headingPathProp);
1133     _pitchProp = resolvePathProperty(_pitchPathProp);
1134     _rollProp = resolvePathProperty(_rollPathProp);
1135 }
1136
1137 SGPropertyNode_ptr View::PositionAttitudeProperties::resolvePathProperty(SGPropertyNode_ptr p)
1138 {
1139     if (!p)
1140         return SGPropertyNode_ptr();
1141
1142     std::string path = p->getStringValue();
1143     if (path.empty())
1144         return SGPropertyNode_ptr();
1145
1146     return fgGetNode(path, true);
1147 }
1148
1149 SGGeod View::PositionAttitudeProperties::position() const
1150 {
1151     double lon = _lonProp ? _lonProp->getDoubleValue() : 0.0;
1152     double lat = _latProp ? _latProp->getDoubleValue() : 0.0;
1153     double alt = _altProp ? _altProp->getDoubleValue() : 0.0;
1154     return SGGeod::fromDegFt(lon, lat, alt);
1155 }
1156
1157 SGVec3d View::PositionAttitudeProperties::attitude() const
1158 {
1159     double heading = _headingProp ? _headingProp->getDoubleValue() : 0.0;
1160     double pitch = _pitchProp ? _pitchProp->getDoubleValue() : 0.0;
1161     double roll = _rollProp ? _rollProp->getDoubleValue() : 0.0;
1162     return SGVec3d(heading, pitch, roll);
1163 }