]> git.tdb.fi Git - libs/gl.git/blob - source/animation.cpp
Plug some memory leaks
[libs/gl.git] / source / animation.cpp
1 #include <cmath>
2 #include <msp/core/maputils.h>
3 #include <msp/datafile/collection.h>
4 #include <msp/interpolate/bezierspline.h>
5 #include "animation.h"
6 #include "animationeventobserver.h"
7 #include "armature.h"
8 #include "error.h"
9 #include "pose.h"
10
11 using namespace std;
12
13 namespace Msp {
14 namespace GL {
15
16 Animation::Animation():
17         armature(0),
18         looping(false)
19 { }
20
21 Animation::~Animation()
22 {
23         for(vector<Curve *>::iterator i=curves.begin(); i!=curves.end(); ++i)
24                 delete *i;
25 }
26
27 void Animation::set_armature(const Armature &a)
28 {
29         if(!keyframes.empty() && &a!=armature)
30                 throw invalid_operation("Animation::set_armature");
31         armature = &a;
32 }
33
34 unsigned Animation::get_slot_for_uniform(const string &n) const
35 {
36         for(unsigned i=0; i<uniforms.size(); ++i)
37                 if(uniforms[i].name==n)
38                         return i;
39         throw key_error(n);
40 }
41
42 const string &Animation::get_uniform_name(unsigned i) const
43 {
44         if(i>=uniforms.size())
45                 throw out_of_range("Animation::get_uniform_name");
46         return uniforms[i].name;
47 }
48
49 void Animation::add_keyframe(const Time::TimeDelta &t, const KeyFrame &kf)
50 {
51         add_keyframe(t, &kf, false, false);
52         create_curves();
53 }
54
55 void Animation::add_keyframe_owned(const Time::TimeDelta &t, const KeyFrame *kf)
56 {
57         add_keyframe(t, kf, false, true);
58         create_curves();
59 }
60
61 void Animation::add_keyframe(const Time::TimeDelta &t, const KeyFrame &kf, float slope)
62 {
63         add_keyframe(t, &kf, slope, slope, false);
64         create_curves();
65 }
66
67 void Animation::add_keyframe(const Time::TimeDelta &t, const KeyFrame &kf, float ss, float es)
68 {
69         add_keyframe(t, &kf, ss, es, false);
70         create_curves();
71 }
72
73 void Animation::add_control_keyframe(const KeyFrame &kf)
74 {
75         if(keyframes.empty())
76                 throw invalid_operation("Animation::add_control_keyframe");
77
78         add_keyframe(keyframes.back().time, &kf, true, false);
79 }
80
81 void Animation::add_control_keyframe_owned(const KeyFrame *kf)
82 {
83         if(keyframes.empty())
84                 throw invalid_operation("Animation::add_control_keyframe_owned");
85
86         add_keyframe(keyframes.back().time, kf, true, true);
87 }
88
89 void Animation::add_keyframe(const Time::TimeDelta &t, const KeyFrame *kf, float ss, float es, bool owned)
90 {
91         if(keyframes.empty())
92                 return add_keyframe(t, kf, false, owned);
93
94         if(keyframes.back().control)
95                 throw invalid_operation("Animation::add_keyframe");
96
97         const KeyFrame &last = *keyframes.back().keyframe;
98         const Transform &trn = kf->get_transform();
99         const Transform &last_trn = last.get_transform();
100         const KeyFrame::UniformMap &kf_unis = kf->get_uniforms();
101         const KeyFrame::UniformMap &last_unis = last.get_uniforms();
102         for(unsigned i=1; i<=2; ++i)
103         {
104                 float x = (i==1 ? ss/3 : 1-es/3);
105                 KeyFrame *ckf = new KeyFrame;
106                 Transform ctrn;
107                 ctrn.set_position(last_trn.get_position()*(1-x)+trn.get_position()*x);
108                 const Transform::AngleVector3 &e1 = last_trn.get_euler();
109                 const Transform::AngleVector3 &e2 = trn.get_euler();
110                 ctrn.set_euler(Transform::AngleVector3(e1.x*(1-x)+e2.x*x, e1.y*(1-x)+e2.y*x, e1.z*(1-x)+e2.z*x));
111                 ctrn.set_scale(last_trn.get_scale()*(1-x)+trn.get_scale()*x);
112                 ckf->set_transform(ctrn);
113
114                 for(KeyFrame::UniformMap::const_iterator j=kf_unis.begin(); j!=kf_unis.end(); ++j)
115                 {
116                         KeyFrame::UniformMap::const_iterator k = last_unis.find(j->first);
117                         if(k==last_unis.end())
118                                 continue;
119
120                         KeyFrame::AnimatedUniform uni(j->second.size, 0.0f);
121                         for(unsigned c=0; c<uni.size; ++c)
122                                 uni.values[c] = k->second.values[c]*(1-x)+j->second.values[c]*x;
123
124                         ckf->set_uniform(j->first, uni);
125                 }
126
127                 add_keyframe(t, ckf, true, true);
128         }
129
130         add_keyframe(t, kf, false, owned);
131 }
132
133 void Animation::add_keyframe(const Time::TimeDelta &t, const KeyFrame *kf, bool c, bool owned)
134 {
135         if(c && keyframes.empty())
136                 throw invalid_argument("Animation::add_keyframe");
137         if(keyframes.empty() && t!=Time::zero)
138                 throw invalid_argument("Animation::add_keyframe");
139         if(!keyframes.empty() && t<keyframes.back().time)
140                 throw invalid_argument("Animation::add_keyframe");
141         if(kf->get_pose() && armature && kf->get_pose()->get_armature()!=armature)
142                 throw invalid_argument("Animation::add_keyframe");
143
144         const KeyFrame::UniformMap &kf_uniforms = kf->get_uniforms();
145         for(vector<UniformInfo>::const_iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
146         {
147                 KeyFrame::UniformMap::const_iterator j = kf_uniforms.find(i->name);
148                 if(j!=kf_uniforms.end() && j->second.size!=i->size)
149                         throw invalid_argument("Animation::add_keyframe");
150         }
151
152         if(kf->get_pose() && !armature)
153                 armature = kf->get_pose()->get_armature();
154
155         TimedKeyFrame tkf;
156         tkf.time = t;
157         tkf.keyframe = kf;
158         if(!owned)
159                 tkf.keyframe.keep();
160         tkf.control = c;
161
162         keyframes.push_back(tkf);
163
164         for(KeyFrame::UniformMap::const_iterator i=kf_uniforms.begin(); i!=kf_uniforms.end(); ++i)
165         {
166                 bool found = false;
167                 for(vector<UniformInfo>::const_iterator j=uniforms.begin(); (!found && j!=uniforms.end()); ++j)
168                         found = (j->name==i->first);
169
170                 if(!found)
171                         uniforms.push_back(UniformInfo(i->first, i->second.size));
172         }
173 }
174
175 void Animation::create_curves()
176 {
177         for(vector<Curve *>::iterator i=curves.begin(); i!=curves.end(); ++i)
178                 delete *i;
179         curves.clear();
180
181         curves.reserve(6+uniforms.size());
182         create_curve(POSITION, Transform::POSITION, &extract_position);
183         create_curve(EULER, Transform::EULER, &extract_euler);
184         create_curve(SCALE, Transform::SCALE, &extract_scale);
185
186         uniform_curve_offset = curves.size();
187         for(vector<UniformInfo>::const_iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
188         {
189                 if(i->size==1)
190                         create_curve<1>(UNIFORM, -1, ExtractUniform<1>(i->name));
191                 else if(i->size==2)
192                         create_curve<2>(UNIFORM, -1, ExtractUniform<2>(i->name));
193                 else if(i->size==3)
194                         create_curve<3>(UNIFORM, -1, ExtractUniform<3>(i->name));
195                 else if(i->size==4)
196                         create_curve<4>(UNIFORM, -1, ExtractUniform<4>(i->name));
197         }
198 }
199
200 void Animation::create_curve(CurveTarget target, Transform::ComponentMask mask, ExtractComponent::Extract extract)
201 {
202         Transform::ComponentMask all = mask;
203         Transform::ComponentMask any = Transform::NONE;
204         for(vector<TimedKeyFrame>::const_iterator i=keyframes.begin(); i!=keyframes.end(); ++i)
205         {
206                 all = all&i->keyframe->get_transform().get_mask();
207                 any = any|i->keyframe->get_transform().get_mask();
208         }
209
210         if(all==mask)
211                 create_curve<3>(target, -1, extract);
212         else if(any&mask)
213         {
214                 unsigned low_bit = mask&(mask>>2);
215                 for(unsigned i=3; i-->0; )
216                 {
217                         Transform::ComponentMask bit = static_cast<Transform::ComponentMask>(low_bit<<i);
218                         if(any&bit)
219                                 create_curve<1>(target, i, ExtractComponent(extract, i, bit));
220                 }
221         }
222 }
223
224 template<unsigned N, typename T>
225 void Animation::create_curve(CurveTarget target, int component, const T &extract)
226 {
227         typedef typename ValueCurve<N>::Knot Knot;
228
229         vector<Knot> knots;
230         unsigned n_control = 0;
231         for(vector<TimedKeyFrame>::const_iterator i=keyframes.begin(); i!=keyframes.end(); ++i)
232         {
233                 if(i->control && knots.empty())
234                         continue;
235
236                 typename Interpolate::SplineValue<float, N>::Type value;
237                 if(extract(*i->keyframe, value))
238                 {
239                         typename Knot::Value dvalue = value;
240                         float x = i->time/Time::sec;
241                         if(i->control)
242                         {
243                                 ++n_control;
244                                 if(n_control>2)
245                                         throw logic_error("too many control keyframes");
246                         }
247                         else
248                         {
249                                 if(n_control==1)
250                                 {
251                                         typename Knot::Value cv = knots.back().y;
252                                         knots.back().y = (knots[knots.size()-2].y+cv*2.0)/3.0;
253                                         knots.push_back(Knot(x, (dvalue+cv*2.0)/3.0));
254                                 }
255                                 else if(n_control==0 && !knots.empty())
256                                 {
257                                         typename Knot::Value prev = knots.back().y;
258                                         knots.push_back(Knot(knots.back().x, (prev*2.0+dvalue)/3.0));
259                                         knots.push_back(Knot(x, (prev+dvalue*2.0)/3.0));
260                                 }
261                                 n_control = 0;
262                         }
263                         knots.push_back(Knot(x, value));
264                 }
265         }
266         
267         while(n_control--)
268                 knots.pop_back();
269
270         curves.push_back(new ValueCurve<N>(target, component, knots));
271 }
272
273 bool Animation::extract_position(const KeyFrame &kf, Vector3 &value)
274 {
275         value = kf.get_transform().get_position();
276         return true;
277 }
278
279 bool Animation::extract_euler(const KeyFrame &kf, Vector3 &value)
280 {
281         const Transform::AngleVector3 &euler = kf.get_transform().get_euler();
282         value = Vector3(euler.x.radians(), euler.y.radians(), euler.z.radians());
283         return true;
284 }
285
286 bool Animation::extract_scale(const KeyFrame &kf, Vector3 &value)
287 {
288         value = kf.get_transform().get_scale();
289         return true;
290 }
291
292 void Animation::add_event(const Time::TimeDelta &t, const string &n, const Variant &v)
293 {
294         Event event;
295         event.time = t;
296         event.name = n;
297         event.value = v;
298         events.push_back(event);
299 }
300
301 const Time::TimeDelta &Animation::get_duration() const
302 {
303         if(keyframes.empty())
304                 return Time::zero;
305
306         return keyframes.back().time;
307 }
308
309 void Animation::set_looping(bool l)
310 {
311         looping = l;
312 }
313
314
315 Animation::Curve::Curve(CurveTarget t, int c):
316         target(t),
317         component(c)
318 { }
319
320
321 template<unsigned N>
322 Animation::ValueCurve<N>::ValueCurve(CurveTarget t, int c, const vector<Knot> &k):
323         Curve(t, c),
324         spline(Interpolate::BezierSpline<double, 3, N>(k))
325 { }
326
327 template<unsigned N>
328 void Animation::ValueCurve<N>::apply(float, Matrix &) const
329 {
330         throw invalid_operation("ValueCurve::apply");
331 }
332
333 template<>
334 void Animation::ValueCurve<1>::apply(float x, Matrix &matrix) const
335 {
336         float value = spline(x);
337         if(target==POSITION || target==SCALE)
338         {
339                 Vector3 vec;
340                 vec[component] = value;
341                 if(target==POSITION)
342                         matrix.translate(vec);
343                 else
344                         matrix.scale(vec);
345         }
346         else if(target==EULER)
347         {
348                 Vector3 vec;
349                 vec[component] = 1.0f;
350                 matrix.rotate(Geometry::Angle<float>::from_radians(value), vec);
351         }
352         else
353                 throw invalid_operation("ValueCurve::apply");
354 }
355
356 template<>
357 void Animation::ValueCurve<3>::apply(float x, Matrix &matrix) const
358 {
359         Vector3 value = spline(x);
360         if(target==POSITION)
361                 matrix.translate(value);
362         else if(target==EULER)
363         {
364                 matrix.rotate(Geometry::Angle<float>::from_radians(value.z), Vector3(0, 0, 1));
365                 matrix.rotate(Geometry::Angle<float>::from_radians(value.y), Vector3(0, 1, 0));
366                 matrix.rotate(Geometry::Angle<float>::from_radians(value.x), Vector3(1, 0, 0));
367         }
368         else if(target==SCALE)
369                 matrix.scale(value);
370         else
371                 throw invalid_operation("ValueCurve::apply");
372 }
373
374 template<unsigned N>
375 void Animation::ValueCurve<N>::apply(float x, KeyFrame::AnimatedUniform &uni) const
376 {
377         uni.size = N;
378         typename Interpolate::Spline<double, 3, N>::Value value = spline(x);
379         for(unsigned i=0; i<N; ++i)
380                 uni.values[i] = Interpolate::SplineValue<float, N>::get(value, i);
381 }
382
383
384 bool Animation::ExtractComponent::operator()(const KeyFrame &kf, float &value) const
385 {
386         Vector3 vec;
387         if(!extract(kf, vec))
388                 return false;
389
390         value = vec[index];
391         return kf.get_transform().get_mask()&mask;
392 }
393
394
395 template<unsigned N>
396 bool Animation::ExtractUniform<N>::operator()(const KeyFrame &kf, typename Interpolate::SplineValue<float, N>::Type &value) const
397 {
398         const KeyFrame::UniformMap &kf_uniforms = kf.get_uniforms();
399         const KeyFrame::UniformMap::const_iterator i = kf_uniforms.find(name);
400         if(i==kf_uniforms.end())
401                 return false;
402
403         value = Interpolate::SplineValue<float, N>::make(i->second.values);
404         return true;
405 }
406
407
408 Animation::UniformInfo::UniformInfo(const string &n, unsigned s):
409         name(n),
410         size(s)
411 { }
412
413
414 Animation::Iterator::Iterator(const Animation &a):
415         animation(&a),
416         event_iter(animation->events.begin()),
417         end(false)
418 {
419 }
420
421 Animation::Iterator &Animation::Iterator::operator+=(const Time::TimeDelta &t)
422 {
423         const Time::TimeDelta &duration = animation->get_duration();
424         if(!duration)
425                 return *this;
426
427         elapsed += t;
428         if(animation->looping)
429         {
430                 while(elapsed>=duration)
431                         elapsed -= duration;
432         }
433         else if(elapsed>=duration)
434         {
435                 end = true;
436                 elapsed = duration;
437         }
438
439         return *this;
440 }
441
442 void Animation::Iterator::dispatch_events(AnimationEventObserver &observer)
443 {
444         for(; (event_iter!=animation->events.end() && event_iter->time<=elapsed); ++event_iter)
445                 observer.animation_event(0, event_iter->name, event_iter->value);
446 }
447
448 Matrix Animation::Iterator::get_matrix() const
449 {
450         Matrix matrix;
451         for(unsigned i=0; i<animation->uniform_curve_offset; ++i)
452                 animation->curves[i]->apply(elapsed/Time::sec, matrix);
453         return matrix;
454 }
455
456 KeyFrame::AnimatedUniform Animation::Iterator::get_uniform(unsigned i) const
457 {
458         if(i>=animation->uniforms.size())
459                 throw out_of_range("Animation::Iterator::get_uniform");
460
461         KeyFrame::AnimatedUniform uni(animation->uniforms[i].size, 0.0f);
462         animation->curves[animation->uniform_curve_offset+i]->apply(elapsed/Time::sec, uni);
463         return uni;
464 }
465
466 Matrix Animation::Iterator::get_pose_matrix(unsigned link) const
467 {
468         if(!animation->armature)
469                 throw invalid_operation("Animation::Iterator::get_pose_matrix");
470         if(link>animation->armature->get_max_link_index())
471                 throw out_of_range("Animation::Iterator::get_pose_matrix");
472
473         throw logic_error("pose animations are currently unimplemented");
474 }
475
476
477 Animation::Loader::Loader(Animation &a):
478         DataFile::CollectionObjectLoader<Animation>(a, 0)
479 {
480         init();
481 }
482
483 Animation::Loader::Loader(Animation &a, Collection &c):
484         DataFile::CollectionObjectLoader<Animation>(a, &c)
485 {
486         init();
487 }
488
489 void Animation::Loader::init()
490 {
491         start_slope = 1;
492         end_slope = 1;
493         slopes_set = 0;
494         add("armature", &Animation::armature);
495         add("control_keyframe", &Loader::control_keyframe);
496         add("control_keyframe", &Loader::control_keyframe_inline);
497         add("event", &Loader::event);
498         add("event", &Loader::event1i);
499         add("event", &Loader::event1f);
500         add("event", &Loader::event2f);
501         add("event", &Loader::event3f);
502         add("event", &Loader::event4f);
503         add("interval", &Loader::interval);
504         add("keyframe", &Loader::keyframe);
505         add("keyframe", &Loader::keyframe_inline);
506         add("looping", &Animation::looping);
507         add("slopes", &Loader::slopes);
508 }
509
510 void Animation::Loader::finish()
511 {
512         obj.create_curves();
513 }
514
515 void Animation::Loader::check_slopes_and_control(bool s, bool c)
516 {
517         if(s && c)
518                 throw logic_error("can't use both slopes and control keyframes in same segment");
519 }
520
521 void Animation::Loader::add_kf(const KeyFrame *kf, bool c, bool owned)
522 {
523         if(slopes_set && !c)
524                 obj.add_keyframe(current_time, kf, start_slope, end_slope, owned);
525         else
526                 obj.add_keyframe(current_time, kf, c, owned);
527
528         start_slope = end_slope;
529         end_slope = 1;
530         slopes_set = (slopes_set<<1)&3;
531 }
532
533 void Animation::Loader::load_kf(const string &n, bool c)
534 {
535         add_kf(&get_collection().get<KeyFrame>(n), c, false);
536 }
537
538 void Animation::Loader::load_kf_inline(bool c)
539 {
540         RefPtr<KeyFrame> kf = new KeyFrame;
541         if(coll)
542                 load_sub(*kf, get_collection());
543         else
544                 load_sub(*kf);
545
546         add_kf(kf.get(), c, true);
547         kf.release();
548 }
549
550 void Animation::Loader::control_keyframe(const string &n)
551 {
552         slopes_set &= 1;
553         check_slopes_and_control(slopes_set, true);
554         load_kf(n, true);
555 }
556
557 void Animation::Loader::control_keyframe_inline()
558 {
559         slopes_set &= 1;
560         check_slopes_and_control(slopes_set, true);
561         load_kf_inline(true);
562 }
563
564 void Animation::Loader::event(const string &n)
565 {
566         obj.add_event(current_time, n);
567 }
568
569 void Animation::Loader::event1i(const string &n, int v)
570 {
571         obj.add_event(current_time, n, v);
572 }
573
574 void Animation::Loader::event1f(const string &n, float v)
575 {
576         obj.add_event(current_time, n, v);
577 }
578
579 void Animation::Loader::event2f(const string &n, float v0, float v1)
580 {
581         obj.add_event(current_time, n, LinAl::Vector<float, 2>(v0, v1));
582 }
583
584 void Animation::Loader::event3f(const string &n, float v0, float v1, float v2)
585 {
586         obj.add_event(current_time, n, Vector3(v0, v1, v2));
587 }
588
589 void Animation::Loader::event4f(const string &n, float v0, float v1, float v2, float v3)
590 {
591         obj.add_event(current_time, n, Vector4(v0, v1, v2, v3));
592 }
593
594 void Animation::Loader::interval(float t)
595 {
596         current_time += t*Time::sec;
597 }
598
599 void Animation::Loader::keyframe(const string &n)
600 {
601         load_kf(n, false);
602 }
603
604 void Animation::Loader::keyframe_inline()
605 {
606         load_kf_inline(false);
607 }
608
609 void Animation::Loader::slopes(float s, float e)
610 {
611         check_slopes_and_control(true, (!obj.keyframes.empty() && obj.keyframes.back().control));
612
613         start_slope = s;
614         end_slope = e;
615         slopes_set = 1;
616 }
617
618 } // namespace GL
619 } // namespace Msp