载入中...
搜索中...
未找到
AnimStateMachine.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <limits>
5#include <stdexcept>
6#include <utility>
12#include "animation/AnimTrail.h"
14#include "common/Capability.h"
15#include "common/Exception.h"
17#include "graphics/Graphics.h"
18
19// AnimStateMachine.cpp
20namespace eve::animation {
21namespace {
22
23std::vector<AnimStateMachine *> &machines() {
24 static std::vector<AnimStateMachine *> instances;
25 return instances;
26}
27
28double stateNumber(const StateValue &v) { return v.isInt() ? static_cast<double>(v.asInt()) : v.asDouble(); }
29
31class AnimStateProvider final : public eve::caps::IStateProvider {
32public:
33 const char *stateKind() const override { return "anim"; }
34
35 Result<Value> capture() override {
36 StateValue arr = StateValue::array();
37 for (AnimStateMachine *m : machines()) {
38 StateValue sv;
39 if (!m->captureState(sv))
40 return Result<Value>::failure(Diagnostic::error(DiagnosticCode::Failed, "animation capture failed"));
41 arr.pushBack(std::move(sv));
42 }
44 }
45
46 Result<void> restore(const Value &value) override {
47 const StateValue in = toLegacyStateValue(value);
48 if (!in.isArray()) {
50 Diagnostic::error(DiagnosticCode::InvalidArgument, "anim: expected array of state machines"));
51 }
52 const size_t n = std::min(in.arraySize(), machines().size());
53 for (size_t i = 0; i < n; ++i) {
54 std::string error;
55 if (!machines()[i]->restoreState(in.at(i), &error))
57 }
58 return Result<void>::success();
59 }
60
61 Result<void> resetToDefaults() override {
62 for (AnimStateMachine *m : machines()) {
63 if (!m->resetToDefaults())
64 return Result<void>::failure(Diagnostic::error(DiagnosticCode::Failed, "animation reset failed"));
65 }
66 return Result<void>::success();
67 }
68};
69
70struct Register {
71 Register() {
72 static AnimStateProvider provider;
73 eve::cap::addListener<eve::caps::IStateProvider>(&provider);
74 }
75} g_register;
76
77} // namespace
78
79AnimStateMachine::AnimStateMachine(AnimSkeleton *skeleton) : skeleton_(skeleton) {
80 if (!skeleton_) throw Exception("AnimStateMachine: skeleton is null");
81 pose_.resize(skeleton_->getBoneCount());
82 fromPose_.resize(skeleton_->getBoneCount());
83 toPose_.resize(skeleton_->getBoneCount());
84 skeleton_->applyBindPose(&pose_);
85 machines().push_back(this);
86}
87
89 machines().erase(std::remove(machines().begin(), machines().end(), this), machines().end());
90}
91
92void AnimStateMachine::requireState(const std::string &name) const {
93 if (states_.find(name) == states_.end()) {
94 throw Exception("AnimStateMachine: unknown state '%s'", name.c_str());
95 }
96}
97
98AnimStateMachine::Transition &AnimStateMachine::requireTransition(int id) {
99 if (id < 0 || id >= static_cast<int>(transitions_.size())) {
100 throw Exception("AnimStateMachine: invalid transition id %d", id);
101 }
102 return transitions_[static_cast<size_t>(id)];
103}
104
105AnimStateMachine::FloatOp AnimStateMachine::parseFloatOp(const std::string &op) {
106 if (op == ">") return FloatOp::Gt;
107 if (op == ">=") return FloatOp::Ge;
108 if (op == "<") return FloatOp::Lt;
109 if (op == "<=") return FloatOp::Le;
110 if (op == "==") return FloatOp::Eq;
111 if (op == "!=") return FloatOp::Ne;
112 throw Exception("AnimStateMachine: unknown float op '%s'", op.c_str());
113}
114
115void AnimStateMachine::addState(const std::string &name, AnimClip *clip) {
116 if (name.empty()) throw Exception("AnimStateMachine.addState: name empty");
117 if (!clip) throw Exception("AnimStateMachine.addState: clip is null");
118 if (states_.count(name)) {
119 throw Exception("AnimStateMachine.addState: duplicate state '%s'", name.c_str());
120 }
121 states_[name] = State{name, clip};
122 stateOrder_.push_back(name);
123}
124
125void AnimStateMachine::setEntry(const std::string &name) {
126 requireState(name);
127 currentState_ = name;
128 stateTime_ = 0.f;
129 blending_ = false;
130 started_ = true;
131 states_[name].clip->sample(0.f, &pose_, skeleton_);
132}
133
134bool AnimStateMachine::hasState(const std::string &name) const { return states_.count(name) > 0; }
135
136int AnimStateMachine::addTransition(const std::string &from, const std::string &to, float blendSeconds) {
137 requireState(from);
138 requireState(to);
139 if (blendSeconds < 0.f) {
140 throw Exception("AnimStateMachine.addTransition: blendSeconds must be >= 0");
141 }
142 Transition tr;
143 tr.from = from;
144 tr.to = to;
145 tr.blendSeconds = blendSeconds;
146 transitions_.push_back(tr);
147 return static_cast<int>(transitions_.size()) - 1;
148}
149
150void AnimStateMachine::addFloatCondition(int transitionId, const std::string &param, const std::string &op,
151 float threshold) {
152 if (param.empty()) throw Exception("AnimStateMachine.addFloatCondition: param empty");
153 Transition &tr = requireTransition(transitionId);
154 Condition c;
155 c.kind = CondKind::Float;
156 c.param = param;
157 c.op = parseFloatOp(op);
158 c.threshold = threshold;
159 tr.conditions.push_back(c);
160 floats_.emplace(param, 0.f);
161}
162
163void AnimStateMachine::addBoolCondition(int transitionId, const std::string &param, bool value) {
164 if (param.empty()) throw Exception("AnimStateMachine.addBoolCondition: param empty");
165 Transition &tr = requireTransition(transitionId);
166 Condition c;
167 c.kind = CondKind::Bool;
168 c.param = param;
169 c.boolValue = value;
170 tr.conditions.push_back(c);
171 bools_.emplace(param, false);
172}
173
174void AnimStateMachine::addTriggerCondition(int transitionId, const std::string &param) {
175 if (param.empty()) throw Exception("AnimStateMachine.addTriggerCondition: param empty");
176 Transition &tr = requireTransition(transitionId);
177 Condition c;
178 c.kind = CondKind::Trigger;
179 c.param = param;
180 tr.conditions.push_back(c);
181 triggers_.emplace(param, false);
182}
183
184void AnimStateMachine::setExitTime(int transitionId, float normalizedTime) {
185 Transition &tr = requireTransition(transitionId);
186 tr.exitTime = clampf(normalizedTime, 0.f, 1.f);
187 tr.hasExitTime = true;
188}
189
190void AnimStateMachine::setHasExitTime(int transitionId, bool enabled) {
191 requireTransition(transitionId).hasExitTime = enabled;
192}
193
194void AnimStateMachine::setFloat(const std::string &name, float value) { floats_[name] = value; }
195
196float AnimStateMachine::getFloat(const std::string &name) const {
197 auto it = floats_.find(name);
198 return it == floats_.end() ? 0.f : it->second;
199}
200
201void AnimStateMachine::setBool(const std::string &name, bool value) { bools_[name] = value; }
202
203bool AnimStateMachine::getBool(const std::string &name) const {
204 auto it = bools_.find(name);
205 return it == bools_.end() ? false : it->second;
206}
207
208void AnimStateMachine::setTrigger(const std::string &name) { triggers_[name] = true; }
209
210void AnimStateMachine::resetTrigger(const std::string &name) { triggers_[name] = false; }
211
213
214bool AnimStateMachine::conditionsMet(const Transition &tr) const {
215 for (const Condition &c : tr.conditions) {
216 switch (c.kind) {
217 case CondKind::Float: {
218 const float v = getFloat(c.param);
219 bool ok = false;
220 switch (c.op) {
221 case FloatOp::Gt: ok = v > c.threshold; break;
222 case FloatOp::Ge: ok = v >= c.threshold; break;
223 case FloatOp::Lt: ok = v < c.threshold; break;
224 case FloatOp::Le: ok = v <= c.threshold; break;
225 case FloatOp::Eq: ok = std::fabs(v - c.threshold) < 1e-5f; break;
226 case FloatOp::Ne: ok = std::fabs(v - c.threshold) >= 1e-5f; break;
227 }
228 if (!ok) return false;
229 break;
230 }
231 case CondKind::Bool: {
232 if (getBool(c.param) != c.boolValue) return false;
233 break;
234 }
235 case CondKind::Trigger: {
236 auto it = triggers_.find(c.param);
237 if (it == triggers_.end() || !it->second) return false;
238 break;
239 }
240 }
241 }
242 return true;
243}
244
245bool AnimStateMachine::tryTransition() {
246 if (currentState_.empty() || blending_) return false;
247 const State &cur = states_.at(currentState_);
248 const float dur = cur.clip ? cur.clip->getDuration() : 0.f;
249 const float norm = dur > 1e-8f ? clampf(stateTime_ / dur, 0.f, 1.f) : 1.f;
250
251 for (const Transition &tr : transitions_) {
252 if (tr.from != currentState_) continue;
253 if (tr.hasExitTime && norm < tr.exitTime) continue;
254 if (!conditionsMet(tr)) continue;
255
256 // Consume triggers used by this transition.
257 for (const Condition &c : tr.conditions) {
258 if (c.kind == CondKind::Trigger) triggers_[c.param] = false;
259 }
260
261 nextState_ = tr.to;
262 blendDuration_ = tr.blendSeconds;
263 blendElapsed_ = 0.f;
264 stateTime_ = 0.f;
265 if (blendDuration_ <= 1e-6f) {
266 currentState_ = nextState_;
267 blending_ = false;
268 states_.at(currentState_).clip->sample(0.f, &pose_, skeleton_);
269 } else {
270 // Switch logical state immediately; pose cross-fades from previous.
271 fromPose_.copyFrom(&pose_);
272 currentState_ = nextState_;
273 blending_ = true;
274 states_.at(currentState_).clip->sample(0.f, &toPose_, skeleton_);
275 pose_.blendFrom(&fromPose_, &toPose_, 0.f);
276 }
277 return true;
278 }
279 return false;
280}
281
282void AnimStateMachine::updateUnchecked(float dt) {
283 if (dt < 0.f) throw Exception("AnimStateMachine.update: dt must be >= 0");
284 if (!started_) {
285 if (!stateOrder_.empty())
286 setEntry(stateOrder_.front());
287 else
288 return;
289 }
290 if (currentState_.empty()) return;
291
292 if (blending_) {
293 blendElapsed_ += dt;
294 stateTime_ += dt;
295 const State &dst = states_.at(currentState_);
296 dst.clip->sample(stateTime_, &toPose_, skeleton_);
297 float t = blendDuration_ > 1e-8f ? blendElapsed_ / blendDuration_ : 1.f;
298 if (t >= 1.f) {
299 blending_ = false;
300 pose_.copyFrom(&toPose_);
301 } else {
302 // Keep fromPose frozen at transition start for stable crossfade.
303 pose_.blendFrom(&fromPose_, &toPose_, t);
304 }
305 // Allow chained transitions after blend completes next frame.
306 if (!blending_) tryTransition();
307 return;
308 }
309
310 stateTime_ += dt;
311 const State &st = states_.at(currentState_);
312 st.clip->sample(stateTime_, &pose_, skeleton_);
313 tryTransition();
314}
315
317 if (step.delta.nanoseconds() < 0)
319 "animation state-machine delta must be non-negative"));
320 if (hasLastTick_ && step.tick <= lastTick_)
322 eve::DiagnosticCode::Conflict, "animation state-machine tick must advance monotonically"));
323
324 const float dt = static_cast<float>(step.delta.seconds());
325 if (!std::isfinite(dt))
327 eve::DiagnosticCode::InvalidArgument, "animation state-machine delta is outside float range"));
328 updateUnchecked(dt);
329 lastTick_ = step.tick;
330 hasLastTick_ = true;
332}
333
336 if (!duration) {
337 duration.ignore("legacy animation state-machine update received an invalid duration");
338 return;
339 }
340 auto nextTick = hasLastTick_ ? lastTick_.incremented() : std::optional<eve::SimulationTick>(eve::SimulationTick(1));
341 if (!nextTick) {
343 "animation state-machine simulation tick overflow"))
344 .ignore("legacy animation state-machine update tick overflow");
345 return;
346 }
347 advance({*nextTick, std::move(duration).takeValue()}).ignore("legacy animation state-machine update facade");
348}
349
352 out.set("currentState", StateValue::string(currentState_));
353 out.set("nextState", StateValue::string(nextState_));
354 out.set("stateTime", StateValue::number(stateTime_));
355 out.set("blendDuration", StateValue::number(blendDuration_));
356 out.set("blendElapsed", StateValue::number(blendElapsed_));
357 out.set("blending", StateValue::boolean(blending_));
358 out.set("started", StateValue::boolean(started_));
359 out.set("hasSimulationTick", StateValue::boolean(hasLastTick_));
360 out.set("simulationTick", StateValue::string(std::to_string(lastTick_.value())));
361
363 for (const auto &kv : floats_) floats.set(kv.first, StateValue::number(kv.second));
364 out.set("floats", std::move(floats));
365
367 for (const auto &kv : bools_) bools.set(kv.first, StateValue::boolean(kv.second));
368 out.set("bools", std::move(bools));
369
370 StateValue triggers = StateValue::object();
371 for (const auto &kv : triggers_) triggers.set(kv.first, StateValue::boolean(kv.second));
372 out.set("triggers", std::move(triggers));
373 return true;
374}
375
376bool AnimStateMachine::restoreState(const StateValue &in, std::string *err) {
377 if (!in.isObject()) {
378 if (err) *err = "anim: state is not an object";
379 return false;
380 }
381 const StateValue *current = in.find("currentState");
382 const StateValue *started = in.find("started");
383 if (!current || !current->isString() || !started || !started->isBool()) {
384 if (err) *err = "anim: missing currentState/started";
385 return false;
386 }
387 const std::string stateName = current->asString();
388 const bool wasStarted = started->asBool();
389 if (wasStarted && !stateName.empty() && !hasState(stateName)) {
390 if (err) *err = "anim: unknown state '" + stateName + "'";
391 return false;
392 }
393
395 bool restoredHasTick = false;
396 if (const StateValue *hasTick = in.find("hasSimulationTick"); hasTick && hasTick->isBool())
397 restoredHasTick = hasTick->asBool();
398 if (restoredHasTick) {
399 const StateValue *tick = in.find("simulationTick");
400 if (!tick || !tick->isString()) {
401 if (err) *err = "anim: missing simulationTick";
402 return false;
403 }
404 try {
405 std::size_t parsed = 0;
406 const std::uint64_t value = std::stoull(tick->asString(), &parsed);
407 if (parsed != tick->asString().size()) throw std::invalid_argument("trailing characters");
408 restoredTick = eve::SimulationTick(value);
409 } catch (...) {
410 if (err) *err = "anim: invalid simulationTick";
411 return false;
412 }
413 }
414
415 floats_.clear();
416 bools_.clear();
417 triggers_.clear();
418
419 if (const StateValue *floats = in.find("floats"); floats && floats->isObject()) {
420 for (const auto &key : floats->keys()) {
421 const StateValue *v = floats->find(key);
422 if (v && (v->isInt() || v->isFloat())) floats_[key] = static_cast<float>(stateNumber(*v));
423 }
424 }
425 if (const StateValue *bools = in.find("bools"); bools && bools->isObject()) {
426 for (const auto &key : bools->keys()) {
427 const StateValue *v = bools->find(key);
428 if (v && v->isBool()) bools_[key] = v->asBool();
429 }
430 }
431 if (const StateValue *triggers = in.find("triggers"); triggers && triggers->isObject()) {
432 for (const auto &key : triggers->keys()) {
433 const StateValue *v = triggers->find(key);
434 if (v && v->isBool()) triggers_[key] = v->asBool();
435 }
436 }
437
438 currentState_ = stateName;
439 if (const StateValue *ns = in.find("nextState"); ns && ns->isString()) nextState_ = ns->asString();
440 if (const StateValue *st = in.find("stateTime"); st && (st->isInt() || st->isFloat()))
441 stateTime_ = static_cast<float>(stateNumber(*st));
442 if (const StateValue *bd = in.find("blendDuration"); bd && (bd->isInt() || bd->isFloat()))
443 blendDuration_ = static_cast<float>(stateNumber(*bd));
444 if (const StateValue *be = in.find("blendElapsed"); be && (be->isInt() || be->isFloat()))
445 blendElapsed_ = static_cast<float>(stateNumber(*be));
446 if (const StateValue *bl = in.find("blending"); bl && bl->isBool()) blending_ = bl->asBool();
447 started_ = wasStarted;
448 lastTick_ = restoredTick;
449 hasLastTick_ = restoredHasTick;
450
451 if (started_ && !currentState_.empty()) {
452 states_.at(currentState_).clip->sample(stateTime_, &pose_, skeleton_);
453 }
454 return true;
455}
456
458 floats_.clear();
459 bools_.clear();
460 triggers_.clear();
461 blending_ = false;
462 nextState_.clear();
463 stateTime_ = 0.f;
464 blendDuration_ = 0.f;
465 blendElapsed_ = 0.f;
466 lastTick_ = eve::SimulationTick::zero();
467 hasLastTick_ = false;
468 if (!stateOrder_.empty()) {
469 setEntry(stateOrder_.front());
470 return true;
471 }
472 started_ = false;
473 currentState_.clear();
474 return true;
475}
476
477} // namespace eve::animation
478
479// AnimSyncGroup.cpp
480namespace eve::animation {
481
482void AnimSyncGroup::addPlayer(AnimPlayer *player, float phaseOffset) {
483 if (!player) throw Exception("AnimSyncGroup.addPlayer: player is null");
484 entries_.push_back({player, phaseOffset});
485}
486
488 if (index < 0 || index >= getCount()) throw Exception("AnimSyncGroup.setLeader: invalid index %d", index);
489 leader_ = index;
490}
491
493 auto seconds = detail::secondsForStep(step, hasLastTick_, lastTick_, "AnimSyncGroup");
494 if (!seconds) return eve::Result<void>::failure(seconds.status());
495 (void)std::move(seconds).takeValue();
496 usedMarkerSync_ = false;
497 if (entries_.empty()) {
498 lastTick_ = step.tick;
499 hasLastTick_ = true;
501 }
502 for (const Entry &entry : entries_) {
503 if (entry.player->hasCurrentTick() && step.tick <= entry.player->currentTick())
505 eve::DiagnosticCode::Conflict, "animation sync-group player already consumed this tick"));
506 }
507 Entry &leader = entries_[static_cast<size_t>(leader_)];
508 auto leaderResult = leader.player->advance(step);
509 if (!leaderResult) return eve::Result<void>::failure(leaderResult.status());
510 AnimClip *leaderClip = leader.player->getClip();
511 if (!leaderClip || leaderClip->getDuration() <= 1e-8f) {
512 lastTick_ = step.tick;
513 hasLastTick_ = true;
515 }
516 phase_ = leaderClip->wrapTime(leader.player->getTime()) / leaderClip->getDuration();
517 for (int i = 0; i < getCount(); ++i) {
518 if (i == leader_) continue;
519 AnimPlayer *player = entries_[static_cast<size_t>(i)].player;
520 auto playerResult = player->advance(step);
521 if (!playerResult) return eve::Result<void>::failure(playerResult.status());
522 AnimClip *clip = player->getClip();
523 if (!clip || clip->getDuration() <= 1e-8f) continue;
524 float mappedTime;
525 if (leaderClip->hasCompatibleSyncMarkers(clip)) {
526 mappedTime = leaderClip->mapSyncTimeTo(leader.player->getTime(), clip);
527 usedMarkerSync_ = true;
528 } else {
529 mappedTime = phase_ * clip->getDuration();
530 }
531 mappedTime += entries_[static_cast<size_t>(i)].phaseOffset * clip->getDuration();
532 player->setTime(clip->wrapTime(mappedTime));
533 }
534 lastTick_ = step.tick;
535 hasLastTick_ = true;
537}
538
540 auto step = detail::legacyStep(dt, hasLastTick_, lastTick_, "AnimSyncGroup");
541 if (!step) {
542 step.ignore("legacy AnimSyncGroup update");
543 return;
544 }
545 advance(std::move(step).takeValue()).ignore("legacy AnimSyncGroup update");
546}
547
548} // namespace eve::animation
549
550// AnimTrail.cpp
551namespace eve::animation {
552
553// Color lives in eve::graphics (see graphics/Canvas.h); keep the unqualified form.
555
557
559 if (capacity < 2) throw Exception("AnimTrail.setCapacity: capacity must be >= 2");
560 capacity_ = capacity;
561 while (static_cast<int>(points_.size()) > capacity_) {
562 points_.erase(points_.begin());
563 }
564}
565
566void AnimTrail::setDuration(float seconds) { duration_ = seconds; }
567
569 if (distance < 0.f) throw Exception("AnimTrail.setMinDistance: must be >= 0");
570 minDistance_ = distance;
571}
572
574 if (pixels <= 0.f) throw Exception("AnimTrail.setWidth: must be > 0");
575 width_ = pixels;
576}
577
578void AnimTrail::setColor(float r, float g, float b, float a) {
579 colorR_ = r;
580 colorG_ = g;
581 colorB_ = b;
582 colorA_ = a;
583}
584
585void AnimTrail::setFade(bool enable) { fade_ = enable; }
586
587void AnimTrail::setStyle(const std::string &style) {
588 if (style == "line") {
589 style_ = Style::Line;
590 return;
591 }
592 if (style == "points") {
593 style_ = Style::Points;
594 return;
595 }
596 throw Exception("AnimTrail.setStyle: unknown style '%s' (use line|points)", style.c_str());
597}
598
599std::string AnimTrail::getStyle() const { return style_ == Style::Line ? "line" : "points"; }
600
601void AnimTrail::setDrawScale(float sx, float sy) {
602 drawScaleX_ = sx;
603 drawScaleY_ = sy;
604}
605
606void AnimTrail::setDrawOffset(float ox, float oy) {
607 drawOffsetX_ = ox;
608 drawOffsetY_ = oy;
609}
610
611void AnimTrail::addPoint(float x, float y) { pushPoint(x, y, 0.f); }
612
613void AnimTrail::addPoint3(float x, float y, float z) { pushPoint(x, y, z); }
614
615void AnimTrail::projectPlane(float x, float y, float z, const std::string &plane, float *outX, float *outY) const {
616 if (!outX || !outY) return;
617 if (plane == "xy" || plane.empty()) {
618 *outX = x;
619 *outY = y;
620 return;
621 }
622 if (plane == "xz") {
623 *outX = x;
624 *outY = z;
625 return;
626 }
627 if (plane == "yz") {
628 *outX = y;
629 *outY = z;
630 return;
631 }
632 throw Exception("AnimTrail: unknown plane '%s' (use xy|xz|yz)", plane.c_str());
633}
634
635void AnimTrail::sampleBone(const AnimPose *pose, int boneIndex, const std::string &plane) {
636 sampleBoneOffset(pose, boneIndex, 0.f, 0.f, 0.f, plane);
637}
638
639void AnimTrail::sampleBoneOffset(const AnimPose *pose, int boneIndex, float ox, float oy, float oz,
640 const std::string &plane) {
641 if (!pose) throw Exception("AnimTrail.sampleBone: pose is null");
642 if (boneIndex < 0 || boneIndex >= pose->getBoneCount()) {
643 throw Exception("AnimTrail.sampleBone: boneIndex %d out of range (count=%d)", boneIndex, pose->getBoneCount());
644 }
645 const float wx = pose->getWorldPositionX(boneIndex) + ox;
646 const float wy = pose->getWorldPositionY(boneIndex) + oy;
647 const float wz = pose->getWorldPositionZ(boneIndex) + oz;
648 float px = 0.f, py = 0.f;
649 projectPlane(wx, wy, wz, plane, &px, &py);
650 pushPoint(px, py, plane == "xy" || plane.empty() ? wz : (plane == "xz" ? wy : wx));
651}
652
653void AnimTrail::pushPoint(float x, float y, float z) {
654 if (!points_.empty() && minDistance_ > 0.f) {
655 const Point &last = points_.back();
656 const float dx = x - last.x;
657 const float dy = y - last.y;
658 const float dz = z - last.z;
659 if (dx * dx + dy * dy + dz * dz < minDistance_ * minDistance_) return;
660 }
661 Point p;
662 p.x = x;
663 p.y = y;
664 p.z = z;
665 p.age = 0.f;
666 points_.push_back(p);
667 while (static_cast<int>(points_.size()) > capacity_) {
668 points_.erase(points_.begin());
669 }
670}
671
672void AnimTrail::clear() { points_.clear(); }
673
674void AnimTrail::updateUnchecked(float dt) {
675 if (dt < 0.f) dt = 0.f;
676 for (Point &p : points_) p.age += dt;
677 if (duration_ > 0.f) {
678 auto it = points_.begin();
679 while (it != points_.end()) {
680 if (it->age > duration_) {
681 it = points_.erase(it);
682 } else {
683 ++it;
684 }
685 }
686 }
687}
688
690 auto seconds = detail::secondsForStep(step, hasLastTick_, lastTick_, "AnimTrail");
691 if (!seconds) return eve::Result<void>::failure(seconds.status());
692 updateUnchecked(std::move(seconds).takeValue());
693 lastTick_ = step.tick;
694 hasLastTick_ = true;
696}
697
699 auto step = detail::legacyStep(dt, hasLastTick_, lastTick_, "AnimTrail");
700 if (!step) {
701 step.ignore("legacy AnimTrail update");
702 return;
703 }
704 advance(std::move(step).takeValue()).ignore("legacy AnimTrail update");
705}
706
707void AnimTrail::requireIndex(int index) const {
708 if (index < 0 || index >= getPointCount()) {
709 throw Exception("AnimTrail: point index %d out of range (count=%d)", index, getPointCount());
710 }
711}
712
713float AnimTrail::getPointX(int index) const {
714 requireIndex(index);
715 return points_[static_cast<size_t>(index)].x;
716}
717
718float AnimTrail::getPointY(int index) const {
719 requireIndex(index);
720 return points_[static_cast<size_t>(index)].y;
721}
722
723float AnimTrail::getPointZ(int index) const {
724 requireIndex(index);
725 return points_[static_cast<size_t>(index)].z;
726}
727
729 requireIndex(index);
730 return points_[static_cast<size_t>(index)].age;
731}
732
733float AnimTrail::alphaFor(const Point &p) const {
734 if (!fade_ || duration_ <= 0.f) return colorA_;
735 const float t = 1.f - std::min(1.f, p.age / duration_);
736 return colorA_ * t;
737}
738
740 requireIndex(index);
741 return alphaFor(points_[static_cast<size_t>(index)]);
742}
743
744void AnimTrail::toScreen(float x, float y, float *sx, float *sy) const {
745 if (!sx || !sy) return;
746 *sx = x * drawScaleX_ + drawOffsetX_;
747 *sy = y * drawScaleY_ + drawOffsetY_;
748}
749
750void AnimTrail::drawDot(graphics::Graphics *gfx, float x, float y, float alpha) const {
751 if (!gfx || alpha <= 0.f) return;
752 float sx = 0.f, sy = 0.f;
753 toScreen(x, y, &sx, &sy);
754 const float half = width_ * 0.5f;
755 gfx->drawSolidRect(sx - half, sy - half, width_, width_, Color(colorR_, colorG_, colorB_, alpha));
756}
757
758void AnimTrail::drawSegment(graphics::Graphics *gfx, float x0, float y0, float x1, float y1, float a0, float a1) const {
759 if (!gfx) return;
760 float sx0 = 0.f, sy0 = 0.f, sx1 = 0.f, sy1 = 0.f;
761 toScreen(x0, y0, &sx0, &sy0);
762 toScreen(x1, y1, &sx1, &sy1);
763 const float dx = sx1 - sx0;
764 const float dy = sy1 - sy0;
765 const float len = std::sqrt(dx * dx + dy * dy);
766 if (len < 1e-4f) {
767 drawDot(gfx, x1, y1, a1);
768 return;
769 }
770 const float step = std::max(1.f, width_ * 0.75f);
771 const int steps = std::max(1, int(len / step));
772 const float half = width_ * 0.5f;
773 for (int i = 0; i <= steps; ++i) {
774 const float t = float(i) / float(steps);
775 const float a = a0 + (a1 - a0) * t;
776 if (a <= 0.f) continue;
777 const float px = sx0 + dx * t;
778 const float py = sy0 + dy * t;
779 gfx->drawSolidRect(px - half, py - half, width_, width_, Color(colorR_, colorG_, colorB_, a));
780 }
781}
782
784 if (!gfx || points_.empty()) return;
785
786 if (style_ == Style::Points) {
787 for (const Point &p : points_) {
788 drawDot(gfx, p.x, p.y, alphaFor(p));
789 }
790 return;
791 }
792
793 // Line: connect oldest → newest with per-vertex fade.
794 for (size_t i = 1; i < points_.size(); ++i) {
795 const Point &a = points_[i - 1];
796 const Point &b = points_[i];
797 drawSegment(gfx, a.x, a.y, b.x, b.y, alphaFor(a), alphaFor(b));
798 }
799 // Emphasize the head.
800 if (!points_.empty()) {
801 const Point &head = points_.back();
802 drawDot(gfx, head.x, head.y, alphaFor(head));
803 }
804}
805
806} // namespace eve::animation
double z
double y
double m[16]
double x
float duration
eve::EntitySpatialPose pose
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
tensor::Graph g
Definition GpuGraph.cpp:7
std::uint32_t capacity
glm::vec4 clip
glm::vec3 n
Definition Grass.cpp:63
double r
float v
std::int32_t c
std::vector< Colorf > px
std::string to
std::string from
std::string id
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
float tr
ScriptMotionSinkStore< ScriptMotionFloatSink > floats
glm::dvec3 dx
glm::dvec3 dz
double dt
std::string error
Definition Package.cpp:174
Object::Ptr value
int steps
float t
uint8_t * pixels
ScriptStructure out
size_t begin
size_t end
double current
float dy
Definition Shadow.cpp:151
SimulationTick tick
float step
Definition TreeMesh.cpp:451
float size
Definition TreeMesh.cpp:158
uint32_t index
double oy
double ox
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static Result< Duration > fromSeconds(double seconds)
Convert finite seconds to the nearest nanosecond.
Definition Time.cpp:17
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
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Definition Result.h:424
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
JSON-compatible state value tree used by state hot reload.
Definition StateValue.h:30
static StateValue object()
Empty object.
Definition StateValue.h:50
static StateValue boolean(bool v)
Boolean value.
static StateValue array()
Empty array.
Definition StateValue.h:48
bool isString() const
Definition StateValue.h:59
bool isBool() const
Definition StateValue.h:58
bool isObject() const
Definition StateValue.h:60
static StateValue number(double v)
Floating-point value.
const StateValue * find(const std::string &key) const
Look up key; nullptr when absent.
static StateValue string(std::string v)
String value.
void set(const std::string &key, StateValue v)
Insert or replace key; only valid on objects.
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 hasCompatibleSyncMarkers(const AnimClip *target) const
Whether this clip and target share a usable ordered marker interval.
Definition AnimClip.cpp:252
float mapSyncTimeTo(float time, const AnimClip *target) const
Map local time into target marker space, falling back to normalized duration.
Definition AnimClip.cpp:280
float wrapTime(float time) const
Wrap or clamp time according to loop flag.
Definition AnimClip.cpp:471
Single-clip (or cross-fading) 3D animation player. Script type: AnimPlayer.
Definition AnimPlayer.h:33
eve::Result< void > advance(const eve::SimulationStep &step) override
Advance playback and sample into internal pose.
void setTime(float seconds)
Sets the time.
AnimClip * getClip() const
Borrow the selected clip, or null if none is selected. The caller owns the clip and must keep it aliv...
Definition AnimPlayer.h:89
Evaluated local (and optional world) pose for an AnimSkeleton. Script type: AnimPose.
Definition AnimPose.h:17
void blendFrom(const AnimPose *a, const AnimPose *b, float t)
Blend from.
Definition AnimPose.cpp:101
void copyFrom(const AnimPose *other)
Copies from.
Definition AnimPose.cpp:95
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.
void setHasExitTime(int transitionId, bool enabled)
Sets the has exit time.
float getFloat(const std::string &name) const
Returns the float.
int addTransition(const std::string &from, const std::string &to, float blendSeconds)
Add transition from → to with blend duration.
void addTriggerCondition(int transitionId, const std::string &param)
Adds trigger condition.
bool captureState(StateValue &out) const
Serialize runtime state (params, current/next state, blend).
void update(float dt)
Legacy seconds facade retained for scripts and old callers.
bool hasState(const std::string &name) const
True when state.
AnimStateMachine(AnimSkeleton *skeleton)
Anim state machine.
void resetTrigger(const std::string &name)
Resets trigger.
void addBoolCondition(int transitionId, const std::string &param, bool value)
Adds bool condition.
void setTrigger(const std::string &name)
Sets the trigger.
void addFloatCondition(int transitionId, const std::string &param, const std::string &op, float threshold)
Comparison op: ">", ">=", "<", "<=", "==", "!=".
void setBool(const std::string &name, bool value)
Sets the bool.
void setFloat(const std::string &name, float value)
Sets the float.
bool restoreState(const StateValue &in, std::string *err=nullptr)
Restore runtime state captured by captureState().
void addState(const std::string &name, AnimClip *clip)
Adds state.
bool getBool(const std::string &name) const
Returns the bool.
~AnimStateMachine() override
Anim state machine.
AnimPose * getPose() override
Borrowed pointer accessor. @ownership Borrowed @lifetime Valid while the owning animation object rema...
eve::Result< void > advance(const eve::SimulationStep &step) override
Advance state and pose using one scheduler-owned deterministic step.
void setEntry(const std::string &name)
Sets the entry.
void setExitTime(int transitionId, float normalizedTime)
Optional: require normalized local time in [0,1] >= exitTime before transition.
bool resetToDefaults()
Clear params and re-seat the entry state (restore fallback).
eve::Result< void > advance(const eve::SimulationStep &step)
Advance and synchronize all players using one scheduler step.
void update(float dt)
Legacy seconds facade; explicitly forwards to advance().
void setLeader(int index)
Sets the leader.
int getCount() const
Returns the count.
void addPlayer(AnimPlayer *player, float phaseOffset=0.f)
Adds player.
std::string getStyle() const
Returns the style.
void setDuration(float seconds)
How long each sample lives (seconds). <= 0 keeps until capacity eviction.
void setCapacity(int capacity)
Max retained samples (ring). Clamped to >= 2.
void setWidth(float pixels)
Sets the width.
void update(float dt)
Legacy seconds facade; explicitly forwards to advance().
void addPoint3(float x, float y, float z)
Append a 3D sample (draw uses set plane / first two mapped axes via sampleBone).
void setDrawOffset(float ox, float oy)
Sets the draw offset.
int getPointCount() const
Returns the point count.
Definition AnimTrail.h:125
void setMinDistance(float distance)
Skip new samples closer than this distance to the newest point (0 = always add).
void draw(graphics::Graphics *gfx)
Draw trajectory in 2D pixel/world space via Graphics.
void setColor(float r, float g, float b, float a=1.f)
Head (newest) color; alpha fades toward 0 along the trail when fade is on.
float getPointZ(int index) const
Returns the point z.
void sampleBone(const AnimPose *pose, int boneIndex, const std::string &plane="xy")
Sample bone world position after pose->computeWorld. plane maps axes to draw (x,y): "xy" | "xz" | "yz...
eve::Result< void > advance(const eve::SimulationStep &step)
Age samples by one scheduler-owned deterministic step.
void setStyle(const std::string &style)
"line" | "points". Invalid → exception.
void setFade(bool enable)
Sets the fade.
float getPointAlpha(int index) const
Effective draw alpha in [0, colorA] after fade.
float getPointX(int index) const
Index 0 = oldest retained sample; count-1 = newest.
void setDrawScale(float sx, float sy)
Applied at draw time: screen = (x,y) * scale + offset. Useful when sampling bone world units into pix...
float getPointY(int index) const
Returns the point y.
float getPointAge(int index) const
Returns the point age.
void sampleBoneOffset(const AnimPose *pose, int boneIndex, float ox, float oy, float oz, const std::string &plane="xy")
Sample bone offset.
void addPoint(float x, float y)
Append a 2D sample (z stored as 0).
AnimTrail(int capacity=64)
Anim trail.
Runtime-state serialization for state hot reload.
constexpr std::optional< StrongUint64 > incremented() const noexcept
Returns the next value, or empty instead of unsigned wraparound.
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
static constexpr StrongUint64 zero() noexcept
Returns the zero value for this strong type.
virtual void drawSolidRect(float x, float y, float w, float h, float r, float g, float b, float a=1.f)
RGBA-float overload matching the script-facing drawSolidRect name.
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.
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.
constexpr float clampf(float v, float lo, float hi) noexcept
Clampf.
Definition AnimMath.h:34
WGPUStringView sv(const char *s)
Build a WGPUStringView from a C string (null-safe, length auto-computed).
Definition wgpu_types.h:20
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
State
Lifecycle state of a generic transaction plan.
StateValue toLegacyStateValue(const Value &value)
Project a canonical value into the legacy reload snapshot format.
Value toCanonicalStateValue(const StateValue &value)
Copy a legacy reload tree into the canonical owning value protocol.
glm::vec4 Color
Render-neutral RGBA color shared by graphics-facing modules.
Definition RenderTypes.h:8
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31
bool enabled
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
bool started
Definition Graphics.cpp:200