]> git.mxchange.org Git - simgear.git/blob - simgear/scene/model/SGTrackToAnimation.cxx
Use simulation time for spin and timed animations
[simgear.git] / simgear / scene / model / SGTrackToAnimation.cxx
1 // TrackTo animation
2 //
3 // Copyright (C) 2013  Thomas Geymayer <tomgey@gmail.com>
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Library General Public
7 // License as published by the Free Software Foundation; either
8 // version 2 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // Library General Public License for more details.
14 //
15 // You should have received a copy of the GNU Library General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA
18
19 #include "SGRotateTransform.hxx"
20 #include "SGTrackToAnimation.hxx"
21
22 #include <simgear/scene/util/OsgMath.hxx>
23 #include <osg/Transform>
24 #include <cassert>
25
26 /**
27  *
28  */
29 static osg::NodePath requireNodePath( osg::Node* node,
30                                       osg::Node* haltTraversalAtNode = 0 )
31 {
32   const osg::NodePathList node_paths =
33     node->getParentalNodePaths(haltTraversalAtNode);
34   return node_paths.at(0);
35 }
36
37 /**
38  * Get a subpath of an osg::NodePath
39  *
40  * @param path  Path to extract subpath from
41  * @param start Number of elements to skip from start of #path
42  *
43  * @return Subpath starting with node at position #start
44  */
45 static osg::NodePath subPath( const osg::NodePath& path,
46                               size_t start )
47 {
48   if( start >= path.size() )
49     return osg::NodePath();
50
51   osg::NodePath np(path.size() - start);
52   for(size_t i = start; i < path.size(); ++i)
53     np[i - start] = path[i];
54
55   return np;
56 }
57
58 /**
59  * Visitor to find a group by its name.
60  */
61 class FindGroupVisitor:
62   public osg::NodeVisitor
63 {
64   public:
65
66     FindGroupVisitor(const std::string& name):
67         osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
68         _name(name),
69         _group(0)
70     {
71       if( name.empty() )
72         SG_LOG(SG_IO, SG_WARN, "FindGroupVisitor: empty name provided");
73     }
74
75     osg::Group* getGroup() const
76     {
77       return _group;
78     }
79
80     virtual void apply(osg::Group& group)
81     {
82       if( _name != group.getName() )
83         return traverse(group);
84
85       if( !_group )
86         _group = &group;
87       else
88         SG_LOG
89         (
90           SG_IO,
91           SG_WARN,
92           "FindGroupVisitor: name not unique '" << _name << "'"
93         );
94     }
95
96   protected:
97
98     std::string _name;
99     osg::Group *_group;
100 };
101
102 /**
103  * Get angle of a triangle given by three side lengths
104  *
105  * @return Angle enclosed by @c side1 and @c side2
106  */
107 double angleFromSSS(double side1, double side2, double opposite)
108 {
109   return std::acos
110   (
111     ( SGMiscd::pow<2>(side1)
112     + SGMiscd::pow<2>(side2)
113     - SGMiscd::pow<2>(opposite)
114     ) / (2 * side1 * side2)
115   );
116 }
117
118 //------------------------------------------------------------------------------
119 class SGTrackToAnimation::UpdateCallback:
120   public osg::NodeCallback
121 {
122   public:
123     UpdateCallback( osg::Group* target,
124                     const SGTrackToAnimation* anim,
125                     SGRotateTransform* slave_tf ):
126       _target(target),
127       _slave_tf(slave_tf),
128       _root_length(0),
129       _slave_length(0),
130       _root_initial_angle(0),
131       _condition(anim->getCondition()),
132       _root_disabled_value(
133         anim->readOffsetValue("disabled-rotation-deg")
134       ),
135       _slave_disabled_value(
136         anim->readOffsetValue("slave-disabled-rotation-deg")
137       )
138     {
139       setName("SGTrackToAnimation::UpdateCallback");
140
141       _node_center = toOsg( anim->readVec3("center", "-m") );
142       _slave_center = toOsg( anim->readVec3("slave-center", "-m") );
143       _target_center = toOsg( anim->readVec3("target-center", "-m") );
144       _lock_axis = toOsg( anim->readVec3("lock-axis") );
145       _track_axis = toOsg( anim->readVec3("track-axis") );
146
147       if( _lock_axis.normalize() == 0.0 )
148       {
149         anim->log(SG_WARN, "invalid lock-axis");
150         _lock_axis.set(0, 1, 0);
151       }
152
153       if( _slave_center != osg::Vec3() )
154       {
155         _root_length = (_slave_center - _node_center).length();
156         _slave_length = (_target_center - _slave_center).length();
157         double dist = (_target_center - _node_center).length();
158
159         _root_initial_angle = angleFromSSS(_root_length, dist, _slave_length);
160
161         // If no rotation should be applied to the slave element it is looking
162         // in the same direction then the root node. Inside the triangle given
163         // by the root length, slave length and distance from the root node to
164         // the target node, this equals an angle of 180 degrees.
165         _slave_initial_angle = angleFromSSS(_root_length, _slave_length, dist)
166                              - SGMiscd::pi();
167
168         _track_axis = _target_center - _node_center;
169       }
170
171       for(;;)
172       {
173         float proj = _lock_axis * _track_axis;
174         if( proj != 0.0 )
175         {
176           anim->log(SG_WARN, "track-axis not perpendicular to lock-axis");
177
178           // Make tracking axis perpendicular to locked axis
179           _track_axis -= _lock_axis * proj;
180         }
181
182         if( _track_axis.normalize() == 0.0 )
183         {
184           anim->log(SG_WARN, "invalid track-axis");
185           if( std::fabs(_lock_axis.x()) < 0.1 )
186             _track_axis.set(1, 0, 0);
187           else
188             _track_axis.set(0, 1, 0);
189         }
190         else
191           break;
192       }
193
194       _up_axis = _lock_axis ^ _track_axis;
195     }
196
197     virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
198     {
199       SGRotateTransform* tf = static_cast<SGRotateTransform*>(node);
200
201       // We need to wait with this initialization steps until the first update
202       // as this allows us to be sure all animations have already been installed
203       // and are therefore also accounted for calculating the animation.
204       if( _target )
205       {
206         // Get path to animated node and calculated simplified paths to the
207         // nearest common parent node of both the animated node and the target
208         // node
209
210                                   // start at parent to not get false results by
211                                   // also including animation transformation
212         osg::NodePath node_path = requireNodePath(node->getParent(0)),
213                       target_path = requireNodePath(_target);
214         size_t tp_size = target_path.size(),
215                np_size = node_path.size();
216         size_t common_parents = 0;
217
218         for(; common_parents < std::min(tp_size, np_size); ++common_parents)
219         {
220           if( target_path[common_parents] != node_path[common_parents] )
221             break;
222         }
223
224         _node_path = subPath(node_path, common_parents);
225         _target_path = subPath(target_path, common_parents);
226         _target = 0;
227
228         tf->setCenter( toSG(_node_center) );
229         tf->setAxis( toSG(_lock_axis) );
230
231         if( _slave_tf )
232         {
233           _slave_tf->setCenter( toSG(_slave_center) );
234           _slave_tf->setAxis( toSG(_lock_axis) );
235         }
236       }
237
238       osg::Vec3 target_pos = ( osg::computeLocalToWorld(_target_path)
239                              * osg::computeWorldToLocal(_node_path)
240                              ).preMult(_target_center),
241                        dir = target_pos - _node_center;
242
243       double root_angle,
244              slave_angle;
245
246       if( !_condition || _condition->test() )
247       {
248         root_angle = -_root_initial_angle;
249         slave_angle = -_slave_initial_angle;
250
251         if( _root_length > 0 )
252         {
253           double dist = dir.length();
254           if( dist < _root_length + _slave_length )
255           {
256             root_angle += angleFromSSS(_root_length, dist, _slave_length);
257
258             if( _slave_tf )
259               slave_angle += angleFromSSS(_root_length, _slave_length, dist)
260                            - SGMiscd::pi();
261           }
262         }
263
264         // Ensure direction is perpendicular to lock axis
265         float proj = _lock_axis * dir;
266         if( proj != 0.0 )
267           dir -= _lock_axis * proj;
268
269         float x = dir * _track_axis,
270               y = dir * _up_axis;
271         root_angle += std::atan2(y, x);
272       }
273       else
274       {
275         root_angle = _root_disabled_value
276                    ? SGMiscd::deg2rad(_root_disabled_value->getValue())
277                    : 0;
278         slave_angle = _slave_disabled_value
279                     ? SGMiscd::deg2rad(_slave_disabled_value->getValue())
280                     : 0;
281       }
282
283       tf->setAngleRad( root_angle );
284       if( _slave_tf )
285         _slave_tf->setAngleRad(slave_angle);
286
287       traverse(node, nv);
288     }
289   protected:
290
291     osg::Vec3           _node_center,
292                         _slave_center,
293                         _target_center,
294                         _lock_axis,
295                         _track_axis,
296                         _up_axis;
297     osg::Group         *_target;
298     SGRotateTransform  *_slave_tf;
299     osg::NodePath       _node_path,
300                         _target_path;
301     double              _root_length,
302                         _slave_length,
303                         _root_initial_angle,
304                         _slave_initial_angle;
305
306     SGSharedPtr<SGCondition const>      _condition;
307     SGExpressiond_ref   _root_disabled_value,
308                         _slave_disabled_value;
309 };
310
311 //------------------------------------------------------------------------------
312 SGTrackToAnimation::SGTrackToAnimation( osg::Node* node,
313                                         const SGPropertyNode* configNode,
314                                         SGPropertyNode* modelRoot ):
315   SGAnimation(configNode, modelRoot),
316   _target_group(0),
317   _slave_group(0)
318 {
319   std::string target = configNode->getStringValue("target-name");
320   FindGroupVisitor target_finder(target);
321   node->accept(target_finder);
322
323   if( !(_target_group = target_finder.getGroup()) )
324     log(SG_ALERT, "target not found: '" + target + '\'');
325
326   std::string slave = configNode->getStringValue("slave-name");
327   if( !slave.empty() )
328   {
329     FindGroupVisitor slave_finder(slave);
330     node->accept(slave_finder);
331     _slave_group = slave_finder.getGroup();
332   }
333 }
334
335 //------------------------------------------------------------------------------
336 osg::Group* SGTrackToAnimation::createAnimationGroup(osg::Group& parent)
337 {
338   if( !_target_group )
339     return 0;
340
341   SGRotateTransform* slave_tf = 0;
342   if( _slave_group )
343   {
344     slave_tf = new SGRotateTransform;
345     slave_tf->setName("locked-track slave animation");
346
347     osg::Group* parent = _slave_group->getParent(0);
348     slave_tf->addChild(_slave_group);
349     parent->removeChild(_slave_group);
350     parent->addChild(slave_tf);
351   }
352
353   SGRotateTransform* tf = new SGRotateTransform;
354   tf->setName("locked-track animation");
355   tf->setUpdateCallback(new UpdateCallback(_target_group, this, slave_tf));
356   parent.addChild(tf);
357
358   return tf;
359 }
360
361 //------------------------------------------------------------------------------
362 void SGTrackToAnimation::log(sgDebugPriority p, const std::string& msg) const
363 {
364   SG_LOG
365   (
366     SG_IO,
367     p,
368     // TODO handle multiple object-names?
369     "SGTrackToAnimation(" << getConfig()->getStringValue("object-name") << "): "
370     << msg
371   );
372 }