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