]> git.mxchange.org Git - flightgear.git/blob - src/Model/model.cxx
Streamline to create fewer branch nodes. This involves moving some
[flightgear.git] / src / Model / model.cxx
1 // model.cxx - manage a 3D aircraft model.
2 // Written by David Megginson, started 2002.
3 //
4 // This file is in the Public Domain, and comes with no warranty.
5
6 #ifdef HAVE_CONFIG_H
7 #  include <config.h>
8 #endif
9
10 #include <string.h>             // for strcmp()
11
12 #include <plib/sg.h>
13 #include <plib/ssg.h>
14
15 #include <simgear/compiler.h>
16 #include <simgear/debug/logstream.hxx>
17 #include <simgear/math/interpolater.hxx>
18 #include <simgear/math/point3d.hxx>
19 #include <simgear/math/sg_geodesy.hxx>
20 #include <simgear/misc/exception.hxx>
21 #include <simgear/misc/sg_path.hxx>
22
23 #include <Main/fg_props.hxx>
24 #include <Main/globals.hxx>
25 #include <Main/location.hxx>
26 #include <Scenery/scenery.hxx>
27
28 #include "model.hxx"
29 #include "panelnode.hxx"
30
31
32 \f
33 ////////////////////////////////////////////////////////////////////////
34 // Static utility functions.
35 ////////////////////////////////////////////////////////////////////////
36
37 /**
38  * Callback to update an animation.
39  */
40 static int
41 animation_callback (ssgEntity * entity, int mask)
42 {
43     ((Animation *)entity->getUserData())->update();
44     return true;
45 }
46
47
48 /**
49  * Locate a named SSG node in a branch.
50  */
51 static ssgEntity *
52 find_named_node (ssgEntity * node, const char * name)
53 {
54   char * node_name = node->getName();
55   if (node_name != 0 && !strcmp(name, node_name))
56     return node;
57   else if (node->isAKindOf(ssgTypeBranch())) {
58     int nKids = node->getNumKids();
59     for (int i = 0; i < nKids; i++) {
60       ssgEntity * result =
61         find_named_node(((ssgBranch*)node)->getKid(i), name);
62       if (result != 0)
63         return result;
64     }
65   } 
66   return 0;
67 }
68
69 /**
70  * Splice a branch in between all child nodes and their parents.
71  */
72 static void
73 splice_branch (ssgBranch * branch, ssgEntity * child)
74 {
75   int nParents = child->getNumParents();
76   branch->addKid(child);
77   for (int i = 0; i < nParents; i++) {
78     ssgBranch * parent = child->getParent(i);
79     parent->replaceKid(child, branch);
80   }
81 }
82
83 /**
84  * Set up the transform matrix for a spin or rotation.
85  */
86 static void
87 set_rotation (sgMat4 &matrix, double position_deg,
88               sgVec3 &center, sgVec3 &axis)
89 {
90  float temp_angle = -position_deg * SG_DEGREES_TO_RADIANS ;
91  
92  float s = (float) sin ( temp_angle ) ;
93  float c = (float) cos ( temp_angle ) ;
94  float t = SG_ONE - c ;
95
96  // axis was normalized at load time 
97  // hint to the compiler to put these into FP registers
98  float x = axis[0];
99  float y = axis[1];
100  float z = axis[2];
101
102  matrix[0][0] = t * x * x + c ;
103  matrix[0][1] = t * y * x - s * z ;
104  matrix[0][2] = t * z * x + s * y ;
105  matrix[0][3] = SG_ZERO;
106  
107  matrix[1][0] = t * x * y + s * z ;
108  matrix[1][1] = t * y * y + c ;
109  matrix[1][2] = t * z * y - s * x ;
110  matrix[1][3] = SG_ZERO;
111  
112  matrix[2][0] = t * x * z - s * y ;
113  matrix[2][1] = t * y * z + s * x ;
114  matrix[2][2] = t * z * z + c ;
115  matrix[2][3] = SG_ZERO;
116
117   // hint to the compiler to put these into FP registers
118  x = center[0];
119  y = center[1];
120  z = center[2];
121  
122  matrix[3][0] = x - x*matrix[0][0] - y*matrix[1][0] - z*matrix[2][0];
123  matrix[3][1] = y - x*matrix[0][1] - y*matrix[1][1] - z*matrix[2][1];
124  matrix[3][2] = z - x*matrix[0][2] - y*matrix[1][2] - z*matrix[2][2];
125  matrix[3][3] = SG_ONE;
126 }
127
128 /**
129  * Set up the transform matrix for a translation.
130  */
131 static void
132 set_translation (sgMat4 &matrix, double position_m, sgVec3 &axis)
133 {
134   sgVec3 xyz;
135   sgScaleVec3(xyz, axis, position_m);
136   sgMakeTransMat4(matrix, xyz);
137 }
138
139
140 /**
141  * Make an offset matrix from rotations and position offset.
142  */
143 static void
144 make_offsets_matrix (sgMat4 * result, double h_rot, double p_rot, double r_rot,
145                      double x_off, double y_off, double z_off)
146 {
147   sgMat4 rot_matrix;
148   sgMat4 pos_matrix;
149   sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
150   sgMakeTransMat4(pos_matrix, x_off, y_off, z_off);
151   sgMultMat4(*result, pos_matrix, rot_matrix);
152 }
153
154
155 /**
156  * Read an interpolation table from properties.
157  */
158 static SGInterpTable *
159 read_interpolation_table (SGPropertyNode_ptr props)
160 {
161   SGPropertyNode_ptr table_node = props->getNode("interpolation");
162   if (table_node != 0) {
163     SGInterpTable * table = new SGInterpTable();
164     vector<SGPropertyNode_ptr> entries = table_node->getChildren("entry");
165     for (unsigned int i = 0; i < entries.size(); i++)
166       table->addEntry(entries[i]->getDoubleValue("ind", 0.0),
167                       entries[i]->getDoubleValue("dep", 0.0));
168     return table;
169   } else {
170     return 0;
171   }
172 }
173
174
175 static void
176 make_animation (ssgBranch * model,
177                 vector<SGPropertyNode_ptr> &name_nodes,
178                 SGPropertyNode_ptr node)
179 {
180   Animation * animation = 0;
181   const char * type = node->getStringValue("type");
182   if (!strcmp("none", type)) {
183     animation = new NullAnimation(node);
184   } else if (!strcmp("range", type)) {
185     animation = new RangeAnimation(node);
186   } else if (!strcmp("billboard", type)) {
187     animation = new BillboardAnimation(node);
188   } else if (!strcmp("select", type)) {
189     animation = new SelectAnimation(node);
190   } else if (!strcmp("spin", type)) {
191     animation = new SpinAnimation(node);
192   } else if (!strcmp("rotate", type)) {
193     animation = new RotateAnimation(node);
194   } else if (!strcmp("translate", type)) {
195     animation = new TranslateAnimation(node);
196   } else {
197     animation = new NullAnimation(node);
198     SG_LOG(SG_INPUT, SG_WARN, "Unknown animation type " << type);
199   }
200
201   ssgEntity * object;
202   if (name_nodes.size() > 0) {
203     object = find_named_node(model, name_nodes[0]->getStringValue());
204     if (object == 0) {
205       SG_LOG(SG_INPUT, SG_WARN, "Object " << name_nodes[0]->getStringValue()
206              << " not found");
207       delete animation;
208       animation = 0;
209     }
210   } else {
211     object = model;
212   }
213   
214   ssgBranch * branch = animation->getBranch();
215   splice_branch(branch, object);
216
217   for (int i = 1; i < name_nodes.size(); i++) {
218       const char * name = name_nodes[i]->getStringValue();
219       object = find_named_node(model, name);
220       if (object == 0) {
221           SG_LOG(SG_INPUT, SG_WARN, "Object " << name << " not found");
222           delete animation;
223           animation = 0;
224       }
225       ssgBranch * oldParent = object->getParent(0);
226       std::cerr << "Moving " << name << " to new parent\n";
227       branch->addKid(object);
228       oldParent->removeKid(object);
229       std::cerr << "  leaf has " << object->getNumParents() << " parents\n";
230       std::cerr << "  branch has " << branch->getNumKids() << " kids\n";
231   }
232
233   branch->setUserData(animation);
234   branch->setTravCallback(SSG_CALLBACK_PRETRAV, animation_callback);
235 }
236
237
238 \f
239 ////////////////////////////////////////////////////////////////////////
240 // Global functions.
241 ////////////////////////////////////////////////////////////////////////
242
243 ssgBranch *
244 fgLoad3DModel (const string &path)
245 {
246   ssgBranch * model = 0;
247   SGPropertyNode props;
248
249                                 // Load the 3D aircraft object itself
250   SGPath xmlpath;
251   SGPath modelpath = path;
252   if ( path[ 0 ] == '/' || path[ 0 ] == '\\' || ( isalpha( path[ 0 ] ) && path[ 1 ] == ':' ) ) {
253     xmlpath = modelpath;
254   }
255   else {
256     xmlpath = globals->get_fg_root();
257     xmlpath.append(modelpath.str());
258   }
259
260                                 // Check for an XML wrapper
261   if (xmlpath.str().substr(xmlpath.str().size() - 4, 4) == ".xml") {
262     readProperties(xmlpath.str(), &props);
263     if (props.hasValue("/path")) {
264       modelpath = modelpath.dir();
265       modelpath.append(props.getStringValue("/path"));
266     } else {
267       if (model == 0)
268         model = new ssgBranch;
269     }
270   }
271
272                                 // Assume that textures are in
273                                 // the same location as the XML file.
274   if (model == 0) {
275     ssgTexturePath((char *)xmlpath.dir().c_str());
276     model = (ssgBranch *)ssgLoad((char *)modelpath.c_str());
277     if (model == 0)
278       throw sg_exception("Failed to load 3D model");
279   }
280
281                                 // Set up the alignment node
282   ssgTransform * align = new ssgTransform;
283   align->addKid(model);
284   sgMat4 res_matrix;
285   make_offsets_matrix(&res_matrix,
286                       props.getFloatValue("/offsets/heading-deg", 0.0),
287                       props.getFloatValue("/offsets/roll-deg", 0.0),
288                       props.getFloatValue("/offsets/pitch-deg", 0.0),
289                       props.getFloatValue("/offsets/x-m", 0.0),
290                       props.getFloatValue("/offsets/y-m", 0.0),
291                       props.getFloatValue("/offsets/z-m", 0.0));
292   align->setTransform(res_matrix);
293
294                                 // Load animations
295   vector<SGPropertyNode_ptr> animation_nodes = props.getChildren("animation");
296   unsigned int i;
297   for (i = 0; i < animation_nodes.size(); i++) {
298     vector<SGPropertyNode_ptr> name_nodes =
299       animation_nodes[i]->getChildren("object-name");
300     make_animation(model, name_nodes, animation_nodes[i]);
301   }
302
303                                 // Load panels
304   vector<SGPropertyNode_ptr> panel_nodes = props.getChildren("panel");
305   for (i = 0; i < panel_nodes.size(); i++) {
306     printf("Reading a panel in model.cxx\n");
307     FGPanelNode * panel = new FGPanelNode(panel_nodes[i]);
308     model->addKid(panel);
309   }
310
311                                 // Load sub-models
312   vector<SGPropertyNode_ptr> model_nodes = props.getChildren("model");
313   for (i = 0; i < model_nodes.size(); i++) {
314     SGPropertyNode_ptr node = model_nodes[i];
315     ssgTransform * align = new ssgTransform;
316     sgMat4 res_matrix;
317     make_offsets_matrix(&res_matrix,
318                         node->getFloatValue("offsets/heading-deg", 0.0),
319                         node->getFloatValue("offsets/roll-deg", 0.0),
320                         node->getFloatValue("offsets/pitch-deg", 0.0),
321                         node->getFloatValue("offsets/x-m", 0.0),
322                         node->getFloatValue("offsets/y-m", 0.0),
323                         node->getFloatValue("offsets/z-m", 0.0));
324     align->setTransform(res_matrix);
325
326     ssgBranch * kid = fgLoad3DModel(node->getStringValue("path"));
327     align->addKid(kid);
328     model->addKid(align);
329   }
330
331   return model;
332 }
333
334
335 \f
336 ////////////////////////////////////////////////////////////////////////
337 // Implementation of Animation
338 ////////////////////////////////////////////////////////////////////////
339
340 Animation::Animation (SGPropertyNode_ptr props, ssgBranch * branch)
341     : _branch(branch)
342 {
343     _branch->setName(props->getStringValue("name", 0));
344 }
345
346 Animation::~Animation ()
347 {
348 }
349
350
351 \f
352 ////////////////////////////////////////////////////////////////////////
353 // Implementation of NullAnimation
354 ////////////////////////////////////////////////////////////////////////
355
356 NullAnimation::NullAnimation (SGPropertyNode_ptr props)
357   : Animation(props, new ssgBranch)
358 {
359 }
360
361 NullAnimation::~NullAnimation ()
362 {
363 }
364
365 void
366 NullAnimation::update ()
367 {
368 }
369
370
371 \f
372 ////////////////////////////////////////////////////////////////////////
373 // Implementation of RangeAnimation
374 ////////////////////////////////////////////////////////////////////////
375
376 RangeAnimation::RangeAnimation (SGPropertyNode_ptr props)
377   : Animation(props, new ssgRangeSelector)
378 {
379     float ranges[] = { props->getFloatValue("min-m", 0),
380                        props->getFloatValue("max-m", 5000) };
381     ((ssgRangeSelector *)_branch)->setRanges(ranges, 2);
382                        
383 }
384
385 RangeAnimation::~RangeAnimation ()
386 {
387 }
388
389 void
390 RangeAnimation::update ()
391 {
392 }
393
394
395 \f
396 ////////////////////////////////////////////////////////////////////////
397 // Implementation of BillboardAnimation
398 ////////////////////////////////////////////////////////////////////////
399
400 BillboardAnimation::BillboardAnimation (SGPropertyNode_ptr props)
401     : Animation(props, new ssgCutout(props->getBoolValue("spherical", true)))
402 {
403 }
404
405 BillboardAnimation::~BillboardAnimation ()
406 {
407 }
408
409 void
410 BillboardAnimation::update ()
411 {
412 }
413
414
415 \f
416 ////////////////////////////////////////////////////////////////////////
417 // Implementation of SelectAnimation
418 ////////////////////////////////////////////////////////////////////////
419
420 SelectAnimation::SelectAnimation (SGPropertyNode_ptr props)
421   : Animation(props, new ssgSelector),
422     _condition(0)
423 {
424   SGPropertyNode_ptr node = props->getChild("condition");
425   if (node != 0)
426     _condition = fgReadCondition(node);
427 }
428
429 SelectAnimation::~SelectAnimation ()
430 {
431   delete _condition;
432 }
433
434 void
435 SelectAnimation::update ()
436 {
437   if (_condition != 0 && _condition->test()) 
438       ((ssgSelector *)_branch)->select(0xffff);
439   else
440       ((ssgSelector *)_branch)->select(0x0000);
441 }
442
443
444 \f
445 ////////////////////////////////////////////////////////////////////////
446 // Implementation of SpinAnimation
447 ////////////////////////////////////////////////////////////////////////
448
449 SpinAnimation::SpinAnimation (SGPropertyNode_ptr props)
450   : Animation(props, new ssgTransform),
451     _prop(fgGetNode(props->getStringValue("property", "/null"), true)),
452     _factor(props->getDoubleValue("factor", 1.0)),
453     _position_deg(props->getDoubleValue("starting-position-deg", 0)),
454     _last_time_sec(globals->get_sim_time_sec())
455 {
456     _center[0] = props->getFloatValue("center/x-m", 0);
457     _center[1] = props->getFloatValue("center/y-m", 0);
458     _center[2] = props->getFloatValue("center/z-m", 0);
459     _axis[0] = props->getFloatValue("axis/x", 0);
460     _axis[1] = props->getFloatValue("axis/y", 0);
461     _axis[2] = props->getFloatValue("axis/z", 0);
462     sgNormalizeVec3(_axis);
463 }
464
465 SpinAnimation::~SpinAnimation ()
466 {
467 }
468
469 void
470 SpinAnimation::update ()
471 {
472   double sim_time = globals->get_sim_time_sec();
473   double dt = sim_time - _last_time_sec;
474   _last_time_sec = sim_time;
475
476   float velocity_rpms = (_prop->getDoubleValue() * _factor / 60.0);
477   _position_deg += (dt * velocity_rpms * 360);
478   while (_position_deg < 0)
479     _position_deg += 360.0;
480   while (_position_deg >= 360.0)
481     _position_deg -= 360.0;
482   set_rotation(_matrix, _position_deg, _center, _axis);
483   ((ssgTransform *)_branch)->setTransform(_matrix);
484 }
485
486
487 \f
488 ////////////////////////////////////////////////////////////////////////
489 // Implementation of RotateAnimation
490 ////////////////////////////////////////////////////////////////////////
491
492 RotateAnimation::RotateAnimation (SGPropertyNode_ptr props)
493     : Animation(props, new ssgTransform),
494       _prop(fgGetNode(props->getStringValue("property", "/null"), true)),
495       _offset_deg(props->getDoubleValue("offset-deg", 0.0)),
496       _factor(props->getDoubleValue("factor", 1.0)),
497       _table(read_interpolation_table(props)),
498       _has_min(props->hasValue("min-deg")),
499       _min_deg(props->getDoubleValue("min-deg")),
500       _has_max(props->hasValue("max-deg")),
501       _max_deg(props->getDoubleValue("max-deg")),
502       _position_deg(props->getDoubleValue("starting-position-deg", 0))
503 {
504   _center[0] = props->getFloatValue("center/x-m", 0);
505   _center[1] = props->getFloatValue("center/y-m", 0);
506   _center[2] = props->getFloatValue("center/z-m", 0);
507   _axis[0] = props->getFloatValue("axis/x", 0);
508   _axis[1] = props->getFloatValue("axis/y", 0);
509   _axis[2] = props->getFloatValue("axis/z", 0);
510   sgNormalizeVec3(_axis);
511 }
512
513 RotateAnimation::~RotateAnimation ()
514 {
515   delete _table;
516 }
517
518 void
519 RotateAnimation::update ()
520 {
521   if (_table == 0) {
522     _position_deg = (_prop->getDoubleValue() + _offset_deg) * _factor;
523    if (_has_min && _position_deg < _min_deg)
524      _position_deg = _min_deg;
525    if (_has_max && _position_deg > _max_deg)
526      _position_deg = _max_deg;
527   } else {
528     _position_deg = _table->interpolate(_prop->getDoubleValue());
529   }
530   set_rotation(_matrix, _position_deg, _center, _axis);
531   ((ssgTransform *)_branch)->setTransform(_matrix);
532 }
533
534
535 \f
536 ////////////////////////////////////////////////////////////////////////
537 // Implementation of TranslateAnimation
538 ////////////////////////////////////////////////////////////////////////
539
540 TranslateAnimation::TranslateAnimation (SGPropertyNode_ptr props)
541   : Animation(props, new ssgTransform),
542     _prop(fgGetNode(props->getStringValue("property", "/null"), true)),
543     _offset_m(props->getDoubleValue("offset-m", 0.0)),
544     _factor(props->getDoubleValue("factor", 1.0)),
545     _table(read_interpolation_table(props)),
546     _has_min(props->hasValue("min-m")),
547     _min_m(props->getDoubleValue("min-m")),
548     _has_max(props->hasValue("max-m")),
549     _max_m(props->getDoubleValue("max-m")),
550     _position_m(props->getDoubleValue("starting-position-m", 0))
551 {
552   _axis[0] = props->getFloatValue("axis/x", 0);
553   _axis[1] = props->getFloatValue("axis/y", 0);
554   _axis[2] = props->getFloatValue("axis/z", 0);
555   sgNormalizeVec3(_axis);
556 }
557
558 TranslateAnimation::~TranslateAnimation ()
559 {
560   delete _table;
561 }
562
563 void
564 TranslateAnimation::update ()
565 {
566   if (_table == 0) {
567     _position_m = (_prop->getDoubleValue() + _offset_m) * _factor;
568     if (_has_min && _position_m < _min_m)
569       _position_m = _min_m;
570     if (_has_max && _position_m > _max_m)
571       _position_m = _max_m;
572   } else {
573     _position_m = _table->interpolate(_prop->getDoubleValue());
574   }
575   set_translation(_matrix, _position_m, _axis);
576   ((ssgTransform *)_branch)->setTransform(_matrix);
577 }
578
579
580 \f
581 ////////////////////////////////////////////////////////////////////////
582 // Implementation of FGModelPlacement.
583 ////////////////////////////////////////////////////////////////////////
584
585 FGModelPlacement::FGModelPlacement ()
586   : _lon_deg(0),
587     _lat_deg(0),
588     _elev_ft(0),
589     _roll_deg(0),
590     _pitch_deg(0),
591     _heading_deg(0),
592     _selector(new ssgSelector),
593     _position(new ssgTransform),
594     _location(new FGLocation)
595 {
596 }
597
598 FGModelPlacement::~FGModelPlacement ()
599 {
600 }
601
602 void
603 FGModelPlacement::init (const string &path)
604 {
605   ssgBranch * model = fgLoad3DModel(path);
606   if (model != 0)
607       _position->addKid(model);
608   _selector->addKid(_position);
609   _selector->clrTraversalMaskBits(SSGTRAV_HOT);
610 }
611
612 void
613 FGModelPlacement::update ()
614 {
615   _location->setPosition( _lon_deg, _lat_deg, _elev_ft );
616   _location->setOrientation( _roll_deg, _pitch_deg, _heading_deg );
617
618   sgMat4 POS;
619   sgCopyMat4(POS, _location->getTransformMatrix());
620   
621   sgVec3 trans;
622   sgCopyVec3(trans, _location->get_view_pos());
623
624   for(int i = 0; i < 4; i++) {
625     float tmp = POS[i][3];
626     for( int j=0; j<3; j++ ) {
627       POS[i][j] += (tmp * trans[j]);
628     }
629   }
630   _position->setTransform(POS);
631 }
632
633 bool
634 FGModelPlacement::getVisible () const
635 {
636   return (_selector->getSelect() != 0);
637 }
638
639 void
640 FGModelPlacement::setVisible (bool visible)
641 {
642   _selector->select(visible);
643 }
644
645 void
646 FGModelPlacement::setLongitudeDeg (double lon_deg)
647 {
648   _lon_deg = lon_deg;
649 }
650
651 void
652 FGModelPlacement::setLatitudeDeg (double lat_deg)
653 {
654   _lat_deg = lat_deg;
655 }
656
657 void
658 FGModelPlacement::setElevationFt (double elev_ft)
659 {
660   _elev_ft = elev_ft;
661 }
662
663 void
664 FGModelPlacement::setPosition (double lon_deg, double lat_deg, double elev_ft)
665 {
666   _lon_deg = lon_deg;
667   _lat_deg = lat_deg;
668   _elev_ft = elev_ft;
669 }
670
671 void
672 FGModelPlacement::setRollDeg (double roll_deg)
673 {
674   _roll_deg = roll_deg;
675 }
676
677 void
678 FGModelPlacement::setPitchDeg (double pitch_deg)
679 {
680   _pitch_deg = pitch_deg;
681 }
682
683 void
684 FGModelPlacement::setHeadingDeg (double heading_deg)
685 {
686   _heading_deg = heading_deg;
687 }
688
689 void
690 FGModelPlacement::setOrientation (double roll_deg, double pitch_deg,
691                                   double heading_deg)
692 {
693   _roll_deg = roll_deg;
694   _pitch_deg = pitch_deg;
695   _heading_deg = heading_deg;
696 }
697
698 // end of model.cxx