载入中...
搜索中...
未找到
MontagePlayer.cpp
浏览该文件的文档.
2
8
9#include <algorithm>
10#include <cmath>
11#include <set>
12#include <unordered_map>
13#include <utility>
14
15namespace eve::animation {
16
25public:
26 struct Section {
29 std::size_t clipIndex = 0;
30 bool contiguousPrevious = false;
31 bool contiguousNext = false;
32 };
33
34 std::vector<Section> sections;
35 std::vector<std::pair<Duration, Duration>> physicalSections;
36 std::unordered_map<std::string, std::size_t> clipIndices;
37};
38
39namespace {
40
41template <class T>
42Result<T> invalid(std::string message, std::string path) {
44}
45
46RootMotionLockAxes locksFromMask(MontageRootMotionMask mask) noexcept {
48 if (!mask.translationX) locks = locks | RootMotionLockAxes::X;
49 if (!mask.translationY) locks = locks | RootMotionLockAxes::Y;
50 if (!mask.translationZ) locks = locks | RootMotionLockAxes::Z;
51 return locks;
52}
53
54MontageRootMotionMask maskFromPolicy(const RootMotionPolicy& policy) noexcept {
55 MontageRootMotionMask mask;
56 mask.translationX = !hasLock(policy.lockAxes, RootMotionLockAxes::X);
57 mask.translationY = !hasLock(policy.lockAxes, RootMotionLockAxes::Y);
58 mask.translationZ = !hasLock(policy.lockAxes, RootMotionLockAxes::Z);
59 mask.rotation = !policy.lockRotation;
60 return mask;
61}
62
63void multiplyRotation(TransformTRS& total, float x, float y, float z, float w) {
64 const float tx = total.qx;
65 const float ty = total.qy;
66 const float tz = total.qz;
67 const float tw = total.qw;
68 total.qx = tw * x + tx * w + ty * z - tz * y;
69 total.qy = tw * y - tx * z + ty * w + tz * x;
70 total.qz = tw * z + tx * y - ty * x + tz * w;
71 total.qw = tw * w - tx * x - ty * y - tz * z;
72}
73
74Result<std::unique_ptr<PreparedMontage>> buildPreparedMontage(const action::ActionTimeline& timeline,
75 const std::vector<MontageClipAsset>& clips) {
76 auto prepared = std::make_unique<PreparedMontage>();
77 prepared->clipIndices.reserve(clips.size());
78 for (std::size_t index = 0; index < clips.size(); ++index)
79 prepared->clipIndices.emplace(clips[index].uri, index);
80
81 prepared->sections.reserve(timeline.animationSections.size());
82 for (std::size_t index = 0; index < timeline.animationSections.size(); ++index) {
83 const auto& section = timeline.animationSections[index];
84 const auto clip = prepared->clipIndices.find(section.animationUri);
85 if (clip == prepared->clipIndices.end())
86 return invalid<std::unique_ptr<PreparedMontage>>("animation section clip was not supplied",
87 "animationSections[" + std::to_string(index) +
88 "].animationUri");
89 prepared->sections.push_back(
90 {section.start, section.end, clip->second,
91 index > 0 && timeline.animationSections[index - 1].end == section.start,
92 index + 1 < timeline.animationSections.size() &&
93 timeline.animationSections[index + 1].start == section.end});
94 }
95
96 prepared->physicalSections.reserve(timeline.splitTimestamps.size() + 1U);
97 Duration start = Duration::zero();
98 for (const Duration split : timeline.splitTimestamps) {
99 prepared->physicalSections.emplace_back(start, split);
100 start = split;
101 }
102 prepared->physicalSections.emplace_back(start, timeline.duration);
103 return Result<std::unique_ptr<PreparedMontage>>::success(std::move(prepared));
104}
105
106} // namespace
107
109 : skeleton_(skeleton), player_(std::make_unique<AnimPlayer>(&skeleton)) {
110 pushRootMotionPolicyToPlayer();
111}
112
114
116 auto valid = timeline.validate();
117 if (!valid) return Result<void>::failure(valid.status());
118 std::set<std::string> seen;
119 std::vector<MontageClipAsset> clips;
120 for (const auto& section : timeline.animationSections) {
121 if (!seen.insert(section.animationUri).second) continue;
122 auto loaded = provider.load(section.animationUri, skeleton_);
123 if (!loaded) return Result<void>::failure(loaded.status());
124 clips.push_back({section.animationUri, std::move(loaded).takeValue()});
125 }
126 return prepare(std::move(timeline), std::move(clips));
127}
128
129Result<void> MontagePlayer::prepare(action::ActionTimeline timeline, std::vector<MontageClipAsset>&& clips) {
130 auto valid = timeline.validate();
131 if (!valid) return Result<void>::failure(valid.status());
132
133 std::set<std::string> uris;
134 for (std::size_t index = 0; index < clips.size(); ++index) {
135 if (clips[index].uri.empty() || !clips[index].clip)
137 "montage clip asset is incomplete",
138 "clips[" + std::to_string(index) + "]"));
139 if (!std::isfinite(clips[index].clip->getDuration()) || clips[index].clip->getDuration() <= 0.0f)
141 "montage clip duration must be positive",
142 "clips[" + std::to_string(index) + "]"));
143 if (!uris.insert(clips[index].uri).second)
145 "montage clip URI is duplicated",
146 "clips[" + std::to_string(index) + "].uri"));
147 }
148 for (std::size_t index = 0; index < timeline.animationSections.size(); ++index) {
149 const auto& section = timeline.animationSections[index];
150 if (!uris.contains(section.animationUri))
152 Diagnostic::error(DiagnosticCode::InvalidArgument, "animation section clip was not supplied",
153 "animationSections[" + std::to_string(index) + "].animationUri"));
154 AnimClip* clip = nullptr;
155 const auto asset = std::find_if(clips.begin(), clips.end(),
156 [&](const auto& candidate) { return candidate.uri == section.animationUri; });
157 if (asset != clips.end()) clip = asset->clip.get();
158 const double sourceStart = section.sourceStart.seconds();
159 const double sourceEnd = section.sourceEnd.isZero() ? clip->getDuration() : section.sourceEnd.seconds();
160 if (sourceStart >= clip->getDuration() || sourceEnd > clip->getDuration() || sourceEnd <= sourceStart)
162 DiagnosticCode::InvalidArgument, "animation section trim is outside the supplied clip",
163 "animationSections[" + std::to_string(index) + "].sourceStartNs"));
164 }
165
166 auto prepared = buildPreparedMontage(timeline, clips);
167 if (!prepared) return Result<void>::failure(prepared.status());
168
169 timeline_ = std::move(timeline);
170 clips_ = std::move(clips);
171 prepared_ = std::move(prepared).takeValue();
172 activeSection_ = nullptr;
173 player_->stop();
174 time_ = Duration::zero();
175 lastTick_ = SimulationTick::zero();
176 hasLastTick_ = false;
177 started_ = false;
178 playing_ = false;
179 blendingOut_ = false;
180 weight_ = 1.0;
181 executionId_ = {};
182 applyTimelineRootMotionChannels();
184}
185
187 if (!timeline_)
189 Diagnostic::error(DiagnosticCode::InvalidArgument, "montage has not been prepared", "montage"));
190
191 std::set<std::string> seen;
192 std::vector<MontageClipAsset> replacements;
193 for (const auto& section : timeline_->animationSections) {
194 if (!seen.insert(section.animationUri).second) continue;
195 auto loaded = provider.load(section.animationUri, skeleton_);
196 if (!loaded) return Result<void>::failure(loaded.status());
197 replacements.push_back({section.animationUri, std::move(loaded).takeValue()});
198 }
199
200 MontagePlayer candidate(skeleton_);
201 auto validated = candidate.prepare(*timeline_, std::move(replacements));
202 if (!validated) return validated;
203
204 clips_ = std::move(candidate.clips_);
205 prepared_ = std::move(candidate.prepared_);
206 player_->stop();
207 activeSection_ = nullptr;
208 if ((playing_ || blendingOut_) && time_ < timeline_->duration) {
209 if (const auto* section = sectionAt(time_))
210 activate(*section, Duration::fromNanoseconds(time_.nanoseconds() - section->start.nanoseconds()));
211 }
213}
214
216 if (!timeline_)
218 Diagnostic::error(DiagnosticCode::InvalidArgument, "montage has not been prepared", "montage"));
219 auto candidate = *timeline_;
220 candidate.montage = settings;
221 auto valid = candidate.validate();
222 if (!valid) return Result<void>::failure(valid.status());
223 timeline_->montage = std::move(settings);
224 applyTimelineRootMotionChannels();
226}
227
228Result<void> MontagePlayer::setSectionSplits(std::vector<Duration> splitTimestamps) {
229 if (!timeline_)
231 Diagnostic::error(DiagnosticCode::InvalidArgument, "montage has not been prepared", "montage"));
232 auto candidate = *timeline_;
233 candidate.splitTimestamps = std::move(splitTimestamps);
234 auto valid = candidate.validate();
235 if (!valid) return Result<void>::failure(valid.status());
236 auto prepared = buildPreparedMontage(candidate, clips_);
237 if (!prepared) return Result<void>::failure(prepared.status());
238 timeline_->splitTimestamps = std::move(candidate.splitTimestamps);
239 prepared_ = std::move(prepared).takeValue();
241}
242
243Result<void> MontagePlayer::replaceClip(std::string_view uri, std::unique_ptr<AnimClip> clip) {
244 if (!timeline_)
246 Diagnostic::error(DiagnosticCode::InvalidArgument, "montage has not been prepared", "montage"));
247 if (uri.empty() || !clip)
249 Diagnostic::error(DiagnosticCode::InvalidArgument, "replacement montage clip is incomplete", "clip"));
250 if (!std::isfinite(clip->getDuration()) || clip->getDuration() <= 0.0f)
252 DiagnosticCode::InvalidArgument, "replacement montage clip duration must be positive", "clip.duration"));
253 const auto asset = std::find_if(clips_.begin(), clips_.end(), [&](const auto& value) { return value.uri == uri; });
254 if (asset == clips_.end())
256 "replacement URI is not referenced by the montage", "uri"));
257 for (std::size_t index = 0; index < timeline_->animationSections.size(); ++index) {
258 const auto& section = timeline_->animationSections[index];
259 if (section.animationUri != uri) continue;
260 const double sourceStart = section.sourceStart.seconds();
261 const double sourceEnd = section.sourceEnd.isZero() ? clip->getDuration() : section.sourceEnd.seconds();
262 if (sourceStart >= clip->getDuration() || sourceEnd > clip->getDuration() || sourceEnd <= sourceStart)
264 DiagnosticCode::InvalidArgument, "animation section trim is outside the replacement clip",
265 "animationSections[" + std::to_string(index) + "].sourceStartNs"));
266 }
267
268 asset->clip = std::move(clip);
269 if ((playing_ || blendingOut_) && activeSection_ && activeSection_->animationUri == uri) {
270 player_->stop();
271 const auto* section = sectionAt(time_);
272 activeSection_ = nullptr;
273 if (section) activate(*section, Duration::fromNanoseconds(time_.nanoseconds() - section->start.nanoseconds()));
274 }
276}
277
279 if (!timeline_)
281 Diagnostic::error(DiagnosticCode::InvalidArgument, "montage has not been prepared", "montage"));
282 if (executionId.isZero())
284 Diagnostic::error(DiagnosticCode::InvalidArgument, "action execution id must not be zero", "executionId"));
285 player_->stop();
286 activeSection_ = nullptr;
287 time_ = Duration::zero();
288 hasLastTick_ = false;
289 started_ = false;
290 playing_ = true;
291 blendingOut_ = false;
292 weight_ = timeline_->montage.defaultBlendIn.isZero() ? 1.0 : 0.0;
293 executionId_ = executionId;
295}
296
298 if (!timeline_ || !playing_)
300 DiagnosticCode::InvalidArgument, "montage must be prepared and playing before rebinding", "montage"));
301 if (executionId.isZero())
303 Diagnostic::error(DiagnosticCode::InvalidArgument, "action execution id must not be zero", "executionId"));
304 executionId_ = executionId;
306}
307
308void MontagePlayer::stop() noexcept {
309 player_->stop();
310 activeSection_ = nullptr;
311 time_ = Duration::zero();
312 hasLastTick_ = false;
313 started_ = false;
314 playing_ = false;
315 blendingOut_ = false;
316 weight_ = 0.0;
317 executionId_ = {};
318}
319
320std::optional<std::size_t> MontagePlayer::sectionIndexAt(Duration time) const noexcept {
321 if (!prepared_ || prepared_->sections.empty()) return std::nullopt;
322 const auto found = std::upper_bound(
323 prepared_->sections.begin(), prepared_->sections.end(), time,
324 [](Duration value, const PreparedMontage::Section& section) { return value < section.start; });
325 if (found == prepared_->sections.begin()) return std::nullopt;
326 const auto candidate = std::prev(found);
327 if (time < candidate->start || time >= candidate->end) return std::nullopt;
328 return static_cast<std::size_t>(std::distance(prepared_->sections.begin(), candidate));
329}
330
331std::optional<Duration> MontagePlayer::nextSectionStartAfter(Duration time) const noexcept {
332 if (!prepared_) return std::nullopt;
333 const auto found = std::upper_bound(
334 prepared_->sections.begin(), prepared_->sections.end(), time,
335 [](Duration value, const PreparedMontage::Section& section) { return value < section.start; });
336 return found == prepared_->sections.end() ? std::nullopt : std::optional<Duration>(found->start);
337}
338
339const action::ActionAnimationSection* MontagePlayer::sectionAt(Duration time) const noexcept {
340 const auto index = sectionIndexAt(time);
341 return index && timeline_ ? &timeline_->animationSections[*index] : nullptr;
342}
343
344double MontagePlayer::sectionEnvelopeAt(Duration time) const noexcept {
345 if (!timeline_ || !prepared_ || prepared_->sections.empty()) return 0.0;
346 auto index = sectionIndexAt(time);
347 if (!index && time == prepared_->sections.back().end) index = prepared_->sections.size() - 1U;
348 if (!index) return 0.0;
349 const auto& section = timeline_->animationSections[*index];
350 const auto& topology = prepared_->sections[*index];
351 double envelope = 1.0;
352 if (!topology.contiguousPrevious && !section.blendIn.isZero()) {
353 const auto elapsed = Duration::fromNanoseconds(time.nanoseconds() - section.start.nanoseconds());
354 envelope =
355 action::evaluateActionBlendCurve(section.blendInCurve, elapsed.seconds() / section.blendIn.seconds());
356 }
357 if (!topology.contiguousNext && !section.blendOut.isZero()) {
358 const auto remaining = Duration::fromNanoseconds(section.end.nanoseconds() - time.nanoseconds());
359 envelope *=
360 action::evaluateActionBlendCurve(section.blendOutCurve, remaining.seconds() / section.blendOut.seconds());
361 }
362 return envelope;
363}
364
365void MontagePlayer::activate(const action::ActionAnimationSection& section, Duration localTime) {
366 const auto sectionIndex = static_cast<std::size_t>(&section - timeline_->animationSections.data());
367 AnimClip* clip = clips_[prepared_->sections[sectionIndex].clipIndex].clip.get();
368 const float authoredSeconds = static_cast<float>(
369 Duration::fromNanoseconds(section.end.nanoseconds() - section.start.nanoseconds()).seconds());
370 const float sourceStart = static_cast<float>(section.sourceStart.seconds());
371 const float sourceEnd =
372 section.sourceEnd.isZero() ? clip->getDuration() : static_cast<float>(section.sourceEnd.seconds());
373 const float speed = (sourceEnd - sourceStart) / authoredSeconds;
374 const auto blendCurve = [](action::ActionBlendCurve curve) {
375 switch (curve) {
381 }
383 };
384 player_->setBlendCurve(blendCurve(section.blendInCurve));
385 if (!player_->isPlaying())
386 player_->play(clip);
387 else
388 player_->crossFade(clip, static_cast<float>(section.blendIn.seconds()));
389 player_->setLoop(false);
390 player_->setSpeed(speed);
391 player_->setTime(sourceStart + static_cast<float>(localTime.seconds()) * speed);
392 activeSection_ = &section;
393}
394
395void MontagePlayer::accumulateRootMotion(TransformTRS& total) const {
396 total.px += player_->getRootMotionX();
397 total.py += player_->getRootMotionY();
398 total.pz += player_->getRootMotionZ();
399 multiplyRotation(total, player_->getRootMotionRotationX(), player_->getRootMotionRotationY(),
400 player_->getRootMotionRotationZ(), player_->getRootMotionRotationW());
401}
402
403void MontagePlayer::pushRootMotionPolicyToPlayer() noexcept {
404 player_->setRootMotionPolicy(rootMotionPolicy_)
405 .ignore("montage root-motion policy sync uses an already-validated policy snapshot");
406}
407
408void MontagePlayer::applyTimelineRootMotionChannels() noexcept {
409 MontageRootMotionMask mask;
410 mask.translationX = timeline_->montage.rootMotionHorizontal;
411 mask.translationZ = timeline_->montage.rootMotionHorizontal;
412 mask.translationY = timeline_->montage.rootMotionVertical;
413 mask.rotation = timeline_->montage.rootMotionRotation;
414 rootMotionMask_ = mask;
415 rootMotionPolicy_.lockAxes = locksFromMask(mask);
416 rootMotionPolicy_.lockRotation = !mask.rotation;
417 pushRootMotionPolicyToPlayer();
418}
419
421 rootMotionMask_ = mask;
422 rootMotionPolicy_.lockAxes = locksFromMask(mask);
423 rootMotionPolicy_.lockRotation = !mask.rotation;
424 pushRootMotionPolicyToPlayer();
425}
426
428 auto validated = validateRootMotionPolicy(policy);
429 if (!validated) return validated;
430 rootMotionPolicy_ = policy;
431 rootMotionMask_ = maskFromPolicy(policy);
432 auto pushed = player_->setRootMotionPolicy(policy);
433 if (!pushed) return pushed;
435}
436
438 auto applied = player_->setRootMotionCharacterYaw(yawRadians);
439 if (!applied) return applied;
440 rootMotionPolicy_.characterYaw = yawRadians;
442}
443
445 return presentImpl(advance, advance.timelineEvents, advance.activeBlocks, tick);
446}
447
449 auto events = std::move(advance.timelineEvents);
450 auto activeBlocks = std::move(advance.activeBlocks);
451 return presentImpl(advance, std::move(events), std::move(activeBlocks), tick);
452}
453
455MontagePlayer::presentImpl(const action::ActionAdvance& advance, std::vector<action::ActionTimelineEvent> events,
456 std::vector<MontageActiveBlock> activeBlocks, SimulationTick tick) {
457 if (!timeline_) return invalid<MontageAdvance>("montage has not been prepared", "montage");
458 if (!playing_) return invalid<MontageAdvance>("montage is not playing", "montage");
459 if (advance.id != executionId_)
461 DiagnosticCode::InvalidArgument, "action advance belongs to another execution", "advance.id"));
462 if (advance.totalElapsed < time_ || advance.totalElapsed > timeline_->duration)
464 Diagnostic::error(DiagnosticCode::InvalidArgument, "action advance time is outside the presentation cursor",
465 "advance.totalElapsed"));
466 if (hasLastTick_ && tick <= lastTick_)
468 Diagnostic::error(DiagnosticCode::Conflict, "montage tick must advance monotonically", "tick"));
469
471 result.previous = time_;
472 result.current = advance.totalElapsed;
473
474 if (!started_ && result.current == time_) {
475 if (const auto* section = sectionAt(time_)) activate(*section, Duration::zero());
476 }
477
478 Duration cursor = time_;
479 while (cursor < result.current) {
480 const action::ActionAnimationSection* section = sectionAt(cursor);
481 if (!section) {
482 const auto next = nextSectionStartAfter(cursor);
483 cursor = next ? std::min(*next, result.current) : result.current;
484 activeSection_ = nullptr;
485 if (gapPolicy_ == MontageGapPolicy::BindPose) player_->stop();
486 continue;
487 }
488 if (activeSection_ != section)
489 activate(*section, Duration::fromNanoseconds(cursor.nanoseconds() - section->start.nanoseconds()));
490 const Duration sliceEnd = std::min(section->end, result.current);
491 const Duration slice = Duration::fromNanoseconds(sliceEnd.nanoseconds() - cursor.nanoseconds());
492 player_->update(static_cast<float>(slice.seconds()));
493 accumulateRootMotion(result.rootMotion);
494 cursor = sliceEnd;
495 if (cursor == section->end) activeSection_ = nullptr;
496 }
497
498 result.events = std::move(events);
499 result.activeBlocks = std::move(activeBlocks);
500 result.sectionId = activeSection_ ? std::optional<LogicalId>(activeSection_->id) : std::nullopt;
501 result.completed = advance.phase == action::ActionPhase::Completed;
502 const double currentSeconds = result.current.seconds();
503 if (!timeline_->montage.defaultBlendIn.isZero()) {
504 const double t = std::clamp(currentSeconds / timeline_->montage.defaultBlendIn.seconds(), 0.0, 1.0);
505 weight_ = t * t * (3.0 - 2.0 * t);
506 } else {
507 weight_ = 1.0;
508 }
509 if (!timeline_->montage.looping && !timeline_->montage.defaultBlendOut.isZero()) {
510 const double start = timeline_->duration.seconds() - timeline_->montage.defaultBlendOut.seconds() +
511 timeline_->montage.blendOutOffset.seconds();
512 if (currentSeconds >= start) {
513 const double t =
514 std::clamp((currentSeconds - start) / timeline_->montage.defaultBlendOut.seconds(), 0.0, 1.0);
515 weight_ = std::min(weight_, 1.0 - t * t * (3.0 - 2.0 * t));
516 }
517 }
518 weight_ *= sectionEnvelopeAt(result.current);
519 result.weight = weight_;
520 // Root motion is already policy-filtered (locks / facing / rotation) by the owned AnimPlayer.
521 if (receiver_) receiver_->applyMontageRootMotion(result.rootMotion);
522
523 time_ = result.current;
524 lastTick_ = tick;
525 hasLastTick_ = true;
526 started_ = true;
527 if (result.completed) playing_ = false;
530}
531
532std::vector<action::ActionTimelineEvent> MontagePlayer::realignStateEvents(Duration target) const {
533 std::vector<action::ActionTimelineEvent> events;
534 for (const auto& track : timeline_->tracks) {
535 if (track.muted) continue;
536 for (const auto& state : track.states) {
537 const bool wasActive = time_ >= state.start && time_ < state.end;
538 const bool isActive = target >= state.start && target < state.end;
539 if (wasActive == isActive) continue;
540 events.push_back(
542 track.id, state.id, state.type, target, state.payload});
543 }
544 }
545 return events;
546}
547
548Result<std::vector<MontageActiveBlock>> MontagePlayer::activeBlocksAt(Duration target) const {
549 return timeline_->activeBlocks(target);
550}
551
554 if (!timeline_)
556 Diagnostic::error(DiagnosticCode::InvalidArgument, "montage has not been prepared", "montage"));
557 if (!playing_)
559 Diagnostic::error(DiagnosticCode::InvalidArgument, "montage is not playing", "montage"));
560 if (executionId != executionId_)
562 Diagnostic::error(DiagnosticCode::InvalidArgument, "jump belongs to another execution", "executionId"));
563 if (target < Duration::zero() || target > timeline_->duration)
565 Diagnostic::error(DiagnosticCode::InvalidArgument, "montage jump is outside the timeline", "target"));
566 if (hasLastTick_ && tick <= lastTick_)
568 Diagnostic::error(DiagnosticCode::Conflict, "montage tick must advance monotonically", "tick"));
569
571 result.previous = time_;
572 result.current = target;
573 result.events = realignStateEvents(target);
574 auto active = activeBlocksAt(target);
575 if (!active) return Result<MontageAdvance>::failure(active.status());
576 result.activeBlocks = std::move(active).takeValue();
577 player_->stop();
578 activeSection_ = nullptr;
579 if (const auto* section = sectionAt(target)) {
580 activate(*section, Duration::fromNanoseconds(target.nanoseconds() - section->start.nanoseconds()));
581 result.sectionId = section->id;
582 }
583 time_ = target;
584 lastTick_ = tick;
585 hasLastTick_ = true;
586 started_ = true;
588}
589
592 if (!timeline_) return invalid<MontageAdvance>("montage has not been prepared", "montage");
593 if (!prepared_ || sectionIndex >= prepared_->physicalSections.size())
594 return invalid<MontageAdvance>("physical section index is out of range", "sectionIndex");
595 return jumpToTime(executionId, prepared_->physicalSections[sectionIndex].first, tick);
596}
597
599 std::size_t sectionIndex, double progress,
601 if (!std::isfinite(progress) || progress < 0.0 || progress > 1.0)
602 return invalid<MontageAdvance>("physical section progress must be in [0, 1]", "progress");
603 if (!timeline_) return invalid<MontageAdvance>("montage has not been prepared", "montage");
604 if (!prepared_ || sectionIndex >= prepared_->physicalSections.size())
605 return invalid<MontageAdvance>("physical section index is out of range", "sectionIndex");
606 const auto& range = prepared_->physicalSections[sectionIndex];
607 const auto span = range.second.nanoseconds() - range.first.nanoseconds();
608 const Duration target = Duration::fromNanoseconds(range.first.nanoseconds() +
609 static_cast<std::int64_t>(std::llround(span * progress)));
611}
612
614 if (!timeline_) return invalid<std::size_t>("montage has not been prepared", "montage");
615 const auto found = std::upper_bound(prepared_->physicalSections.begin(), prepared_->physicalSections.end(), time_,
616 [](Duration value, const auto& range) { return value < range.second; });
617 const auto index = found == prepared_->physicalSections.end()
618 ? prepared_->physicalSections.size() - 1U
619 : static_cast<std::size_t>(std::distance(prepared_->physicalSections.begin(), found));
621}
622
624 if (!timeline_) return invalid<double>("montage has not been prepared", "montage");
625 if (!prepared_ || sectionIndex >= prepared_->physicalSections.size())
626 return invalid<double>("physical section index is out of range", "sectionIndex");
627 const auto& range = prepared_->physicalSections[sectionIndex];
628 const double span = static_cast<double>(range.second.nanoseconds() - range.first.nanoseconds());
629 const double elapsed = static_cast<double>(time_.nanoseconds() - range.first.nanoseconds());
630 return Result<double>::success(std::clamp(elapsed / span, 0.0, 1.0));
631}
632
634 if (!timeline_)
636 Diagnostic::error(DiagnosticCode::InvalidArgument, "montage has not been prepared", "montage"));
638 if (hasLastTick_ && tick <= lastTick_)
640 Diagnostic::error(DiagnosticCode::Conflict, "montage tick must advance monotonically", "tick"));
642 result.previous = time_;
643 result.current = time_;
644 result.completed = true;
645 for (const auto& track : timeline_->tracks) {
646 if (track.muted) continue;
647 for (const auto& state : track.states) {
648 if (time_ < state.start || time_ >= state.end) continue;
649 result.events.push_back(
650 {action::ActionTimelineEventKind::StateExit, track.id, state.id, state.type, time_, state.payload});
651 }
652 }
653 player_->stop();
654 activeSection_ = nullptr;
655 playing_ = false;
656 blendingOut_ = false;
657 weight_ = 0.0;
658 result.weight = 0.0;
659 lastTick_ = tick;
660 hasLastTick_ = true;
662}
663
665 if (duration < Duration::zero())
667 DiagnosticCode::InvalidArgument, "montage blend-out duration must be non-negative", "duration"));
668 if (!timeline_)
670 Diagnostic::error(DiagnosticCode::InvalidArgument, "montage has not been prepared", "montage"));
671 if (duration.isZero() && playing_) return interrupt(tick);
672 if (!playing_ && weight_ <= 0.0)
674 if (hasLastTick_ && tick <= lastTick_)
676 Diagnostic::error(DiagnosticCode::Conflict, "montage tick must advance monotonically", "tick"));
678 result.previous = result.current = time_;
679 result.weight = weight_;
680 if (duration.isZero()) {
681 player_->stop();
682 activeSection_ = nullptr;
683 playing_ = false;
684 blendingOut_ = false;
685 weight_ = 0.0;
686 result.weight = 0.0;
687 result.completed = true;
688 lastTick_ = tick;
689 hasLastTick_ = true;
691 }
692 for (const auto& track : timeline_->tracks) {
693 if (track.muted) continue;
694 for (const auto& state : track.states)
695 if (time_ >= state.start && time_ < state.end)
696 result.events.push_back(
697 {action::ActionTimelineEventKind::StateExit, track.id, state.id, state.type, time_, state.payload});
698 }
699 blendingOut_ = true;
700 blendOutDuration_ = duration;
701 blendOutElapsed_ = Duration::zero();
702 blendOutStartWeight_ = weight_;
703 lastTick_ = tick;
704 hasLastTick_ = true;
706}
707
709 if (!blendingOut_)
711 Diagnostic::error(DiagnosticCode::InvalidArgument, "montage is not blending out", "montage"));
712 if (delta < Duration::zero())
714 DiagnosticCode::InvalidArgument, "montage blend-out delta must be non-negative", "delta"));
715 if (tick <= lastTick_)
717 Diagnostic::error(DiagnosticCode::Conflict, "montage tick must advance monotonically", "tick"));
718 auto elapsed = blendOutElapsed_.tryAdd(delta);
719 if (!elapsed) return Result<MontageAdvance>::failure(elapsed.status());
720 blendOutElapsed_ = std::min(std::move(elapsed).takeValue(), blendOutDuration_);
721 const double t = std::clamp(blendOutElapsed_.seconds() / blendOutDuration_.seconds(), 0.0, 1.0);
722 weight_ = blendOutStartWeight_ * (1.0 - t * t * (3.0 - 2.0 * t));
724 result.previous = result.current = time_;
725 result.weight = weight_;
726 result.completed = t >= 1.0;
727 lastTick_ = tick;
728 if (result.completed) {
729 player_->stop();
730 activeSection_ = nullptr;
731 blendingOut_ = false;
732 playing_ = false;
733 }
736}
737
738AnimPose& MontagePlayer::pose() { return *player_->getPose(); }
739
740} // namespace eve::animation
double z
double y
double x
LogicalId target
Duration start
bool & active
float w
Definition AnimClip.cpp:738
float duration
eve::action::ActionExecutionId executionId
std::size_t cursor
int mask
bool applied
std::string message
glm::vec4 clip
Range range
std::vector< Track > tracks
Poco::JSON::Object::Ptr result
bool valid
Deterministic presentation-only action montage playback.
OceanWakeSettings settings
std::vector< particles::ParticleRecordEvent > events
Topology topology
std::string path
Definition PlayHost.cpp:111
std::unordered_set< std::string > loaded
Definition Plugins.cpp:24
std::string uri
Object::Ptr value
float t
bool found
double current
SimulationTick tick
Heightmap curve
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Signed, fixed-resolution simulation duration in nanoseconds.
Definition Time.h:43
constexpr std::int64_t nanoseconds() const noexcept
Return the exact signed nanosecond representation.
Definition Time.h:69
Result< Duration > tryAdd(Duration other) const
Add two durations with overflow validation.
Definition Time.cpp:31
static constexpr Duration fromNanoseconds(std::int64_t nanoseconds) noexcept
Construct an exact duration from nanoseconds.
Definition Time.h:55
static constexpr Duration zero() noexcept
Return zero duration.
Definition Time.h:60
double seconds() const noexcept
Return this duration as seconds for legacy/presentation APIs.
Definition Time.cpp:29
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
Single-clip (or cross-fading) 3D animation player. Script type: AnimPlayer.
Definition AnimPlayer.h:33
Evaluated local (and optional world) pose for an AnimSkeleton. Script type: AnimPose.
Definition AnimPose.h:17
3D bone hierarchy + bind-pose local TRS for skeletal animation. Independent of ik::Skeleton3D (FABRIK...
Synchronous ownership-transfer port used to resolve montage clip URIs.
virtual void applyMontageRootMotion(const TransformTRS &delta) noexcept=0
Consume one borrowed filtered root-motion delta.
Presentation-only montage player over an ActionTimeline.
Result< void > setSettings(action::ActionMontageSettings settings)
Apply validated montage-wide settings without rebuilding clip topology or playback time.
Result< void > replaceClip(std::string_view uri, std::unique_ptr< AnimClip > clip)
Transactionally replace one URI-backed clip and preserve the current cursor and slot weight.
Result< double > physicalSectionProgress(std::size_t sectionIndex) const
Return current normalized progress within an objective physical section.
Result< void > reloadClips(IMontageClipProvider &provider)
Transactionally reload every referenced clip while preserving playback state.
MontagePlayer(AnimSkeleton &skeleton)
Borrow a skeleton that must outlive this player.
~MontagePlayer()
Montage player.
Result< void > setSectionSplits(std::vector< Duration > splitTimestamps)
Atomically replace objective physical-section split timestamps without rebuilding clip topology.
Result< MontageAdvance > advanceBlendOut(Duration delta, SimulationTick tick)
Advance an active blend-out without advancing gameplay or montage time.
Result< MontageAdvance > jumpToTime(action::ActionExecutionId executionId, Duration target, SimulationTick tick)
Atomically realign presentation and active state blocks to an externally authoritative timestamp.
Result< MontageAdvance > jumpToSection(action::ActionExecutionId executionId, std::size_t sectionIndex, SimulationTick tick)
Jump presentation to the start of one objective physical section.
Result< void > setRootMotionPolicy(const RootMotionPolicy &policy)
Replace the canonical root-motion policy used by presentation and the owned AnimPlayer.
Result< MontageAdvance > evaluateSectionProgress(action::ActionExecutionId executionId, std::size_t sectionIndex, double progress, SimulationTick tick)
Evaluate a normalized physical-section progress and atomically realign presentation.
Result< MontageAdvance > interrupt(SimulationTick tick)
Interrupt playback and emit paired exits for every active state block.
Result< void > prepare(action::ActionTimeline timeline, std::vector< MontageClipAsset > &&clips)
Validate and atomically replace the complete montage presentation.
Result< void > play(action::ActionExecutionId executionId)
Bind presentation playback to one authoritative ActionRuntime execution.
Result< MontageAdvance > beginBlendOut(Duration duration, SimulationTick tick)
Enter continuous blend-out and emit exits for every active state block.
Result< MontageAdvance > present(const action::ActionAdvance &advance, SimulationTick tick)
Present one ActionRuntime-owned advance without advancing gameplay time locally.
AnimPose & pose()
Borrow the current evaluated pose.
void setRootMotionMask(MontageRootMotionMask mask) noexcept
Compatibility setter for axis enable bits.
Result< std::size_t > physicalSectionIndex() const
Resolve the objective physical section containing the current cursor.
void stop() noexcept
Stop playback and reset the derived cursor.
Result< void > rebindExecution(action::ActionExecutionId executionId)
Rebind an already playing presentation after its external gameplay authority is recreated.
Result< void > setRootMotionCharacterYaw(float yawRadians)
Update CharacterFacing yaw without replacing bake/lock/apply-space.
Immutable lookup topology built before a montage is published.
std::unordered_map< std::string, std::size_t > clipIndices
std::vector< std::pair< Duration, Duration > > physicalSections
std::vector< Section > sections
static constexpr StrongUint64 zero() noexcept
Returns the zero value for this strong type.
constexpr bool isZero() const noexcept
Returns whether this value is zero.
ActionBlendCurve
Built-in deterministic cross-fade curve evaluated without asset callbacks.
double evaluateActionBlendCurve(ActionBlendCurve curve, double normalized) noexcept
Evaluate a deterministic built-in blend curve for a normalized input.
RootMotionLockAxes
Per-axis translation locks for extracted root-motion deltas.
@ BindPose
Restore the skeleton bind pose on entering a gap.
eve::Result< void > validateRootMotionPolicy(const RootMotionPolicy &policy)
Validate policy fields.
constexpr bool hasLock(RootMotionLockAxes mask, RootMotionLockAxes axis) noexcept
True when mask contains the given axis bit.
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
Result payload for one deterministic advance call.
Definition Action.h:204
ActionPhase phase
Current phase after all transitions in this call.
Definition Action.h:208
Duration totalElapsed
Total simulation duration consumed by the execution.
Definition Action.h:214
std::vector< ActionTimelineEvent > timelineEvents
Owning timeline boundaries crossed by this advance.
Definition Action.h:221
std::vector< ActionActiveBlock > activeBlocks
Owning samples of timeline states active after this advance.
Definition Action.h:223
ActionExecutionId id
Execution advanced by this call.
Definition Action.h:206
Objective animation segment placed on the montage presentation lane.
Montage-wide presentation settings persisted with the action timeline.
Canonical action timeline asset shared by runtime and editor.
Result< void > validate() const
Validate ids, ranges, uniqueness and deterministic ordering.
std::vector< ActionAnimationSection > animationSections
Owning observation returned by one montage presentation step.
Compatibility-only axis enable mask for montage root motion.
Policy applied after raw root-bone delta extraction. @ownership Value type; owned by AnimPlayer or th...
float characterYaw
Yaw in radians for CharacterFacing; ignored for BoneLocal.