载入中...
搜索中...
未找到
MotionBuilder.cpp
浏览该文件的文档.
2#include <array>
3#include <bit>
4#include <cmath>
5#include <cstdint>
6#include <map>
7#include <stdexcept>
8#include <tuple>
16#include "common/Diagnostic.h"
17#include "common/Exception.h"
18
19// MotionBuilder.cpp
20namespace eve::animation {
21namespace {
22
23[[nodiscard]] eve::Diagnostic consumedDiag(const char* api) {
25 std::string(api) + ": builder already consumed");
26}
27
28} // namespace
29
30MotionBuilder::MotionBuilder(MotionRuntime& runtime, float from, float to, float duration) : runtime_(runtime) {
31 desc_.from = from;
32 desc_.to = to;
33 desc_.duration = duration;
34}
35
37 desc_.ease = std::move(kind);
38 return *this;
39}
40
42 desc_.delay = seconds;
43 return *this;
44}
45
47 desc_.loops = count;
48 desc_.loopMode = mode;
49 return *this;
50}
51
53 desc_.onUpdate = std::move(cb);
54 return *this;
55}
56
58 desc_.onComplete = std::move(cb);
59 return *this;
60}
61
63 desc_.onCancel = std::move(cb);
64 return *this;
65}
66
71
73 desc_.sink = &sink;
74 return *this;
75}
76
78 if (consumed_) return eve::Result<MotionHandle>::failure(consumedDiag("MotionBuilder.run"));
79 consumed_ = true;
80 desc_.sink = nullptr;
81 return runtime_.spawnFloat(desc_);
82}
83
85 if (consumed_) return eve::Result<MotionHandle>::failure(consumedDiag("MotionBuilder.bind"));
86 consumed_ = true;
87 desc_.sink = &sink;
88 return runtime_.spawnFloat(desc_);
89}
90
92 if (consumed_) return eve::Result<MotionRuntime::FloatDesc>::failure(consumedDiag("MotionBuilder.takeDesc"));
93 consumed_ = true;
95}
96
98 : runtime_(runtime) {
99 desc_.from = from;
100 desc_.to = to;
101 desc_.duration = duration;
102}
103
105 desc_.ease = std::move(kind);
106 return *this;
107}
108
110 desc_.delay = seconds;
111 return *this;
112}
113
115 desc_.loops = count;
116 desc_.loopMode = mode;
117 return *this;
118}
119
121 desc_.onUpdate = std::move(cb);
122 return *this;
123}
124
126 desc_.onComplete = std::move(cb);
127 return *this;
128}
129
131 desc_.onCancel = std::move(cb);
132 return *this;
133}
134
139
141 desc_.sink = &sink;
142 return *this;
143}
144
146 if (consumed_) return eve::Result<MotionHandle>::failure(consumedDiag("MotionVec2Builder.run"));
147 consumed_ = true;
148 desc_.sink = nullptr;
149 return runtime_.spawnVec2(desc_);
150}
151
153 if (consumed_) return eve::Result<MotionHandle>::failure(consumedDiag("MotionVec2Builder.bind"));
154 consumed_ = true;
155 desc_.sink = &sink;
156 return runtime_.spawnVec2(desc_);
157}
158
160 if (consumed_) return eve::Result<MotionRuntime::Vec2Desc>::failure(consumedDiag("MotionVec2Builder.takeDesc"));
161 consumed_ = true;
162 return eve::Result<MotionRuntime::Vec2Desc>::success(std::move(desc_));
163}
164
166 : runtime_(runtime) {
167 desc_.from = from;
168 desc_.to = to;
169 desc_.duration = duration;
170}
171
173 desc_.ease = std::move(kind);
174 return *this;
175}
176
178 desc_.delay = seconds;
179 return *this;
180}
181
183 desc_.loops = count;
184 desc_.loopMode = mode;
185 return *this;
186}
187
189 desc_.onUpdate = std::move(cb);
190 return *this;
191}
192
194 desc_.onComplete = std::move(cb);
195 return *this;
196}
197
199 desc_.onCancel = std::move(cb);
200 return *this;
201}
202
207
209 desc_.sink = &sink;
210 return *this;
211}
212
214 if (consumed_) return eve::Result<MotionHandle>::failure(consumedDiag("MotionVec3Builder.run"));
215 consumed_ = true;
216 desc_.sink = nullptr;
217 return runtime_.spawnVec3(desc_);
218}
219
221 if (consumed_) return eve::Result<MotionHandle>::failure(consumedDiag("MotionVec3Builder.bind"));
222 consumed_ = true;
223 desc_.sink = &sink;
224 return runtime_.spawnVec3(desc_);
225}
226
228 if (consumed_) return eve::Result<MotionRuntime::Vec3Desc>::failure(consumedDiag("MotionVec3Builder.takeDesc"));
229 consumed_ = true;
230 return eve::Result<MotionRuntime::Vec3Desc>::success(std::move(desc_));
231}
232
233
235 desc_.style = style;
236 return *this;
237}
239 desc_.frequency = count;
240 return *this;
241}
243 desc_.dampingRatio = ratio;
244 return *this;
245}
247 desc_.seed = value;
248 return *this;
249}
250
252 desc_.style = style;
253 return *this;
254}
256 desc_.frequency = count;
257 return *this;
258}
260 desc_.dampingRatio = ratio;
261 return *this;
262}
264 desc_.seed = value;
265 return *this;
266}
267
269 desc_.style = style;
270 return *this;
271}
273 desc_.frequency = count;
274 return *this;
275}
277 desc_.dampingRatio = ratio;
278 return *this;
279}
281 desc_.seed = value;
282 return *this;
283}
284
286 : runtime_(runtime) {
287 desc_.from = from;
288 desc_.to = to;
289 desc_.duration = duration;
290}
292 desc_.ease = std::move(kind);
293 return *this;
294}
296 desc_.delay = seconds;
297 return *this;
298}
300 desc_.loops = count;
301 desc_.loopMode = mode;
302 return *this;
303}
305 desc_.onUpdate = std::move(cb);
306 return *this;
307}
309 desc_.onComplete = std::move(cb);
310 return *this;
311}
313 desc_.onCancel = std::move(cb);
314 return *this;
315}
321 desc_.sink = &sink;
322 return *this;
323}
325 if (consumed_) return eve::Result<MotionHandle>::failure(consumedDiag("MotionColorBuilder.run"));
326 consumed_ = true;
327 desc_.sink = nullptr;
328 return runtime_.spawnColor(desc_);
329}
331 if (consumed_) return eve::Result<MotionHandle>::failure(consumedDiag("MotionColorBuilder.bind"));
332 consumed_ = true;
333 desc_.sink = &sink;
334 return runtime_.spawnColor(desc_);
335}
337 if (consumed_) return eve::Result<MotionRuntime::ColorDesc>::failure(consumedDiag("MotionColorBuilder.takeDesc"));
338 consumed_ = true;
339 return eve::Result<MotionRuntime::ColorDesc>::success(std::move(desc_));
340}
341
343 : runtime_(runtime) {
344 desc_.from = from;
345 desc_.to = to;
346 desc_.duration = duration;
347}
349 desc_.ease = std::move(kind);
350 return *this;
351}
353 desc_.delay = seconds;
354 return *this;
355}
357 desc_.loops = count;
358 desc_.loopMode = mode;
359 return *this;
360}
362 desc_.onUpdate = std::move(cb);
363 return *this;
364}
366 desc_.onComplete = std::move(cb);
367 return *this;
368}
370 desc_.onCancel = std::move(cb);
371 return *this;
372}
378 desc_.sink = &sink;
379 return *this;
380}
382 if (consumed_) return eve::Result<MotionHandle>::failure(consumedDiag("MotionQuatBuilder.run"));
383 consumed_ = true;
384 desc_.sink = nullptr;
385 return runtime_.spawnQuat(desc_);
386}
388 if (consumed_) return eve::Result<MotionHandle>::failure(consumedDiag("MotionQuatBuilder.bind"));
389 consumed_ = true;
390 desc_.sink = &sink;
391 return runtime_.spawnQuat(desc_);
392}
394 if (consumed_) return eve::Result<MotionRuntime::QuatDesc>::failure(consumedDiag("MotionQuatBuilder.takeDesc"));
395 consumed_ = true;
396 return eve::Result<MotionRuntime::QuatDesc>::success(std::move(desc_));
397}
398
399} // namespace eve::animation
400
401// MotionDatabase.cpp
402namespace eve::animation {
403
404MotionDatabase::MotionDatabase(AnimSkeleton* skeleton) : skeleton_(skeleton) {
405 if (!skeleton_) throw Exception("MotionDatabase: skeleton is null");
406 scratchPose_.resize(skeleton_->getBoneCount());
407 // Default: use every non-root bone if none specified before bake.
408}
409
411 if (locomotionFeatures_ || schema_) throw Exception("MotionDatabase: configured layout owns its feature bones");
412 if (boneIndex < 0 || boneIndex >= skeleton_->getBoneCount()) {
413 throw Exception("MotionDatabase.addFeatureBone: invalid bone %d", boneIndex);
414 }
415 for (int b : featureBones_) {
416 if (b == boneIndex) return;
417 }
418 featureBones_.push_back(boneIndex);
419 baked_ = false;
420}
421
423 const int id = skeleton_->findBone(name);
424 if (id < 0) throw Exception("MotionDatabase.addFeatureBoneByName: unknown '%s'", name.c_str());
425 addFeatureBone(id);
426}
427
428void MotionDatabase::setRootBone(int boneIndex) {
429 if (schema_ && baked_) throw Exception("MotionDatabase: baked feature layout is immutable");
430 if (boneIndex < 0 || boneIndex >= skeleton_->getBoneCount()) {
431 throw Exception("MotionDatabase.setRootBone: invalid bone %d", boneIndex);
432 }
433 rootBone_ = boneIndex;
434 baked_ = false;
435}
436
437void MotionDatabase::setRootBoneByName(const std::string& name) {
438 const int id = skeleton_->findBone(name);
439 if (id < 0) throw Exception("MotionDatabase.setRootBoneByName: unknown '%s'", name.c_str());
440 setRootBone(id);
441}
442
444 if (schema_ && baked_) throw Exception("MotionDatabase: baked feature layout is immutable");
445 if (!clip) throw Exception("MotionDatabase.addClip: clip is null");
446 clips_.push_back(clip);
447 baked_ = false;
448}
449
450AnimClip* MotionDatabase::getClip(int clipIndex) const {
451 if (clipIndex < 0 || clipIndex >= getClipCount()) {
452 throw Exception("MotionDatabase.getClip: invalid index %d", clipIndex);
453 }
454 return clips_[static_cast<size_t>(clipIndex)];
455}
456
457void MotionDatabase::computeFeatureSize() {
458 // vel(2) + trajPos*3(6) + trajFacing(2) + bones*3
459 featureSize_ = schema_ ? schema_->dimension
460 : (locomotionFeatures_ ? 30 : 2 + 6 + 2 + static_cast<int>(featureBones_.size()) * 3);
461}
462
463float MotionDatabase::yawFromQuat(float /*x*/, float y, float /*z*/, float w) {
464 // Yaw from quaternion (Y-up), assuming mostly planar rotation.
465 return std::atan2(2.f * (w * y), 1.f - 2.f * (y * y));
466}
467
469 if (index < 0 || index >= getFeatureBoneCount()) {
470 throw Exception("MotionDatabase.getFeatureBone: invalid index %d", index);
471 }
472 return featureBones_[static_cast<size_t>(index)];
473}
474
475void MotionDatabase::extractFeature(AnimClip* clip, float time, float dtSample, std::vector<float>& out, float& rootX,
476 float& rootZ, float& rootYaw, float& velX, float& velZ) const {
477 if (schema_) {
478 extractSchemaFeature(clip, time, out, rootX, rootZ, rootYaw, velX, velZ);
479 return;
480 }
481 if (locomotionFeatures_) {
482 extractLocomotionFeature(clip, time, out, rootX, rootZ, rootYaw, velX, velZ);
483 return;
484 }
485 out.assign(static_cast<size_t>(featureSize_), 0.f);
486 // Trajectory horizons need only the root's ancestor chain; pose features
487 // need only their own chains. Sampling every unrelated finger/face bone at
488 // all six horizons makes full-corpus baking unnecessarily expensive.
489 auto worldBone = [&](auto&& self, int bone, float sampleTime) -> TransformTRS {
490 const auto local = clip->sampleBone(bone, sampleTime, skeleton_->bindLocal(bone));
491 const int parent = skeleton_->getParent(bone);
492 return parent < 0 ? local : detail::mulTRS(self(self, parent, sampleTime), local);
493 };
494 auto worldAt = [&](int bone, float sampleTime, bool wrap = true) {
495 const float t = clampf(wrap ? clip->wrapTime(sampleTime) : sampleTime, 0.f, clip->getDuration());
496 return worldBone(worldBone, bone, t);
497 };
498 const int root = rootBone_;
499 const auto current = worldAt(root, time);
500 rootX = current.px;
501 rootZ = current.pz;
502 rootYaw = yawFromQuat(current.qx, current.qy, current.qz, current.qw);
503
504 // Sampling a looping pose wraps its root back to the origin. Trajectories
505 // must instead accumulate the displacement of every completed cycle.
506 float cycleX = 0.f, cycleZ = 0.f;
507 const float duration = clip->getDuration();
508 if (clip->getLoop() && duration > 1e-8f) {
509 const auto start = worldAt(root, 0.f, false);
510 const auto end = worldAt(root, duration, false);
511 cycleX = end.px - start.px;
512 cycleZ = end.pz - start.pz;
513 }
514 auto cyclesAt = [&](float t) { return clip->getLoop() && duration > 1e-8f ? std::floor(t / duration) : 0.f; };
515
516 // Velocity from nearby sample.
517 const float t1 = time + std::max(dtSample, 1e-3f);
518 const auto next = worldAt(root, t1);
519 const float nX = next.px + cyclesAt(t1) * cycleX;
520 const float nZ = next.pz + cyclesAt(t1) * cycleZ;
521 const float dtt = std::max(dtSample, 1e-3f);
522 velX = (nX - rootX) / dtt;
523 velZ = (nZ - rootZ) / dtt;
524
525 float cs = std::cos(rootYaw);
526 float sn = std::sin(rootYaw);
527 // Character-space: rotate world xz by -yaw
528 auto toLocal = [&](float wx, float wz, float& lx, float& lz) {
529 const float dx = wx - rootX;
530 const float dz = wz - rootZ;
531 lx = dx * cs - dz * sn;
532 lz = dx * sn + dz * cs;
533 };
534
535 out[0] = velX * cs - velZ * sn;
536 out[1] = velX * sn + velZ * cs;
537
538 const float horizons[3] = {0.33f, 0.66f, 1.0f};
539 for (int h = 0; h < 3; ++h) {
540 const auto fut = worldAt(root, time + horizons[h]);
541 float lx, lz;
542 const float cycles = cyclesAt(time + horizons[h]);
543 toLocal(fut.px + cycles * cycleX, fut.pz + cycles * cycleZ, lx, lz);
544 out[2 + h * 2] = lx;
545 out[2 + h * 2 + 1] = lz;
546 }
547
548 {
549 const auto fut = worldAt(root, time + 1.0f);
550 const float fyaw = yawFromQuat(fut.qx, fut.qy, fut.qz, fut.qw);
551 float fx, fz;
552 yawToForward(fyaw - rootYaw, fx, fz);
553 out[8] = fx;
554 out[9] = fz;
555 }
556
557 int base = 10;
558 for (int bone : featureBones_) {
559 float lx, lz;
560 const auto feature = worldAt(bone, time);
561 const float wy = feature.py;
562 toLocal(feature.px, feature.pz, lx, lz);
563 out[static_cast<size_t>(base)] = lx;
564 out[static_cast<size_t>(base + 1)] = wy;
565 out[static_cast<size_t>(base + 2)] = lz;
566 base += 3;
567 }
568}
569
571 if (schema_)
572 for (const auto& channel : schema_->layout.channels) {
573 if (channel.kind != MotionFeatureKind::Curve) continue;
574 if (!schema_->curves) throw Exception("MotionDatabase: scalar curve data must be configured before bake");
575 for (const auto* clip : clips_)
576 if (!schema_->curveSources.contains(clip))
577 throw Exception("MotionDatabase: added clip has no scalar curve source");
578 }
579 if (clips_.empty()) throw Exception("MotionDatabase.bake: no clips");
580 if (featureBones_.empty() && !schema_) {
581 // Default: all bones except root.
582 for (int i = 1; i < skeleton_->getBoneCount(); ++i) addFeatureBone(i);
583 if (featureBones_.empty() && skeleton_->getBoneCount() > 0) addFeatureBone(0);
584 }
585 computeFeatureSize();
586 baked_ = false;
587 std::vector<std::vector<Frame>> clipFrames(clips_.size());
588
589 detail::parallelAnimationItems(clips_.size(), clips_.size() < 16 ? 1 : 0, [&](std::size_t index) {
590 const int ci = static_cast<int>(index);
591 auto& output = clipFrames[index];
592 AnimClip* clip = clips_[static_cast<size_t>(ci)];
593 const float rate = schema_ ? static_cast<float>(schema_->layout.sampleRate)
594 : (clip->getSampleRate() > 0.f ? clip->getSampleRate() : 30.f);
595 const float dt = 1.f / rate;
596 const float dur = clip->getDuration();
597 if (dur <= 0.f) {
598 Frame f;
599 f.clipIndex = ci;
600 f.time = 0.f;
601 extractFeature(clip, 0.f, dt, f.feature, f.rootX, f.rootZ, f.rootYaw, f.velX, f.velZ);
602 if (schema_) f.trajectorySpeed = schemaTrajectorySpeed(f.feature);
603 output.push_back(std::move(f));
604 return;
605 }
606 const int schemaLast = schema_ ? static_cast<int>(std::floor(dur * rate)) : 0;
607 float t = 0.f;
608 for (int sample = 0;; ++sample, t = schema_ ? sample / rate : t + dt) {
609 if (schema_ ? (sample > schemaLast || (clip->getLoop() && t >= dur - 1e-5f)) : t >= dur - 1e-5f) break;
610 Frame f;
611 f.clipIndex = ci;
612 f.time = t;
613 extractFeature(clip, t, dt, f.feature, f.rootX, f.rootZ, f.rootYaw, f.velX, f.velZ);
614 if (schema_) f.trajectorySpeed = schemaTrajectorySpeed(f.feature);
615 output.push_back(std::move(f));
616 }
617 });
618 // Preserve frame IDs and floating-point reduction order exactly.
619 std::size_t total = 0;
620 for (const auto& output : clipFrames) total += output.size();
621 frames_.clear();
622 frames_.reserve(total);
623 clipFrameOffsets_.clear();
624 clipFrameOffsets_.reserve(clipFrames.size() + 1);
625 for (auto& output : clipFrames) {
626 clipFrameOffsets_.push_back(static_cast<int>(frames_.size()));
627 for (auto& frame : output) frames_.push_back(std::move(frame));
628 }
629 clipFrameOffsets_.push_back(static_cast<int>(frames_.size()));
630 if (schema_) {
631 normalizeSchemaFeatures();
632 baked_ = true;
633 return;
634 }
635 if (locomotionFeatures_) {
636 normalizeLocomotionFeatures();
637 baked_ = true;
638 return;
639 }
640 featureMean_.assign(static_cast<size_t>(featureSize_), 0.f);
641 featureInvStd_.assign(static_cast<size_t>(featureSize_), 0.f);
642 for (const Frame& frame : frames_)
643 for (int i = 0; i < featureSize_; ++i)
644 featureMean_[static_cast<size_t>(i)] += frame.feature[static_cast<size_t>(i)];
645 const float invCount = 1.f / static_cast<float>(frames_.size());
646 for (float& mean : featureMean_) mean *= invCount;
647 for (const Frame& frame : frames_)
648 for (int i = 0; i < featureSize_; ++i) {
649 const float d = frame.feature[static_cast<size_t>(i)] - featureMean_[static_cast<size_t>(i)];
650 featureInvStd_[static_cast<size_t>(i)] += d * d;
651 }
652 for (float& invStd : featureInvStd_) invStd = 1.f / std::sqrt(invStd * invCount + 1e-6f);
653 for (Frame& frame : frames_) normalizeFeature(frame.feature);
654 baked_ = true;
655}
656
657void MotionDatabase::normalizeFeature(std::vector<float>& feature) const {
658 if (static_cast<int>(feature.size()) != featureSize_ || static_cast<int>(featureMean_.size()) != featureSize_)
659 return;
660 for (int i = 0; i < featureSize_; ++i)
661 feature[static_cast<size_t>(i)] = (feature[static_cast<size_t>(i)] - featureMean_[static_cast<size_t>(i)]) *
662 featureInvStd_[static_cast<size_t>(i)];
663}
664
665void MotionDatabase::requireBaked() const {
666 if (!baked_) throw Exception("MotionDatabase: not baked; call bake() first");
667}
668
670 requireBaked();
671 if (index < 0 || index >= getFrameCount()) {
672 throw Exception("MotionDatabase: invalid frame %d", index);
673 }
674 return frames_[static_cast<size_t>(index)];
675}
676
677float MotionDatabase::getFrameTime(int frameIndex) const { return frameAt(frameIndex).time; }
678
679int MotionDatabase::getFrameClipIndex(int frameIndex) const { return frameAt(frameIndex).clipIndex; }
680
681void MotionDatabase::getFeature(int frameIndex, float* out, int outCount) const {
682 const Frame& f = frameAt(frameIndex);
683 if (!out || outCount < featureSize_) {
684 throw Exception("MotionDatabase.getFeature: buffer too small");
685 }
686 for (int i = 0; i < featureSize_; ++i) out[i] = f.feature[static_cast<size_t>(i)];
687}
688
689} // namespace eve::animation
690
691// MotionDatabaseLocomotion.cpp
692namespace eve::animation {
693eve::Result<void> MotionDatabase::setLocomotionFeatures(int leftFoot, int rightFoot, int pelvis) {
694 const int count = skeleton_->getBoneCount();
695 if (baked_ || leftFoot < 0 || rightFoot < 0 || pelvis < 0 || leftFoot >= count || rightFoot >= count ||
696 pelvis >= count || leftFoot == rightFoot || leftFoot == pelvis || rightFoot == pelvis)
698 eve::DiagnosticCode::InvalidArgument, "locomotion features require three distinct valid bones before bake",
699 "featureBones", {}, "animation"));
700 std::vector<int> bones{leftFoot, rightFoot, pelvis};
701 schema_.reset();
702 featureBones_.swap(bones);
703 locomotionFeatures_ = true;
704 computeFeatureSize();
706}
707
708void MotionDatabase::extractLocomotionFeature(AnimClip* clip, float time, std::vector<float>& out, float& rootX,
709 float& rootZ, float& rootYaw, float& velX, float& velZ) const {
711 const float duration = clip->getDuration();
712 const float delta = 1.f / 60.f;
713 auto world = [&](auto&& self, int bone, float t) -> TransformTRS {
714 const auto local = clip->sampleBone(bone, t, skeleton_->bindLocal(bone));
715 const int parent = skeleton_->getParent(bone);
716 return parent < 0 ? local : detail::mulTRS(self(self, parent, t), local);
717 };
718 auto poseAt = [&](int bone, float t) { return world(world, bone, clampf(clip->wrapTime(t), 0.f, duration)); };
719 // Accumulate complete root transforms at loop seams; turning cycles need
720 // rotation composition, not repeated addition of an unrotated displacement.
721 const auto start = world(world, rootBone_, 0.f), end = world(world, rootBone_, duration);
722 const float startYaw = detail::featureYaw(start);
723 const float cycleYaw = std::remainder(detail::featureYaw(end) - startYaw, 6.28318530718f);
724 auto rootAt = [&](float t) {
725 auto root = poseAt(rootBone_, t);
726 if (clip->getLoop() && duration > 1e-6f) {
727 const int cycles = static_cast<int>(std::floor(t / duration));
728 float x = root.px - start.px, z = root.pz - start.pz;
729 const float dx = end.px - start.px, dz = end.pz - start.pz;
730 const float cs = std::cos(cycleYaw), sn = std::sin(cycleYaw);
731 for (int i = 0; i < std::abs(cycles); ++i) {
732 if (cycles > 0) {
733 const float nextX = cs * x + sn * z + dx;
734 z = -sn * x + cs * z + dz;
735 x = nextX;
736 } else {
737 x -= dx;
738 z -= dz;
739 const float nextX = cs * x - sn * z;
740 z = sn * x + cs * z;
741 x = nextX;
742 }
743 }
744 root.px = start.px + x;
745 root.pz = start.pz + z;
746 root.py += cycles * (end.py - start.py);
747 const float angle = detail::featureYaw(root) + cycles * cycleYaw;
748 root.qx = root.qz = 0.f;
749 root.qy = std::sin(angle * .5f);
750 root.qw = std::cos(angle * .5f);
751 } else if (duration > 1e-6f && (t < 0.f || t > duration)) {
752 // Root trajectory extrapolation preserves velocity outside short
753 // starts/stops, instead of inventing a stationary future endpoint.
754 const float dt = std::min(delta, duration);
755 const auto a = world(world, rootBone_, t < 0.f ? 0.f : duration - dt);
756 const auto b = world(world, rootBone_, t < 0.f ? dt : duration);
757 const float extension = (t < 0.f ? t : t - duration) / dt;
758 root.px += (b.px - a.px) * extension;
759 root.py += (b.py - a.py) * extension;
760 root.pz += (b.pz - a.pz) * extension;
761 const float angle =
763 std::remainder(detail::featureYaw(b) - detail::featureYaw(a), 6.28318530718f) * extension;
764 root.qx = root.qz = 0.f;
765 root.qy = std::sin(angle * .5f);
766 root.qw = std::cos(angle * .5f);
767 }
768 return root;
769 };
770 struct Sample {
771 float x, y, z, vx, vy, vz, yaw;
772 };
773 std::array<Sample, 5> samples{};
774 const auto current = rootAt(time);
775 rootX = current.px;
776 rootZ = current.pz;
777 rootYaw = detail::featureYaw(current);
778 for (int i = 0; i < 5; ++i) {
779 const float t = time + detail::locomotionHorizons[i];
780 const auto r = rootAt(t), previous = rootAt(t - delta);
781 samples[i] = {r.px - current.px,
782 r.py - current.py,
783 r.pz - current.pz,
784 (r.px - previous.px) / delta,
785 (r.py - previous.py) / delta,
786 (r.pz - previous.pz) / delta,
788 }
789 velX = samples[1].vx;
790 velZ = samples[1].vz;
791 detail::encodeLocomotionTrajectory(std::span(out), samples, rootYaw);
792 std::array<TransformTRS, 4> now{}, past{};
793 now[0] = poseAt(rootBone_, time);
794 past[0] = poseAt(rootBone_, time - delta);
795 for (int i = 0; i < 3; ++i) {
796 now[i + 1] = poseAt(featureBones_[i], time);
797 past[i + 1] = poseAt(featureBones_[i], time - delta);
798 }
799 detail::encodeLocomotionPose(out, now, past, delta);
800}
801
802void MotionDatabase::normalizeLocomotionFeatures() {
803 featureMean_.assign(detail::locomotionFeatureCount, 0.f);
804 featureInvStd_.assign(detail::locomotionFeatureCount, 1.f);
805 // Separate channels use vector mean deviation (isotropic XZ/XYZ); the two
806 // feet share a centroid and scale, as the authored FeetVelZ group specifies.
807 const std::array<std::array<int, 3>, 12> channels{{{0, 2, 1},
808 {2, 2, 1},
809 {4, 2, 1},
810 {6, 2, 1},
811 {8, 2, 1},
812 {10, 2, 1},
813 {12, 2, 1},
814 {14, 2, 1},
815 {16, 3, 1},
816 {19, 3, 1},
817 {22, 3, 2},
818 {28, 2, 1}}};
819 for (const auto& channel : channels) {
820 const int base = channel[0], dimensions = channel[1], copies = channel[2];
821 std::array<double, 3> mean{};
822 const double count = static_cast<double>(frames_.size()) * copies;
823 for (const auto& frame : frames_)
824 for (int copy = 0; copy < copies; ++copy)
825 for (int axis = 0; axis < dimensions; ++axis)
826 mean[axis] += frame.feature[base + copy * dimensions + axis];
827 for (double& value : mean) value /= count;
828 double deviation = 0;
829 for (const auto& frame : frames_)
830 for (int copy = 0; copy < copies; ++copy) {
831 double square = 0;
832 for (int axis = 0; axis < dimensions; ++axis) {
833 const double d = frame.feature[base + copy * dimensions + axis] - mean[axis];
834 square += d * d;
835 }
836 deviation += std::sqrt(square);
837 }
838 deviation /= count;
839 const bool unitVector = base == 4 || base == 8 || base == 14 || base == 16 || base == 28;
840 const double minimum = unitVector ? 0.1 : 0.001; // UE 0.1 cm, converted to metres.
841 const float inverse = static_cast<float>(deviation > minimum ? 1.0 / deviation : (unitVector ? 1.0 : 100.0));
842 for (int copy = 0; copy < copies; ++copy)
843 for (int axis = 0; axis < dimensions; ++axis) {
844 const int i = base + copy * dimensions + axis;
845 featureMean_[i] = static_cast<float>(mean[axis]);
846 featureInvStd_[i] = inverse;
847 }
848 }
849 for (auto& frame : frames_) normalizeFeature(frame.feature);
850}
851} // namespace eve::animation
852
853// MotionDatabaseSchema.cpp
854namespace eve::animation {
856bool MotionDatabase::hasFeatureLayout() const { return schema_ != nullptr; }
857
858float MotionDatabase::schemaTrajectorySpeed(std::span<const float> feature) const {
859 if (!schema_ || feature.size() != static_cast<std::size_t>(schema_->dimension)) return 0.f;
860 float total = 0.f;
861 for (std::size_t i = 0; i < schema_->layout.channels.size(); ++i) {
862 const auto& channel = schema_->layout.channels[i];
863 if (channel.source != MotionFeatureSource::Trajectory || channel.kind != MotionFeatureKind::Velocity ||
864 channel.normalizeVelocity)
865 continue;
866 const int count = std::popcount(static_cast<unsigned>(channel.axes));
867 float squared = 0.f;
868 for (int component = 0; component < count; ++component) {
869 const float value = feature[schema_->offsets[i] + static_cast<std::size_t>(component)];
870 squared += value * value;
871 }
872 total += std::sqrt(squared);
873 }
874 return total;
875}
876
878 auto fail = [](const char* message) {
880 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, message, "featureLayout", {}, "animation"));
881 };
882 if (baked_ || layout.sampleRate < 1 || layout.sampleRate > 240 || layout.channels.empty() ||
883 layout.channels.size() > 256 || !std::isfinite(layout.normalizationLengthScale) ||
884 layout.normalizationLengthScale <= 0.f || layout.normalizationLengthScale > 1000000.f)
885 return fail("feature layout requires an unbaked database, 1..240 Hz and 1..256 channels");
886 auto next = std::make_unique<detail::MotionSchemaState>();
887 next->layout = layout;
888 double totalWeight = 0;
889 for (const auto& c : layout.channels) {
891 c.query > MotionFeatureQuery::Continuing || c.axes == 0 || c.axes > 7 || c.headingAxis < 0 ||
892 c.headingAxis > 2 || !std::isfinite(c.weight) || c.weight < 0.f || c.weight > 1000000.f ||
893 !std::isfinite(c.sampleTime) || std::abs(c.sampleTime) > 10.f || c.normalizationGroup.size() > 4096)
894 return fail("invalid feature channel operation, axes, weight, time or normalization group");
895 if (c.kind == MotionFeatureKind::Curve &&
896 (c.source != MotionFeatureSource::Pose || c.axes != 1 || c.curve.empty() || c.curve.size() > 4096 ||
897 c.curve.find('\0') != std::string::npos))
898 return fail("curve channels require a named scalar pose source");
899 if (c.kind != MotionFeatureKind::Curve && !c.curve.empty())
900 return fail("vector channels cannot specify a scalar curve");
901 if (c.kind != MotionFeatureKind::Curve && c.source == MotionFeatureSource::Pose &&
902 (c.sampleTime != 0.f || c.bone < 0 || c.origin < 0 || c.bone >= skeleton_->getBoneCount() ||
903 c.origin >= skeleton_->getBoneCount()))
904 return fail("pose channels require valid bones and zero sample offset");
905 if (c.source == MotionFeatureSource::Trajectory &&
907 (c.kind == MotionFeatureKind::Velocity && c.characterSpaceVelocity)))
908 return fail("trajectory channels require character queries and world-space velocity");
909 const int count = std::popcount(static_cast<unsigned>(c.axes));
910 if (c.normalizeVelocity && c.kind != MotionFeatureKind::Velocity)
911 return fail("velocity normalization requires a velocity channel");
912 next->offsets.push_back(next->dimension);
913 next->dimension += count;
914 totalWeight += c.weight * count;
915 const int group = c.source == MotionFeatureSource::Pose ? 0 : (c.kind == MotionFeatureKind::Velocity ? 1 : 2);
916 next->weightSums[group] += c.weight * count;
917 for (int i = 0; i < count; ++i) {
918 next->weights.push_back(c.weight);
919 next->sources.push_back(c.source);
920 next->kinds.push_back(c.kind);
921 next->queries.push_back(c.query);
922 }
923 }
924 if (next->dimension > 1024 || totalWeight <= 0 || !std::isfinite(totalWeight))
925 return fail("feature layout requires bounded dimensions and positive finite total weight");
926 schema_ = std::move(next);
927 locomotionFeatures_ = false;
928 featureBones_.clear();
929 computeFeatureSize();
931}
932
934 std::span<const std::string> sources) {
935 auto fail = [](const char* message) {
937 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, message, "featureCurves", {}, "animation"));
938 };
939 if (!schema_ || baked_ || clips_.empty() || sources.size() != clips_.size())
940 return fail("feature curves require a configured unbaked database and one source per clip");
941 auto library = std::make_unique<AnimCurveLibrary>();
942 auto loaded = library->load(bytes);
943 if (!loaded.ok()) return fail("invalid feature curve binary");
944 std::map<const AnimClip*, std::string> names;
945 for (std::size_t i = 0; i < sources.size(); ++i) {
946 if (!library->contains(sources[i])) return fail("feature curve source is missing");
947 auto [it, inserted] = names.emplace(clips_[i], sources[i]);
948 if (!inserted && it->second != sources[i]) return fail("one clip cannot have conflicting curve sources");
949 }
950 schema_->curves = std::move(library);
951 schema_->curveSources = std::move(names);
953}
954
955eve::Result<int> MotionDatabase::setFeatureNormalizationRanges(std::span<const MotionNormalizationRange> ranges) {
956 auto fail = [](const char* message) {
958 "featureNormalizationRanges", {}, "animation"));
959 };
960 if (!schema_ || baked_ || clips_.empty() || ranges.empty() || ranges.size() > 100000)
961 return fail(
962 "normalization ranges require a configured unbaked variable layout, clips and bounded nonempty input");
963 std::uint64_t sampleCount = 0;
964 const float rate = static_cast<float>(schema_->layout.sampleRate);
965 for (const auto& range : ranges) {
966 if (range.clipIndex < 0 || range.clipIndex >= static_cast<int>(clips_.size()) || !std::isfinite(range.start) ||
967 !std::isfinite(range.end) || range.start < 0.f || range.end < range.start ||
968 range.end > clips_[range.clipIndex]->getDuration() + .001f)
969 return fail("invalid normalization clip or time interval");
970 const auto* clip = clips_[range.clipIndex];
971 int last = static_cast<int>(std::floor(clip->getDuration() * rate));
972 if (clip->getLoop() && static_cast<float>(last) / rate >= clip->getDuration() - 1e-5f) --last;
973 const int first = std::max(0, static_cast<int>(std::ceil((range.start - 1e-5f) * rate)));
974 const int end = std::min(last, static_cast<int>(std::floor((range.end + 1e-5f) * rate)));
975 if (first > end) return fail("normalization interval contains no layout-rate sample");
976 sampleCount += static_cast<std::uint64_t>(end - first + 1);
977 if (sampleCount > 100000000) return fail("normalization sample count exceeds the configured bound");
978 }
979 normalizationRanges_.assign(ranges.begin(), ranges.end());
980 return eve::Result<int>::success(static_cast<int>(sampleCount), eve::Status::success(eve::StatusCode::Applied));
981}
982
983namespace {
984TransformTRS inverseRigid(TransformTRS value) {
985 value.qx = -value.qx;
986 value.qy = -value.qy;
987 value.qz = -value.qz;
988 const auto p = detail::schemaRotate({-value.px, -value.py, -value.pz}, value);
989 value.px = p[0];
990 value.py = p[1];
991 value.pz = p[2];
992 value.sx = value.sy = value.sz = 1.f;
993 return value;
994}
995TransformTRS rigidPower(TransformTRS delta, float count) {
996 if (count < 0.f) {
997 delta = inverseRigid(delta);
998 count = -count;
999 }
1000 auto whole = static_cast<unsigned>(std::floor(count));
1001 const float fraction = count - whole;
1002 TransformTRS result, power = delta;
1003 while (whole) {
1004 if (whole & 1) result = detail::mulTRS(result, power);
1006 whole >>= 1;
1007 }
1008 TransformTRS partial;
1009 partial.px = delta.px * fraction;
1010 partial.py = delta.py * fraction;
1011 partial.pz = delta.pz * fraction;
1012 slerpQuat(0.f, 0.f, 0.f, 1.f, delta.qx, delta.qy, delta.qz, delta.qw, fraction, partial.qx, partial.qy, partial.qz,
1013 partial.qw);
1014 return detail::mulTRS(result, partial);
1015}
1016} // namespace
1021 TransformTRS raw(int bone, float time) const {
1022 const auto local = clip.sampleBone(bone, time, skeleton.bindLocal(bone));
1023 const int parent = skeleton.getParent(bone);
1024 return parent < 0 ? local : detail::mulTRS(raw(parent, time), local);
1025 }
1026 TransformTRS root(float time) const {
1027 const float duration = clip.getDuration();
1028 if (duration <= 0.f) return raw(rootBone, 0.f);
1029 if (clip.getLoop()) {
1030 const float cycles = std::floor(time / duration);
1031 const auto start = raw(rootBone, 0.f), end = raw(rootBone, duration);
1032 const auto delta = detail::mulTRS(inverseRigid(start), end);
1033 const auto local = detail::mulTRS(inverseRigid(start), raw(rootBone, clip.wrapTime(time)));
1034 return detail::mulTRS(detail::mulTRS(start, rigidPower(delta, cycles)), local);
1035 }
1036 if (time >= 0.f && time <= duration) return raw(rootBone, time);
1037 const float step = std::min(1.f / 30.f, duration);
1038 const auto a = raw(rootBone, time < 0.f ? 0.f : duration - step);
1039 const auto b = raw(rootBone, time < 0.f ? step : duration);
1040 const auto delta = detail::mulTRS(inverseRigid(a), b);
1041 return detail::mulTRS(time < 0.f ? a : b, rigidPower(delta, (time < 0.f ? time : time - duration) / step));
1042 }
1043 TransformTRS bone(int index, float time) const {
1044 const float sample = clip.getLoop() ? clip.wrapTime(time) : clampf(time, 0.f, clip.getDuration());
1045 return detail::mulTRS(root(time), detail::mulTRS(inverseRigid(raw(rootBone, sample)), raw(index, sample)));
1046 }
1047};
1048
1049void MotionDatabase::extractSchemaFeature(AnimClip* clip, float time, std::vector<float>& out, float& rootX,
1050 float& rootZ, float& rootYaw, float& velX, float& velZ) const {
1051 constexpr float dt = 1.f / 60.f;
1052 const SchemaSampler sampler{*skeleton_, *clip, rootBone_};
1053 const auto root = sampler.root(time), previousRoot = sampler.root(time - dt);
1054 rootX = root.px;
1055 rootZ = root.pz;
1056 rootYaw =
1057 std::atan2(2.f * (root.qw * root.qy + root.qx * root.qz), 1.f - 2.f * (root.qx * root.qx + root.qy * root.qy));
1058 velX = (root.px - previousRoot.px) / dt;
1059 velZ = (root.pz - previousRoot.pz) / dt;
1060 out.assign(schema_->dimension, 0.f);
1061 for (std::size_t i = 0; i < schema_->layout.channels.size(); ++i) {
1062 const auto& c = schema_->layout.channels[i];
1063 std::array<float, 3> value{};
1064 if (c.kind == MotionFeatureKind::Curve) {
1065 auto sampled =
1066 schema_->curves->sample(schema_->curveSources.at(clip), c.curve, time + c.sampleTime, clip->getLoop());
1067 if (!sampled.ok()) throw std::runtime_error("configured motion curve cannot be sampled");
1068 value[0] = sampled.value().value_or(0.f);
1069 } else if (c.source == MotionFeatureSource::Trajectory) {
1070 const auto sample = sampler.root(time + c.sampleTime);
1071 if (c.kind == MotionFeatureKind::Position)
1073 else if (c.kind == MotionFeatureKind::Heading)
1074 value = detail::schemaHeading(sample, root, c.headingAxis);
1075 else {
1076 value = detail::schemaDifference(sample, sampler.root(time + c.sampleTime - dt), root);
1077 for (float& v : value) v /= dt;
1078 }
1079 } else {
1080 const auto bone = sampler.bone(c.bone, time), origin = sampler.bone(c.origin, time);
1081 if (c.kind == MotionFeatureKind::Position)
1083 else if (c.kind == MotionFeatureKind::Heading)
1084 value = detail::schemaHeading(bone, root, c.headingAxis);
1085 else if (c.characterSpaceVelocity) {
1087 const auto past = detail::schemaDifference(sampler.bone(c.bone, time - dt),
1088 sampler.bone(c.origin, time - dt), previousRoot);
1089 for (int axis = 0; axis < 3; ++axis) value[axis] = (value[axis] - past[axis]) / dt;
1090 } else {
1092 for (float& v : value) v /= dt;
1093 }
1094 }
1095 detail::schemaEncode(std::span(out).subspan(schema_->offsets[i]), c, value,
1096 schema_->layout.normalizationLengthScale);
1097 }
1098}
1099
1100void MotionDatabase::normalizeSchemaFeatures() {
1101 featureMean_.assign(schema_->dimension, 0.f);
1102 featureInvStd_.assign(schema_->dimension, 1.f);
1103 using Key = std::tuple<MotionFeatureKind, int, std::string, int>;
1104 std::map<Key, std::vector<int>> groups;
1105 for (std::size_t i = 0; i < schema_->layout.channels.size(); ++i) {
1106 const auto& c = schema_->layout.channels[i];
1107 groups[{c.kind, std::popcount(static_cast<unsigned>(c.axes)), c.normalizationGroup,
1108 c.normalizationGroup.empty() ? static_cast<int>(i) : -1}]
1109 .push_back(static_cast<int>(i));
1110 }
1111 std::vector<const Frame*> samples;
1112 if (normalizationRanges_.empty()) {
1113 samples.reserve(frames_.size());
1114 for (const auto& frame : frames_) samples.push_back(&frame);
1115 } else {
1116 std::vector<std::vector<const Frame*>> perClip(clips_.size());
1117 for (const auto& frame : frames_) perClip[frame.clipIndex].push_back(&frame);
1118 for (const auto& range : normalizationRanges_)
1119 for (const auto* frame : perClip[range.clipIndex])
1120 if (frame->time + 1e-5f >= range.start && frame->time - 1e-5f <= range.end) samples.push_back(frame);
1121 }
1122 if (samples.empty()) throw Exception("MotionDatabase: normalization ranges contain no baked samples");
1123 for (const auto& [key, channels] : groups) {
1124 const int count = std::get<1>(key);
1125 const double size = static_cast<double>(samples.size()) * channels.size();
1126 std::array<double, 3> mean{};
1127 for (const auto* frame : samples)
1128 for (int channel : channels)
1129 for (int axis = 0; axis < count; ++axis) mean[axis] += frame->feature[schema_->offsets[channel] + axis];
1130 for (double& v : mean) v /= size;
1131 double deviation = 0;
1132 for (const auto* frame : samples)
1133 for (int channel : channels) {
1134 double square = 0;
1135 for (int axis = 0; axis < count; ++axis) {
1136 const double delta = frame->feature[schema_->offsets[channel] + axis] - mean[axis];
1137 square += delta * delta;
1138 }
1139 deviation += std::sqrt(square);
1140 }
1141 deviation /= size;
1142 const auto& first = schema_->layout.channels[channels[0]];
1143 const bool unit = first.kind == MotionFeatureKind::Heading || first.kind == MotionFeatureKind::Curve ||
1144 first.normalizeVelocity;
1145 const float scale = schema_->layout.normalizationLengthScale;
1146 const float inverse =
1147 static_cast<float>(deviation > (unit ? .1 : .001 * scale) ? 1.0 / deviation : (unit ? 1.0 : 100.0 / scale));
1148 for (int channel : channels)
1149 for (int axis = 0; axis < count; ++axis) {
1150 featureMean_[schema_->offsets[channel] + axis] = static_cast<float>(mean[axis]);
1151 featureInvStd_[schema_->offsets[channel] + axis] = inverse;
1152 }
1153 }
1154 for (auto& frame : frames_) normalizeFeature(frame.feature);
1155}
1156} // namespace eve::animation
double z
double y
double x
Duration start
float w
Definition AnimClip.cpp:738
float duration
std::map< std::string, std::vector< Key >, std::less<> > channels
int root
Definition AnimSmr.cpp:119
std::string output
float yaw
Definition BushMesh.cpp:37
glm::vec4 p[6]
Stable, structured diagnostics shared by engine modules.
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
double raw
std::string layout
std::string message
float minimum[3]
vk::UniqueSampler sampler
glm::vec4 clip
double r
float v
std::int32_t c
std::int32_t first
int h
float ratio
JointPoint2D axis
const ColourScope * parent
std::string local
Range range
std::vector< Bone > bones
std::array< float, 3 > scale
std::uint32_t bone
std::string to
std::string from
Poco::JSON::Object::Ptr result
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
Fluent LitMotion-style builder that commits into MotionRuntime.
glm::dvec3 origin
ssq::Object frame
glm::dvec3 dx
glm::dvec3 dz
double dt
std::vector< std::pair< std::uint64_t, OceanBoatReceipt > > sources
std::shared_ptr< const OceanSprayFrame > previous
uint32_t groups
Definition OnnxGpgpu.cpp:39
float f
std::unordered_set< std::string > loaded
Definition Plugins.cpp:24
Object::Ptr value
float d
float t
float power
Definition RockMesh.cpp:23
ScriptStructure out
size_t end
std::string kind
double current
int count
AbilityActivationGroup group
TacticalUnit * unit
float step
Definition TreeMesh.cpp:451
float size
Definition TreeMesh.cpp:158
uint32_t index
float fraction
A structured explanation of a failed, degraded, or noteworthy result.
Definition Diagnostic.h:94
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
Keyframed skeletal animation clip (local TRS tracks per bone). Script type: AnimClip.
Definition AnimClip.h:145
float getDuration() const
Returns the duration.
Definition AnimClip.h:163
bool getLoop() const
Returns the loop.
Definition AnimClip.h:168
float wrapTime(float time) const
Wrap or clamp time according to loop flag.
Definition AnimClip.cpp:471
void resize(int boneCount)
Resize.
Definition AnimPose.cpp:82
3D bone hierarchy + bind-pose local TRS for skeletal animation. Independent of ik::Skeleton3D (FABRIK...
int getBoneCount() const
Returns the bone count.
int getParent(int boneIndex) const
Returns the parent.
const TransformTRS & bindLocal(int boneIndex) const
Binds local.
int findBone(const std::string &name) const
Finds bone.
Push target for a MotionColor motion.
Push target for a float motion. Lifetime is borrowed by MotionRuntime.
Definition MotionTypes.h:84
Push target for a MotionQuat motion.
Push target for a MotionVec2 motion.
Definition MotionTypes.h:96
Push target for a MotionVec3 motion.
Configure then bind/run a float motion into a MotionRuntime.
MotionBuilder & onUpdate(MotionRuntime::FloatCallback cb)
On update.
eve::Result< MotionRuntime::FloatDesc > takeDesc()
Extract the configured desc for sequence scheduling (consumes builder).
eve::Result< MotionHandle > run()
Start without a sink; read values via MotionRuntime::floatValue.
MotionBuilder & onComplete(MotionRuntime::VoidCallback cb)
On complete.
eve::Result< MotionHandle > bind(IMotionFloatSink &sink)
Start and push each sample into sink (borrowed).
MotionBuilder & ease(std::string kind)
Ease.
MotionBuilder & to(IMotionFloatSink &sink)
Attach a sink without spawning (for MotionSequence).
MotionBuilder & style(MotionStyle style)
Select Tween / Punch / Shake evaluation.
MotionBuilder & dampingRatio(float ratio)
Damping ratio for Punch/Shake (0 = none, 1 = full).
MotionBuilder & cancelOnError(bool enabled)
Cancel on error.
MotionBuilder & frequency(int count)
Oscillation count for Punch/Shake (default 10).
MotionBuilder & onCancel(MotionRuntime::VoidCallback cb)
On cancel.
MotionBuilder & loops(int count, MotionLoopMode mode=MotionLoopMode::Restart)
Loops.
MotionBuilder(MotionRuntime &runtime, float from, float to, float duration)
Motion builder.
MotionBuilder & seed(std::uint32_t value)
Deterministic seed for Shake signs.
MotionBuilder & delay(float seconds)
Delay.
Color fluent builder (Tween / lerp only).
MotionColorBuilder(MotionRuntime &runtime, MotionColor from, MotionColor to, float duration)
Motion color builder.
MotionColorBuilder & delay(float seconds)
Delay.
eve::Result< MotionHandle > run()
Run.
eve::Result< MotionRuntime::ColorDesc > takeDesc()
Take desc.
MotionColorBuilder & onComplete(MotionRuntime::VoidCallback cb)
On complete.
MotionColorBuilder & cancelOnError(bool enabled)
Cancel on error.
MotionColorBuilder & onUpdate(MotionRuntime::ColorCallback cb)
On update.
MotionColorBuilder & to(IMotionColorSink &sink)
To.
MotionColorBuilder & loops(int count, MotionLoopMode mode=MotionLoopMode::Restart)
Loops.
MotionColorBuilder & ease(std::string kind)
Ease.
eve::Result< MotionHandle > bind(IMotionColorSink &sink)
Binds .
MotionColorBuilder & onCancel(MotionRuntime::VoidCallback cb)
On cancel.
void setRootBoneByName(const std::string &name)
Sets the root bone by name.
eve::Result< int > setFeatureNormalizationRanges(std::span< const MotionNormalizationRange > ranges)
Atomically select weighted source ranges used to normalize a variable feature layout.
void normalizeFeature(std::vector< float > &feature) const
Normalize a query with statistics computed by bake().
void getFeature(int frameIndex, float *out, int outCount) const
Copy feature vector into out[0..featureSize).
bool hasFeatureLayout() const
Whether this database uses an explicitly configured variable layout.
void addFeatureBone(int boneIndex)
Include bone world position in pose features (by index).
float getFrameTime(int frameIndex) const
Returns the frame time.
int getFeatureBoneCount() const
Returns the feature bone count.
AnimClip * getClip(int clipIndex) const
Returns the clip.
const Frame & frameAt(int index) const
eve::Result< void > setFeatureLayout(const MotionFeatureLayout &layout)
Atomically configure an owning variable feature layout before bake.
void addFeatureBoneByName(const std::string &name)
Adds feature bone by name.
void bake()
Bake all clips into searchable frames. Call after addClip / feature bones.
int getFeatureBone(int index) const
Returns the feature bone.
eve::Result< void > setFeatureCurves(std::span< const std::byte > bytes, std::span< const std::string > sources)
Atomically copy scalar source curves for the configured layout.
eve::Result< void > setLocomotionFeatures(int leftFoot, int rightFoot, int pelvis)
Configure the locomotion layout before baking or creating matchers.
int getFrameCount() const
Returns the frame count.
void setRootBone(int boneIndex)
Bone used for trajectory / velocity features (default 0). Mixamo clips typically want hips (mixamorig...
void addClip(AnimClip *clip)
Adds clip.
MotionDatabase(AnimSkeleton *skeleton)
Motion database.
~MotionDatabase()
Motion database.
int getFrameClipIndex(int frameIndex) const
Returns the frame clip index.
int getClipCount() const
Returns the clip count.
Quaternion fluent builder (Tween / slerp only).
MotionQuatBuilder & ease(std::string kind)
Ease.
eve::Result< MotionRuntime::QuatDesc > takeDesc()
Take desc.
MotionQuatBuilder & onComplete(MotionRuntime::VoidCallback cb)
On complete.
MotionQuatBuilder & onUpdate(MotionRuntime::QuatCallback cb)
On update.
MotionQuatBuilder & to(IMotionQuatSink &sink)
To.
MotionQuatBuilder & loops(int count, MotionLoopMode mode=MotionLoopMode::Restart)
Loops.
eve::Result< MotionHandle > bind(IMotionQuatSink &sink)
Binds .
MotionQuatBuilder & onCancel(MotionRuntime::VoidCallback cb)
On cancel.
MotionQuatBuilder(MotionRuntime &runtime, MotionQuat from, MotionQuat to, float duration)
Motion quat builder.
MotionQuatBuilder & cancelOnError(bool enabled)
Cancel on error.
MotionQuatBuilder & delay(float seconds)
Delay.
eve::Result< MotionHandle > run()
Run.
Owns typed motion slots and applies SimulationStep updates.
std::function< void(MotionColor)> ColorCallback
std::function< void(float)> FloatCallback
eve::Result< MotionHandle > spawnColor(const ColorDesc &desc)
eve::Result< MotionHandle > spawnFloat(const FloatDesc &desc)
std::function< void(MotionQuat)> QuatCallback
eve::Result< MotionHandle > spawnVec2(const Vec2Desc &desc)
std::function< void()> VoidCallback
std::function< void(MotionVec2)> Vec2Callback
eve::Result< MotionHandle > spawnVec3(const Vec3Desc &desc)
eve::Result< MotionHandle > spawnQuat(const QuatDesc &desc)
std::function< void(MotionVec3)> Vec3Callback
MotionVec2Builder & onCancel(MotionRuntime::VoidCallback cb)
On cancel.
MotionVec2Builder & cancelOnError(bool enabled)
Cancel on error.
MotionVec2Builder & seed(std::uint32_t value)
Deterministic seed for Shake signs.
MotionVec2Builder & to(IMotionVec2Sink &sink)
To.
eve::Result< MotionHandle > run()
Run.
eve::Result< MotionHandle > bind(IMotionVec2Sink &sink)
Binds .
MotionVec2Builder & style(MotionStyle style)
Select Tween / Punch / Shake evaluation.
MotionVec2Builder & frequency(int count)
Oscillation count for Punch/Shake (default 10).
MotionVec2Builder & delay(float seconds)
Delay.
MotionVec2Builder & ease(std::string kind)
Ease.
MotionVec2Builder & onComplete(MotionRuntime::VoidCallback cb)
On complete.
MotionVec2Builder & dampingRatio(float ratio)
Damping ratio for Punch/Shake (0 = none, 1 = full).
MotionVec2Builder(MotionRuntime &runtime, MotionVec2 from, MotionVec2 to, float duration)
Motion vec 2 builder.
MotionVec2Builder & onUpdate(MotionRuntime::Vec2Callback cb)
On update.
eve::Result< MotionRuntime::Vec2Desc > takeDesc()
Take desc.
MotionVec2Builder & loops(int count, MotionLoopMode mode=MotionLoopMode::Restart)
Loops.
MotionVec3Builder & to(IMotionVec3Sink &sink)
To.
MotionVec3Builder & seed(std::uint32_t value)
Deterministic seed for Shake signs.
MotionVec3Builder(MotionRuntime &runtime, MotionVec3 from, MotionVec3 to, float duration)
Constructs a MotionVec3Builder.
eve::Result< MotionHandle > bind(IMotionVec3Sink &sink)
Binds .
MotionVec3Builder & onUpdate(MotionRuntime::Vec3Callback cb)
On update.
MotionVec3Builder & style(MotionStyle style)
Select Tween / Punch / Shake evaluation.
MotionVec3Builder & onCancel(MotionRuntime::VoidCallback cb)
On cancel.
eve::Result< MotionRuntime::Vec3Desc > takeDesc()
Take desc.
MotionVec3Builder & delay(float seconds)
Delay.
MotionVec3Builder & cancelOnError(bool enabled)
Cancel on error.
MotionVec3Builder & ease(std::string kind)
Ease.
eve::Result< MotionHandle > run()
Run.
MotionVec3Builder & frequency(int count)
Oscillation count for Punch/Shake (default 10).
MotionVec3Builder & onComplete(MotionRuntime::VoidCallback cb)
On complete.
MotionVec3Builder & dampingRatio(float ratio)
Damping ratio for Punch/Shake (0 = none, 1 = full).
MotionVec3Builder & loops(int count, MotionLoopMode mode=MotionLoopMode::Restart)
Loops.
constexpr std::array< float, 5 > locomotionHorizons
std::array< float, 3 > schemaDifference(const TransformTRS &a, const TransformTRS &b, const TransformTRS &root)
TransformTRS mulTRS(const TransformTRS &parent, const TransformTRS &local)
Mul trs.
std::array< float, 3 > schemaHeading(const TransformTRS &bone, const TransformTRS &root, int axis)
void encodeLocomotionPose(std::span< float > out, const std::array< TransformTRS, 4 > &now, const std::array< TransformTRS, 4 > &past, float interval)
Encode locomotion pose.
float featureYaw(const TransformTRS &t)
Feature yaw.
std::array< float, 3 > schemaRotate(const std::array< float, 3 > &p, const TransformTRS &q, bool inverse=false)
int parallelAnimationItems(std::size_t count, int requested, Body &&body)
Parallel animation items.
void schemaEncode(std::span< float > output, const MotionFeatureChannel &channel, std::array< float, 3 > value, float lengthScale)
Schema encode.
void encodeLocomotionTrajectory(std::span< float > out, const std::array< Sample, 5 > &samples, float yaw)
Encode locomotion trajectory.
void slerpQuat(float ax, float ay, float az, float aw, float bx, float by, float bz, float bw, float t, float &ox, float &oy, float &oz, float &ow)
Slerp quat.
Definition AnimMath.h:43
void yawToForward(float yaw, float &fx, float &fz)
Rotate unit +Z by yaw (radians) around Y — used for planar facing.
Definition AnimMath.h:144
MotionLoopMode
Loop behaviour after a cycle completes.
Definition MotionTypes.h:68
constexpr float clampf(float v, float lo, float hi) noexcept
Clampf.
Definition AnimMath.h:34
MotionStyle
Evaluation style for a motion slot.
Definition MotionTypes.h:77
std::string extension(std::string_view name)
Extension.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
double sample(const Heightmap &map, double u, double v)
Sample.
bool enabled
Compact RGBA color used by motion adapters.
Definition MotionTypes.h:52
TransformTRS bone(int index, float time) const
TransformTRS raw(int bone, float time) const
Owning ordered feature layout; copied atomically by a database.
Compact quaternion used by motion adapters (xyzw).
Definition MotionTypes.h:60
int loops
1 = once, N = N cycles, -1 = infinite.
std::uint32_t seed
Deterministic Shake seed.
int frequency
Oscillation count for Punch/Shake.
float dampingRatio
0 = undamped, 1 = fully damped.
std::uint32_t seed
Deterministic Shake seed.
float dampingRatio
0 = undamped, 1 = fully damped.
int frequency
Oscillation count for Punch/Shake.
float dampingRatio
0 = undamped, 1 = fully damped.
int frequency
Oscillation count for Punch/Shake.
std::uint32_t seed
Deterministic Shake seed.
Compact float2 used by motion adapters (avoids graphics math deps).
Definition MotionTypes.h:39
Compact float3 used by motion adapters.
Definition MotionTypes.h:45
Local TRS used by skeletal animation (quaternion xyzw).
Definition AnimMath.h:9