载入中...
搜索中...
未找到
MotionMatcher.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <limits>
12#include "common/Exception.h"
13
14// MotionMatcher.cpp
15namespace eve::animation {
16
18 : skeleton_(skeleton), database_(database) {
19 if (!skeleton_) throw Exception("MotionMatcher: skeleton is null");
20 if (!database_) throw Exception("MotionMatcher: database is null");
21 if (database_->getSkeleton() != skeleton_) {
22 throw Exception("MotionMatcher: database skeleton mismatch");
23 }
24 pose_.resize(skeleton_->getBoneCount());
25 inertia_ = std::make_unique<detail::PoseInertia>();
26 matchedPose_.resize(skeleton_->getBoneCount());
27 skeleton_->applyBindPose(&pose_);
28}
29
31
33 desiredVelX_ = x;
34 desiredVelZ_ = z;
35}
36
37void MotionMatcher::setDesiredYaw(float yaw) { desiredYaw_ = yaw; }
38
40 if (seconds < 0.f) throw Exception("MotionMatcher.setSearchInterval: must be >= 0");
41 searchInterval_ = seconds;
42}
43
44void MotionMatcher::setBlendTime(float seconds) {
45 if (seconds < 0.f) throw Exception("MotionMatcher.setBlendTime: must be >= 0");
46 blendTime_ = seconds;
47}
48
50 if (w < 0.f) throw Exception("MotionMatcher.setTrajectoryWeight: must be >= 0");
51 trajWeight_ = w;
52}
53
55 if (w < 0.f) throw Exception("MotionMatcher.setPoseWeight: must be >= 0");
56 poseWeight_ = w;
57}
58
60 if (w < 0.f) throw Exception("MotionMatcher.setVelocityWeight: must be >= 0");
61 velWeight_ = w;
62}
63
65 if (frames < 0) throw Exception("MotionMatcher.setIgnoreRadius: must be >= 0");
66 ignoreRadius_ = frames;
67}
68
70 if (!std::isfinite(minimum) || !std::isfinite(maximum) || minimum <= 0.f || maximum < minimum || maximum > 10.f)
72 eve::DiagnosticCode::InvalidArgument, "play rate range requires finite 0 < minimum <= maximum <= 10",
73 "playRateRange", {}, "animation"));
74 playRateMin_ = minimum;
75 playRateMax_ = maximum;
76 playRate_ = std::clamp(playRate_, minimum, maximum);
78}
79
80void MotionMatcher::updatePlayRate(int frame) {
81 float estimated = 1.f;
82 if (database_->schema_ && frame >= 0) {
83 const float poseSpeed = database_->frameAt(frame).trajectorySpeed;
84 if (poseSpeed > 1e-4f) estimated = queryTrajectorySpeed_ / poseSpeed;
85 }
86 playRate_ = std::clamp(estimated, playRateMin_, playRateMax_);
87}
88
90 if (!std::isfinite(seconds) || seconds < 0.f || seconds > 10.f)
93 "pose reselect history must be finite and between zero and ten seconds",
94 "poseReselectHistory", {}, "animation"));
95 poseReselectHistory_ = seconds;
96 if (seconds == 0.f) poseHistory_.clear();
98}
99
101 if (matchedFrame_ < 0 || !database_->isBaked()) return -1;
102 return database_->getFrameClipIndex(matchedFrame_);
103}
104
105AnimPose* MotionMatcher::getPose() { return &pose_; }
106
107void MotionMatcher::buildQuery(std::vector<float>& query) const {
108 if (database_->hasFeatureLayout()) {
109 buildSchemaQuery(query);
110 return;
111 }
112 if (!database_->isBaked()) throw Exception("MotionMatcher: database not baked");
113 if (database_->hasLocomotionFeatures()) {
114 buildLocomotionQuery(query);
115 return;
116 }
117 const int n = database_->getFeatureSize();
118 query.assign(static_cast<size_t>(n), 0.f);
119
120 // Character-space desired velocity (assume current facing = desiredYaw for query).
121 const float cs = std::cos(desiredYaw_);
122 const float sn = std::sin(desiredYaw_);
123 query[0] = desiredVelX_ * cs - desiredVelZ_ * sn;
124 query[1] = desiredVelX_ * sn + desiredVelZ_ * cs;
125
126 // Desired trajectory: integrate constant velocity for 0.33/0.66/1.0s in char space.
127 const float horizons[3] = {0.33f, 0.66f, 1.0f};
128 for (int h = 0; h < 3; ++h) {
129 query[static_cast<size_t>(2 + h * 2)] = query[0] * horizons[h];
130 query[static_cast<size_t>(2 + h * 2 + 1)] = query[1] * horizons[h];
131 if (hasTrajectory_) {
132 query[static_cast<size_t>(2 + h * 2)] = trajectory_[h].x * cs - trajectory_[h].z * sn;
133 query[static_cast<size_t>(3 + h * 2)] = trajectory_[h].x * sn + trajectory_[h].z * cs;
134 }
135 }
136 // Facing at +1s: same as desired (relative facing 0 → forward +Z in char space).
137 float fx, fz;
138 yawToForward(hasTrajectory_ ? trajectory_[2].yaw - desiredYaw_ : 0.f, fx, fz);
139 query[8] = fx;
140 query[9] = fz;
141
142 // Pose features from current pose (character-relative).
143 AnimPose cur;
144 cur.copyFrom(hasQueryPose_ ? &queryPose_ : (playing_ ? &matchedPose_ : &pose_));
145 cur.computeWorld(skeleton_);
146 const int root = database_->getRootBone();
147 const float rootX = cur.getWorldPositionX(root);
148 const float rootZ = cur.getWorldPositionZ(root);
149 // Estimate current yaw from root rotation.
150 const float qy = cur.getWorldRotationY(root);
151 const float qw = cur.getWorldRotationW(root);
152 const float yaw = std::atan2(2.f * (qw * qy), 1.f - 2.f * (qy * qy));
153 const float c2 = std::cos(yaw);
154 const float s2 = std::sin(yaw);
155
156 int base = 10;
157 for (int i = 0; i < database_->getFeatureBoneCount(); ++i) {
158 const int b = database_->getFeatureBone(i);
159 const float dx = cur.getWorldPositionX(b) - rootX;
160 const float dz = cur.getWorldPositionZ(b) - rootZ;
161 const float lx = dx * c2 - dz * s2;
162 const float lz = dx * s2 + dz * c2;
163 query[static_cast<size_t>(base)] = lx;
164 query[static_cast<size_t>(base + 1)] = cur.getWorldPositionY(b);
165 query[static_cast<size_t>(base + 2)] = lz;
166 base += 3;
167 }
168 database_->normalizeFeature(query);
169}
170
171float MotionMatcher::cost(const std::vector<float>& query, const std::vector<float>& cand, float upperBound) const {
172 const int n = static_cast<int>(query.size());
173 float sum = 0.f;
174 const auto* schema = database_->schema_.get();
175 const float schemaWeight = schema ? schema->weightSums[0] * poseWeight_ + schema->weightSums[1] * velWeight_ +
176 schema->weightSums[2] * trajWeight_
177 : 0.f;
178 for (int i = 0; i < n; ++i) {
179 const float d = query[static_cast<size_t>(i)] - cand[static_cast<size_t>(i)];
180 float w = poseWeight_;
181 if (schema) {
182 w = schema->sources[i] == MotionFeatureSource::Pose
183 ? poseWeight_
184 : (schema->kinds[i] == MotionFeatureKind::Velocity ? velWeight_ : trajWeight_);
185 w *= schema->weights[i] / std::max(1e-8f, schemaWeight);
186 } else if (database_->hasLocomotionFeatures()) {
187 w = i < detail::locomotionPoseOffset ? trajWeight_ : poseWeight_;
188 if (i < 2 || (i >= 12 && i < 14) || (i >= 16 && i < 19)) w = velWeight_;
190 w /= std::max(1e-8f, 8.5f * velWeight_ + 10.6f * trajWeight_ + 5.f * poseWeight_);
191 } else if (i < 2)
192 w = velWeight_;
193 else if (i < 10)
194 w = trajWeight_;
195 sum += w * d * d;
196 if (sum >= upperBound) return sum;
197 }
198 return sum;
199}
200
201void MotionMatcher::sampleMatched(AnimPose* out) const {
202 if (matchedFrame_ < 0) {
203 skeleton_->applyBindPose(out);
204 return;
205 }
206 const int ci = database_->getFrameClipIndex(matchedFrame_);
207 AnimClip* clip = database_->getClip(ci);
208 clip->sample(matchedTime_, out, skeleton_);
209}
210
212 if (!database_->isBaked()) throw Exception("MotionMatcher.search: database not baked");
213 if (database_->getFrameCount() == 0) {
214 throw Exception("MotionMatcher.search: empty database");
215 }
216
217 std::vector<float> query;
218 buildQuery(query);
219
220 // Compare against the live playhead, not the original entry frame.
221 // Equal-cost searches must keep advancing instead of restarting a blend.
222 int continuation = -1;
223 float nearest = std::numeric_limits<float>::infinity();
224 const int currentClip = getMatchedClipIndex();
225 const auto* currentAsset = currentClip >= 0 ? database_->getClip(currentClip) : nullptr;
226 const bool ended = currentAsset && !currentAsset->getLoop() && matchedTime_ >= currentAsset->getDuration();
227 if (playing_ && currentClip >= 0 && !ended) {
228 const auto* clip = database_->getClip(currentClip);
229 const float time = clip->wrapTime(matchedTime_);
230 const int count = filtered_ ? static_cast<int>(candidateFrames_.size()) : database_->getFrameCount();
231 for (int candidate = 0; candidate < count; ++candidate) {
232 const int i = filtered_ ? candidateFrames_[candidate] : candidate;
233 if (database_->getFrameClipIndex(i) != currentClip) continue;
234 float distance = std::abs(database_->getFrameTime(i) - time);
235 if (clip->getLoop()) distance = std::min(distance, clip->getDuration() - distance);
236 if (distance < nearest) {
237 nearest = distance;
238 continuation = i;
239 }
240 }
241 // Candidate ranges are a live search context (for example a Chooser
242 // changing from grounded to airborne). A different valid interval in
243 // the same clip must not make an out-of-range playhead eligible as a
244 // continuing pose. At the bake rate, a live time is at most half a
245 // sample from its representing frame.
246 if (filtered_ && continuation >= 0) {
247 const float rate = currentAsset->getSampleRate() > 0.f ? currentAsset->getSampleRate() : 30.f;
248 if (nearest > .5f / rate + 1e-5f) continuation = -1;
249 }
250 }
251 float bestCost = std::numeric_limits<float>::infinity();
252 if (continuation >= 0) {
253 auto feature = database_->frameAt(continuation).feature;
254 // Continuing has no pose discontinuity. Use the evaluated playhead
255 // pose rather than its nearest baked sample (which is quantized).
256 if (database_->schema_) {
257 for (std::size_t i = 0; i < query.size(); ++i)
258 if (database_->schema_->queries[i] == MotionFeatureQuery::Continuing) query[i] = feature[i];
259 } else if (database_->hasLocomotionFeatures()) {
260 // Authored pose channels use UseContinuingPose; trajectory channels
261 // still use the character's actual/predicted movement.
262 std::copy(feature.begin() + detail::locomotionPoseOffset, feature.end(),
263 query.begin() + detail::locomotionPoseOffset);
264 } else
265 std::copy(query.begin() + 10, query.end(), feature.begin() + 10);
266 bestCost = cost(query, feature, bestCost);
267 if (filtered_) bestCost += candidateBias_[continuation] + candidateContinuingBias_[continuation];
268 }
269 int best = continuation;
270 float switchCost = bestCost;
271 const int searchCount = filtered_ ? static_cast<int>(candidateFrames_.size()) : database_->getFrameCount();
272 for (int candidate = 0; candidate < searchCount; ++candidate) {
273 const int i = filtered_ ? candidateFrames_[candidate] : candidate;
274 // Authored protected phases can be played through, but never jumped into.
275 if (filtered_ && transitionBlocked_[i]) continue;
276 if (std::any_of(poseHistory_.begin(), poseHistory_.end(), [i](const auto& item) { return item.first == i; }))
277 continue;
278 // DisableReselection belongs to the current asset, including its end.
279 // An expired one-shot cannot become its own fresh candidate again.
280 if (playing_ && filtered_ && disableReselection_[currentClip] && database_->getFrameClipIndex(i) == currentClip)
281 continue;
282 if (continuation >= 0 && database_->getFrameClipIndex(i) == currentClip) {
283 if (filtered_ && disableReselection_[currentClip]) continue;
284 const auto* clip = database_->getClip(currentClip);
285 float distance = std::abs(database_->getFrameTime(i) - clip->wrapTime(matchedTime_));
286 if (clip->getLoop()) distance = std::min(distance, clip->getDuration() - distance);
287 const float rate = clip->getSampleRate() > 0.f ? clip->getSampleRate() : 30.f;
288 if (distance <= static_cast<float>(ignoreRadius_) / rate + 1e-5f) continue;
289 }
290 const float bias = filtered_ ? candidateBias_[i] : 0.f;
291 const float c = cost(query, database_->frameAt(i).feature, switchCost - bias) + bias;
292 if (c + 1e-5f < switchCost) {
293 bestCost = c;
294 switchCost = c;
295 best = i;
296 }
297 }
298 if (best == continuation && continuation >= 0) {
299 matchedFrame_ = continuation;
300 lastCost_ = bestCost;
301 updatePlayRate(continuation);
302 return;
303 }
304
305 // A database containing only an exhausted, non-reselectable one-shot holds
306 // its terminal pose. It remains searchable after the caller changes candidates.
307 if (best < 0) return;
308 lastCost_ = bestCost;
309 updatePlayRate(best);
310 if (best != matchedFrame_ || ended) {
311 matchedFrame_ = best;
312 matchedTime_ = database_->getFrameTime(best);
313 sampleMatched(&matchedPose_);
314 if (blendTime_ > 1e-6f && playing_) {
315 AnimPose previousTarget;
316 database_->getClip(getMatchedClipIndex())
317 ->sample(matchedTime_ - inertia_->historyInterval * playRate_, &previousTarget, skeleton_);
318 inertia_->begin(pose_, matchedPose_, previousTarget, blendTime_);
319 blending_ = true;
320 blendElapsed_ = 0.f;
321 } else {
322 pose_.copyFrom(&matchedPose_);
323 blending_ = false;
324 }
325 playing_ = true;
326 }
327}
328
329void MotionMatcher::updateUnchecked(float dt) {
330 if (dt < 0.f) throw Exception("MotionMatcher.update: dt must be >= 0");
331 if (!database_->isBaked()) return;
332
333 if (!playing_) {
334 search();
335 searchTimer_ = 0.f;
336 } else {
337 searchTimer_ += dt;
338 const auto* clip = matchedFrame_ >= 0 ? database_->getClip(getMatchedClipIndex()) : nullptr;
339 const bool ended = clip && !clip->getLoop() && matchedTime_ >= clip->getDuration();
340 if (searchTimer_ >= searchInterval_ || ended) {
341 searchTimer_ = 0.f;
342 search();
343 }
344 }
345
346 inertia_->remember(pose_, dt);
347 if (matchedFrame_ >= 0) {
348 matchedTime_ += dt * playRate_;
349 const auto* clip = database_->getClip(getMatchedClipIndex());
350 if (!clip->getLoop()) matchedTime_ = std::min(matchedTime_, clip->getDuration());
351 sampleMatched(&matchedPose_);
352 }
353
354 if (blending_) {
355 blendElapsed_ += dt;
356 if (blendElapsed_ >= inertia_->duration) {
357 blending_ = false;
358 pose_.copyFrom(&matchedPose_);
359 } else {
360 inertia_->apply(matchedPose_, blendElapsed_, pose_);
361 }
362 } else if (matchedFrame_ >= 0) {
363 pose_.copyFrom(&matchedPose_);
364 }
365 updatePoseHistory(dt);
366}
367
368void MotionMatcher::updatePoseHistory(float dt) {
369 if (poseReselectHistory_ <= 0.f || dt <= 0.f || matchedFrame_ < 0) return;
370 for (auto& item : poseHistory_) item.second += dt;
371 std::erase_if(poseHistory_, [&](const auto& item) { return item.second > poseReselectHistory_; });
372 const int clipIndex = getMatchedClipIndex();
373 const auto* clip = database_->getClip(clipIndex);
374 const float time = clip->wrapTime(matchedTime_);
375 int nearestFrame = -1;
376 float nearest = std::numeric_limits<float>::infinity();
377 const int count = filtered_ ? static_cast<int>(candidateFrames_.size()) : database_->getFrameCount();
378 for (int candidate = 0; candidate < count; ++candidate) {
379 const int i = filtered_ ? candidateFrames_[candidate] : candidate;
380 if (database_->getFrameClipIndex(i) != clipIndex) continue;
381 float distance = std::abs(database_->getFrameTime(i) - time);
382 if (clip->getLoop()) distance = std::min(distance, clip->getDuration() - distance);
383 if (distance < nearest) {
384 nearest = distance;
385 nearestFrame = i;
386 }
387 }
388 if (nearestFrame < 0) return;
389 auto found = std::find_if(poseHistory_.begin(), poseHistory_.end(),
390 [nearestFrame](const auto& item) { return item.first == nearestFrame; });
391 if (found == poseHistory_.end())
392 poseHistory_.push_back({nearestFrame, 0.f});
393 else
394 found->second = 0.f;
395}
396
398 auto seconds = detail::secondsForStep(step, hasLastTick_, lastTick_, "MotionMatcher");
399 if (!seconds) return eve::Result<void>::failure(seconds.status());
400 updateUnchecked(std::move(seconds).takeValue());
401 lastTick_ = step.tick;
402 hasLastTick_ = true;
404}
405
407 auto step = detail::legacyStep(dt, hasLastTick_, lastTick_, "MotionMatcher");
408 if (!step) {
409 step.ignore("legacy MotionMatcher update");
410 return;
411 }
412 advance(std::move(step).takeValue()).ignore("legacy MotionMatcher update");
413}
414
415} // namespace eve::animation
416
417// MotionMatcherLocomotion.cpp
418namespace eve::animation {
420 float elapsedSeconds,
421 std::span<const MotionLocomotionSample> samples) {
422 auto finitePose = [](const AnimPose& pose) {
423 for (int i = 0; i < pose.getBoneCount(); ++i) {
424 const auto& t = pose.local(i);
425 for (float v : {t.px, t.py, t.pz, t.qx, t.qy, t.qz, t.qw, t.sx, t.sy, t.sz})
426 if (!std::isfinite(v)) return false;
427 }
428 return true;
429 };
430 if (!database_->hasLocomotionFeatures() || current.getBoneCount() != pose_.getBoneCount() ||
431 previous.getBoneCount() != pose_.getBoneCount() || !std::isfinite(elapsedSeconds) || elapsedSeconds <= 0.f ||
432 elapsedSeconds > 1.f || samples.size() != 5 || !finitePose(current) || !finitePose(previous) ||
433 std::any_of(samples.begin(), samples.end(), [](const auto& s) {
434 for (float v : {s.x, s.y, s.z, s.vx, s.vy, s.vz, s.yaw})
435 if (!std::isfinite(v)) return true;
436 return false;
437 }))
440 "locomotion query requires the locomotion layout, finite matching poses, five samples, and dt in (0,1]",
441 "locomotionQuery", {}, "animation"));
442 AnimPose nextCurrent, nextPrevious;
443 nextCurrent.copyFrom(&current);
444 nextPrevious.copyFrom(&previous);
445 queryPose_ = std::move(nextCurrent);
446 previousQueryPose_ = std::move(nextPrevious);
447 std::copy(samples.begin(), samples.end(), locomotionTrajectory_.begin());
448 queryPoseInterval_ = elapsedSeconds;
449 hasLocomotionQuery_ = true;
450 hasQueryPose_ = true;
452}
453
454void MotionMatcher::buildLocomotionQuery(std::vector<float>& query) const {
455 if (!hasLocomotionQuery_) throw Exception("MotionMatcher: configure a locomotion query before searching");
456 query.assign(detail::locomotionFeatureCount, 0.f);
457 detail::encodeLocomotionTrajectory(std::span(query), locomotionTrajectory_, desiredYaw_);
458 AnimPose current, previous;
459 current.copyFrom(&queryPose_);
460 previous.copyFrom(&previousQueryPose_);
461 current.computeWorld(skeleton_);
462 previous.computeWorld(skeleton_);
463 std::array<TransformTRS, 4> now{}, past{};
464 now[0] = current.world(database_->getRootBone());
465 past[0] = previous.world(database_->getRootBone());
466 for (int i = 0; i < 3; ++i) {
467 const int bone = database_->getFeatureBone(i);
468 now[i + 1] = current.world(bone);
469 past[i + 1] = previous.world(bone);
470 }
471 detail::encodeLocomotionPose(query, now, past, queryPoseInterval_);
472 database_->normalizeFeature(query);
473}
474} // namespace eve::animation
475
476// MotionMatcherSchema.cpp
477namespace eve::animation {
479 std::span<const MotionFeatureTrajectorySample> samples,
480 std::span<const MotionFeatureCurveSample> curves) {
481 auto fail = [](const char* message) {
483 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, message, "featureQuery", {}, "animation"));
484 };
485 if (!database_->schema_ || !database_->isBaked() || !std::isfinite(dt) || dt <= 0.f || dt > 1.f ||
486 current.getBoneCount() != skeleton_->getBoneCount() || previous.getBoneCount() != skeleton_->getBoneCount() ||
487 samples.size() > 256 || curves.size() > 256)
488 return fail("feature query requires a baked variable layout, matching poses and finite dt in (0,1]");
489 for (const auto* pose : {&current, &previous})
490 for (int i = 0; i < pose->getBoneCount(); ++i) {
491 const auto& t = pose->local(i);
492 for (float v : {t.px, t.py, t.pz, t.qx, t.qy, t.qz, t.qw, t.sx, t.sy, t.sz})
493 if (!std::isfinite(v)) return fail("feature query poses must be finite");
494 }
495 for (std::size_t i = 0; i < samples.size(); ++i) {
496 const auto& s = samples[i];
497 for (float v : {s.seconds, s.x, s.y, s.z, s.vx, s.vy, s.vz, s.yaw})
498 if (!std::isfinite(v)) return fail("trajectory samples must be finite");
499 for (std::size_t j = 0; j < i; ++j)
500 if (std::abs(s.seconds - samples[j].seconds) < 1e-6f) return fail("trajectory sample times must be unique");
501 }
502 const auto& schema = *database_->schema_;
503 for (std::size_t i = 0; i < curves.size(); ++i) {
504 const auto& c = curves[i];
505 if (c.curve.empty() || c.curve.size() > 4096 || !std::isfinite(c.seconds) || !std::isfinite(c.value))
506 return fail("curve queries require bounded names and finite times/values");
507 for (std::size_t j = 0; j < i; ++j)
508 if (c.curve == curves[j].curve && std::abs(c.seconds - curves[j].seconds) < 1e-6f)
509 return fail("curve query names and times must be unique");
510 }
511 std::vector<float> scalarValues(schema.layout.channels.size(), 0.f);
512 for (std::size_t i = 0; i < schema.layout.channels.size(); ++i) {
513 const auto& c = schema.layout.channels[i];
514 if (c.kind != MotionFeatureKind::Curve) continue;
515 auto sample = std::find_if(curves.begin(), curves.end(), [&](const auto& s) {
516 return s.curve == c.curve && std::abs(s.seconds - c.sampleTime) < 1e-6f;
517 });
518 if (sample == curves.end()) return fail("curve query does not cover a configured channel/time");
519 scalarValues[i] = sample->value;
520 }
521 std::vector<const MotionFeatureTrajectorySample*> selected;
522 for (const auto& c : schema.layout.channels) {
523 const MotionFeatureTrajectorySample* sample = nullptr;
524 if (c.source == MotionFeatureSource::Trajectory) {
525 for (const auto& s : samples)
526 if (std::abs(s.seconds - c.sampleTime) < 1e-6f) {
527 sample = &s;
528 break;
529 }
530 if (!sample) return fail("trajectory query does not cover a configured sample time");
531 }
532 selected.push_back(sample);
533 }
534 AnimPose now, past;
535 now.copyFrom(&current);
536 past.copyFrom(&previous);
537 now.computeWorld(skeleton_);
538 past.computeWorld(skeleton_);
539 const auto& root = now.world(database_->getRootBone());
540 const auto& previousRoot = past.world(database_->getRootBone());
541 TransformTRS character;
542 character.qy = std::sin(desiredYaw_ * .5f);
543 character.qw = std::cos(desiredYaw_ * .5f);
544 std::vector<float> query(schema.dimension, 0.f);
545 for (std::size_t i = 0; i < schema.layout.channels.size(); ++i) {
546 const auto& c = schema.layout.channels[i];
547 std::array<float, 3> value{};
548 if (c.kind == MotionFeatureKind::Curve)
549 value[0] = scalarValues[i];
550 else if (const auto* sample = selected[i]) {
551 if (c.kind == MotionFeatureKind::Position)
552 value = detail::schemaRotate({sample->x, sample->y, sample->z}, character, true);
553 else if (c.kind == MotionFeatureKind::Velocity)
554 value = detail::schemaRotate({sample->vx, sample->vy, sample->vz}, character, true);
555 else {
557 rotation.qy = std::sin(sample->yaw * .5f);
558 rotation.qw = std::cos(sample->yaw * .5f);
559 value = detail::schemaHeading(rotation, character, c.headingAxis);
560 }
561 } else {
562 const auto& bone = now.world(c.bone);
563 if (c.kind == MotionFeatureKind::Position)
565 else if (c.kind == MotionFeatureKind::Heading)
566 value = detail::schemaHeading(bone, root, c.headingAxis);
567 else if (c.characterSpaceVelocity) {
569 const auto old = detail::schemaDifference(past.world(c.bone), past.world(c.origin), previousRoot);
570 for (int axis = 0; axis < 3; ++axis) value[axis] = (value[axis] - old[axis]) / dt;
571 } else {
573 for (float& v : value) v /= dt;
574 }
575 }
576 detail::schemaEncode(std::span(query).subspan(schema.offsets[i]), c, value,
577 schema.layout.normalizationLengthScale);
578 }
579 for (float v : query)
580 if (!std::isfinite(v)) return fail("encoded feature query exceeds finite range");
581 const float queryTrajectorySpeed = database_->schemaTrajectorySpeed(query);
582 database_->normalizeFeature(query);
583 for (float v : query)
584 if (!std::isfinite(v)) return fail("normalized feature query exceeds finite range");
585 schemaQuery_.swap(query);
586 queryTrajectorySpeed_ = queryTrajectorySpeed;
588}
589
590void MotionMatcher::buildSchemaQuery(std::vector<float>& query) const {
591 if (schemaQuery_.empty()) throw Exception("MotionMatcher: configure a feature query before searching");
592 query = schemaQuery_;
593}
594} // namespace eve::animation
595
596// MotionMatcherSelection.cpp
597namespace eve::animation {
598eve::Result<int> MotionMatcher::setCandidateRanges(std::span<const MotionSearchRange> ranges) {
599 auto fail = [](const char* message) {
601 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, message, "candidateRanges", {}, "animation"));
602 };
603 if (!database_->isBaked() || ranges.empty() || ranges.size() > 100000)
604 return fail("candidate selection requires a baked database and bounded nonempty ranges");
605 std::vector<std::vector<MotionSearchRange>> perClip(database_->getClipCount());
606 std::size_t intervalCount = 0;
607 for (const auto& r : ranges) {
608 if (r.clipIndex < 0 || r.clipIndex >= database_->getClipCount() || !std::isfinite(r.start) ||
609 !std::isfinite(r.end) || !std::isfinite(r.costBias) || r.start < 0.f || r.end < r.start ||
610 r.end > database_->getClip(r.clipIndex)->getDuration() + 0.001f)
611 return fail("invalid candidate clip, time interval, or cost bias");
612 intervalCount += r.transitionBlocks.size() + r.costOverrides.size() + r.continuingCostOverrides.size();
613 if (intervalCount > 100000) return fail("too many candidate metadata intervals");
614 for (const auto& block : r.transitionBlocks)
615 if (!std::isfinite(block.start) || !std::isfinite(block.end) || block.start < 0.f ||
616 block.end <= block.start)
617 return fail("invalid transition block interval");
618 if (!std::isfinite(r.continuingCostBias)) return fail("invalid continuing cost bias");
619 for (const auto* overrides : {&r.costOverrides, &r.continuingCostOverrides})
620 for (const auto& cost : *overrides)
621 if (!std::isfinite(cost.start) || !std::isfinite(cost.end) || !std::isfinite(cost.costBias) ||
622 cost.start < 0.f || cost.end <= cost.start)
623 return fail("invalid cost override interval");
624 perClip[r.clipIndex].push_back(r);
625 }
626 const int count = database_->getFrameCount();
627 std::vector<int> selected;
628 std::vector<float> bias(count, 0.f);
629 std::vector<float> continuingBias(count, 0.f);
630 std::vector<unsigned char> mask(count, 0), noReselect(database_->getClipCount(), 0);
631 std::vector<unsigned char> blocked(count, 0);
632 for (int clipIndex = 0; clipIndex < database_->getClipCount(); ++clipIndex) {
633 const auto& clipRanges = perClip[clipIndex];
634 if (clipRanges.empty()) continue;
635 const int begin = database_->clipFrameOffsets_[static_cast<std::size_t>(clipIndex)];
636 const int end = database_->clipFrameOffsets_[static_cast<std::size_t>(clipIndex + 1)];
637 for (int i = begin; i < end; ++i) {
638 const auto& frame = database_->frameAt(i);
639 float best = std::numeric_limits<float>::infinity();
640 for (const auto& r : clipRanges) {
641 for (const auto& block : r.transitionBlocks)
642 if (frame.time >= block.start && frame.time < block.end) blocked[i] = 1;
643 if (frame.time + 1e-5f < r.start || frame.time - 1e-5f > r.end) continue;
644 float rangeBias = r.costBias;
645 for (const auto& cost : r.costOverrides)
646 if (frame.time >= cost.start && frame.time < cost.end) rangeBias = cost.costBias;
647 float rangeContinuingBias = r.continuingCostBias;
648 for (const auto& cost : r.continuingCostOverrides)
649 if (frame.time >= cost.start && frame.time < cost.end) rangeContinuingBias = cost.costBias;
650 if (rangeBias < best) {
651 best = rangeBias;
652 continuingBias[i] = rangeContinuingBias;
653 }
654 if (r.disableReselection) noReselect[frame.clipIndex] = 1;
655 }
656 if (!std::isfinite(best)) continue;
657 selected.push_back(i);
658 mask[i] = 1;
659 bias[i] = best;
660 }
661 }
662 if (selected.empty()) return fail("candidate selection contains no sampled frames");
663 candidateFrames_.swap(selected);
664 candidateBias_.swap(bias);
665 candidateContinuingBias_.swap(continuingBias);
666 candidateMask_.swap(mask);
667 transitionBlocked_.swap(blocked);
668 disableReselection_.swap(noReselect);
669 filtered_ = true;
670 return eve::Result<int>::success(static_cast<int>(candidateFrames_.size()),
672}
673
675 if (database_->hasLocomotionFeatures() || database_->hasFeatureLayout() ||
676 pose.getBoneCount() != pose_.getBoneCount())
678 eve::DiagnosticCode::InvalidArgument, "basic query pose requires the basic layout and matching bone count",
679 "queryPose", {}, "animation"));
680 queryPose_.copyFrom(&pose);
681 hasQueryPose_ = true;
683}
684
685eve::Result<void> MotionMatcher::setTrajectory(std::span<const MotionTrajectorySample> samples) {
686 if (database_->hasLocomotionFeatures() || database_->hasFeatureLayout() || samples.size() != 3 ||
687 std::any_of(samples.begin(), samples.end(),
688 [](const auto& s) { return !std::isfinite(s.x) || !std::isfinite(s.z) || !std::isfinite(s.yaw); }))
690 "trajectory requires three finite samples",
691 "trajectory", {}, "animation"));
692 std::copy(samples.begin(), samples.end(), trajectory_.begin());
693 hasTrajectory_ = true;
695}
696} // namespace eve::animation
double z
double x
float w
Definition AnimClip.cpp:738
int root
Definition AnimSmr.cpp:119
std::string selected
eve::EntitySpatialPose pose
const std::string & s
int mask
float yaw
Definition BushMesh.cpp:37
eve::resource::CostSpec cost
std::string message
float maximum[3]
float minimum[3]
glm::vec4 clip
glm::vec3 n
Definition Grass.cpp:63
double r
float v
std::int32_t second
std::int32_t c
int h
JointPoint2D axis
std::array< float, 4 > rotation
std::uint32_t bone
bool ended
MeleePoint3 b
Definition MeleeHit.cpp:41
float distance
ssq::Object frame
glm::dvec3 dx
glm::dvec3 dz
double dt
std::shared_ptr< const OceanSprayFrame > previous
Object::Ptr value
float d
float t
bool found
ScriptStructure out
size_t begin
size_t end
double current
float bias
Definition Shadow.cpp:149
int count
std::map< Cell, int > best
float step
Definition TreeMesh.cpp:451
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
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Definition Result.h:571
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
float getDuration() const
Returns the duration.
Definition AnimClip.h:163
bool getLoop() const
Returns the loop.
Definition AnimClip.h:168
void sample(float time, AnimPose *out, const AnimSkeleton *skeleton=nullptr) const
Sample local pose at time (seconds). If skeleton non-null, missing tracks fall back to bind pose; oth...
Definition AnimClip.cpp:575
float wrapTime(float time) const
Wrap or clamp time according to loop flag.
Definition AnimClip.cpp:471
Evaluated local (and optional world) pose for an AnimSkeleton. Script type: AnimPose.
Definition AnimPose.h:17
int getBoneCount() const noexcept
Returns the bone count.
Definition AnimPose.h:36
const TransformTRS & world(int boneIndex) const
World.
Definition AnimPose.cpp:371
void copyFrom(const AnimPose *other)
Copies from.
Definition AnimPose.cpp:95
void computeWorld(const AnimSkeleton *skeleton)
Compute world transforms from local pose + skeleton hierarchy. World values readable via getWorld* af...
Definition AnimPose.cpp:207
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.
void applyBindPose(class AnimPose *pose) const
Fill pose locals with bind pose.
Baked motion-matching feature database from one or more AnimClips. Feature layout per frame: [0....
void normalizeFeature(std::vector< float > &feature) const
Normalize a query with statistics computed by bake().
AnimSkeleton * getSkeleton() const
Returns the skeleton.
bool hasFeatureLayout() const
Whether this database uses an explicitly configured variable layout.
float getFrameTime(int frameIndex) const
Returns the frame time.
bool isBaked() const
True when baked.
int getFeatureBoneCount() const
Returns the feature bone count.
AnimClip * getClip(int clipIndex) const
Returns the clip.
const Frame & frameAt(int index) const
int getFeatureSize() const
Returns the feature size.
int getRootBone() const
Returns the root bone.
bool hasLocomotionFeatures() const
Whether this database uses the 30-dimensional locomotion layout.
int getFeatureBone(int index) const
Returns the feature bone.
int getFrameCount() const
Returns the frame count.
int getFrameClipIndex(int frameIndex) const
Returns the frame clip index.
int getClipCount() const
Returns the clip count.
void search()
Force an immediate search (also called periodically from update).
void update(float dt)
Legacy seconds facade; explicitly forwards to advance().
void setBlendTime(float seconds)
Sets the blend time.
MotionMatcher(AnimSkeleton *skeleton, MotionDatabase *database)
Motion matcher.
eve::Result< void > setFeatureQuery(const AnimPose &current, const AnimPose &previous, float elapsedSeconds, std::span< const MotionFeatureTrajectorySample > samples, std::span< const MotionFeatureCurveSample > curves={})
Atomically copy a query for the database's variable feature layout.
void setDesiredYaw(float yaw)
Desired facing yaw (radians, Y-up).
eve::Result< void > setPoseReselectHistory(float seconds)
Set how long an already selected baked pose is excluded from new candidates.
eve::Result< void > setQueryPose(const AnimPose &pose)
Copy the character's current local pose for the next search, including action handoffs.
void setDesiredVelocity(float x, float z)
Desired planar velocity in character/world XZ (units/sec).
eve::Result< int > setCandidateRanges(std::span< const MotionSearchRange > ranges)
Atomically replace searchable intervals, retaining original database frame IDs.
void setVelocityWeight(float w)
Sets the velocity weight.
eve::Result< void > setLocomotionQuery(const AnimPose &current, const AnimPose &previous, float elapsedSeconds, std::span< const MotionLocomotionSample > samples)
Atomically copy pose history and trajectory for a locomotion database.
void setPoseWeight(float w)
Sets the pose weight.
void setTrajectoryWeight(float w)
Sets the trajectory weight.
AnimPose * getPose()
Returns the pose.
void setIgnoreRadius(int frames)
Keep continuous playback within this frame radius of the live playhead, including loop seams.
eve::Result< void > setTrajectory(std::span< const MotionTrajectorySample > samples)
Set predictions at 0.33, 0.66, and 1.0 seconds instead of constant-velocity prediction.
~MotionMatcher()
Motion matcher.
int getMatchedClipIndex() const
Returns the matched clip index.
eve::Result< void > setPlayRateRange(float minimum, float maximum)
Configure the inclusive playback-rate interval used to reconcile query and selected trajectory speed.
void setSearchInterval(float seconds)
Sets the search interval.
eve::Result< void > advance(const eve::SimulationStep &step)
Advance matching and pose blending by one scheduler step.
float locomotionWeight(int index)
Locomotion weight.
eve::Result< eve::SimulationStep > legacyStep(float seconds, bool hasLastTick, eve::SimulationTick lastTick, const char *owner)
Convert a legacy seconds call to the next local scheduler step.
std::array< float, 3 > schemaDifference(const TransformTRS &a, const TransformTRS &b, const TransformTRS &root)
eve::Result< float > secondsForStep(const eve::SimulationStep &step, bool hasLastTick, eve::SimulationTick lastTick, const char *owner)
Validate a scheduler step before an animation object mutates state.
std::array< float, 3 > schemaHeading(const TransformTRS &bone, const TransformTRS &root, int axis)
std::array< float, 3 > schemaRotate(const std::array< float, 3 > &p, const TransformTRS &q, bool inverse=false)
void schemaEncode(std::span< float > output, const MotionFeatureChannel &channel, std::array< float, 3 > value, float lengthScale)
Schema encode.
void yawToForward(float yaw, float &fx, float &fz)
Rotate unit +Z by yaw (radians) around Y — used for planar facing.
Definition AnimMath.h:144
I * query()
Queries .
Definition Capability.h:88
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Copied trajectory sample at an explicit offset from the current frame.
Local TRS used by skeletal animation (quaternion xyzw).
Definition AnimMath.h:9