载入中...
搜索中...
未找到
ControlAnim.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
7#include "common/Exception.h"
8
9// ControlAnim.cpp
10namespace eve::animation {
11
12ControlAnim::ControlAnim(float frequencyHz, float dampingZeta, float response)
13 : frequencyHz_(frequencyHz), dampingZeta_(dampingZeta), response_(response) {
14 refreshCoeffs();
15}
16
17void ControlAnim::setFrequency(float frequencyHz) {
18 frequencyHz_ = frequencyHz;
19 refreshCoeffs();
20}
21
22void ControlAnim::setDamping(float dampingZeta) {
23 dampingZeta_ = dampingZeta;
24 refreshCoeffs();
25}
26
28 response_ = response;
29 refreshCoeffs();
30}
31
32void ControlAnim::setIntegrator(const std::string &kind) {
33 if (kind == "secondOrder") {
34 integrator_ = Integrator::SecondOrder;
35 } else if (kind == "spring") {
36 integrator_ = Integrator::Spring;
37 } else if (kind == "pd") {
38 integrator_ = Integrator::Pd;
39 } else {
40 throw Exception("ControlAnim::setIntegrator: unknown kind '%s' (expected secondOrder|spring|pd)", kind.c_str());
41 }
42}
43
44std::string ControlAnim::getIntegrator() const {
45 switch (integrator_) {
46 case Integrator::SecondOrder: return "secondOrder";
47 case Integrator::Spring: return "spring";
48 case Integrator::Pd: return "pd";
49 }
50 return "secondOrder";
51}
52
53void ControlAnim::refreshCoeffs() {
54 coeffs_ = makeSecondOrderCoeffs(frequencyHz_, dampingZeta_, response_);
55 pdGainsFromOmegaZeta(hzToOmega(frequencyHz_), dampingZeta_, kp_, kd_);
56}
57
58ControlAnim::Channel &ControlAnim::ensure(const std::string &name) {
59 auto it = channels_.find(name);
60 if (it != channels_.end()) return it->second;
61 Channel ch;
62 channels_.emplace(name, ch);
63 order_.push_back(name);
64 return channels_[name];
65}
66
67void ControlAnim::set(const std::string &name, float value) {
68 Channel &ch = ensure(name);
69 ch.y = value;
70 ch.yd = 0.f;
71 ch.x = value;
72 ch.xp = value;
73 ch.xdExplicit = 0.f;
74 ch.hasXd = false;
75 ch.hasPrevX = true;
76}
77
78void ControlAnim::setTarget(const std::string &name, float value) {
79 Channel &ch = ensure(name);
80 if (!ch.hasPrevX) {
81 ch.y = value;
82 ch.yd = 0.f;
83 ch.xp = value;
84 ch.hasPrevX = true;
85 }
86 ch.x = value;
87}
88
89void ControlAnim::setTargetVelocity(const std::string &name, float velocity) {
90 Channel &ch = ensure(name);
91 ch.xdExplicit = velocity;
92 ch.hasXd = true;
93}
94
95void ControlAnim::impulse(const std::string &name, float deltaVelocity) {
96 Channel &ch = ensure(name);
97 ch.yd += deltaVelocity;
98}
99
100bool ControlAnim::has(const std::string &name) const { return channels_.find(name) != channels_.end(); }
101
102float ControlAnim::get(const std::string &name) const {
103 auto it = channels_.find(name);
104 return it == channels_.end() ? 0.f : it->second.y;
105}
106
107float ControlAnim::getVelocity(const std::string &name) const {
108 auto it = channels_.find(name);
109 return it == channels_.end() ? 0.f : it->second.yd;
110}
111
112float ControlAnim::getTarget(const std::string &name) const {
113 auto it = channels_.find(name);
114 return it == channels_.end() ? 0.f : it->second.x;
115}
116
118 channels_.clear();
119 order_.clear();
120}
121
122void ControlAnim::remove(const std::string &name) {
123 channels_.erase(name);
124 order_.erase(std::remove(order_.begin(), order_.end(), name), order_.end());
125}
126
127std::string ControlAnim::getPropertyName(int index) const {
128 if (index < 0 || index >= static_cast<int>(order_.size())) return {};
129 return order_[static_cast<size_t>(index)];
130}
131
132void ControlAnim::updateUnchecked(float dt) {
133 if (dt <= 0.f) return;
134 const float omega = hzToOmega(frequencyHz_);
135
136 for (auto &kv : channels_) {
137 Channel &ch = kv.second;
138 float xd = 0.f;
139 if (ch.hasXd) {
140 xd = ch.xdExplicit;
141 } else if (ch.hasPrevX && dt > 1e-8f) {
142 xd = (ch.x - ch.xp) / dt;
143 }
144 ch.xp = ch.x;
145 ch.hasPrevX = true;
146
147 switch (integrator_) {
148 case Integrator::SecondOrder: stepSecondOrder(dt, ch.x, xd, coeffs_, ch.y, ch.yd); break;
149 case Integrator::Spring: stepDampedSpring(dt, ch.x, omega, dampingZeta_, ch.y, ch.yd); break;
150 case Integrator::Pd: stepPd(dt, ch.x, xd, kp_, kd_, ch.y, ch.yd); break;
151 }
152 }
153}
154
156 auto seconds = detail::secondsForStep(step, hasLastTick_, lastTick_, "ControlAnim");
157 if (!seconds) return eve::Result<void>::failure(seconds.status());
158 updateUnchecked(std::move(seconds).takeValue());
159 lastTick_ = step.tick;
160 hasLastTick_ = true;
162}
163
165 auto step = detail::legacyStep(dt, hasLastTick_, lastTick_, "ControlAnim");
166 if (!step) {
167 step.ignore("legacy ControlAnim update");
168 return;
169 }
170 advance(std::move(step).takeValue()).ignore("legacy ControlAnim update");
171}
172
173} // namespace eve::animation
174
175// ControlPose.cpp
176namespace eve::animation {
177
178ControlPose::ControlPose(AnimSkeleton *skeleton) : skeleton_(skeleton) {
179 refreshCoeffs();
180 const int n = skeleton_ ? skeleton_->getBoneCount() : 0;
181 ensureBones(n);
182 if (skeleton_ && n > 0) {
183 skeleton_->applyBindPose(&pose_);
184 skeleton_->applyBindPose(&target_);
185 readTargetIntoState(&target_, true);
186 hasTarget_ = true;
187 writePoseFromState();
188 }
189}
190
191void ControlPose::setFrequency(float frequencyHz) {
192 frequencyHz_ = frequencyHz;
193 refreshCoeffs();
194}
195
196void ControlPose::setDamping(float dampingZeta) {
197 dampingZeta_ = dampingZeta;
198 refreshCoeffs();
199}
200
202 response_ = response;
203 refreshCoeffs();
204}
205
206void ControlPose::setIntegrator(const std::string &kind) {
207 if (kind == "secondOrder") {
208 integrator_ = Integrator::SecondOrder;
209 } else if (kind == "spring") {
210 integrator_ = Integrator::Spring;
211 } else if (kind == "pd") {
212 integrator_ = Integrator::Pd;
213 } else {
214 throw Exception("ControlPose::setIntegrator: unknown kind '%s' (expected secondOrder|spring|pd)", kind.c_str());
215 }
216}
217
218std::string ControlPose::getIntegrator() const {
219 switch (integrator_) {
220 case Integrator::SecondOrder: return "secondOrder";
221 case Integrator::Spring: return "spring";
222 case Integrator::Pd: return "pd";
223 }
224 return "secondOrder";
225}
226
227void ControlPose::refreshCoeffs() {
228 coeffs_ = makeSecondOrderCoeffs(frequencyHz_, dampingZeta_, response_);
229 pdGainsFromOmegaZeta(hzToOmega(frequencyHz_), dampingZeta_, kp_, kd_);
230}
231
232void ControlPose::ensureBones(int count) {
233 if (count < 0) count = 0;
234 // AnimPose::resize always resets locals to identity — only call when size changes.
235 if (pose_.getBoneCount() != count) pose_.resize(count);
236 if (target_.getBoneCount() != count) target_.resize(count);
237 if (static_cast<int>(bones_.size()) != count) {
238 bones_.resize(static_cast<size_t>(count));
239 }
240}
241
242void ControlPose::setBoneWeight(int boneIndex, float weight) {
243 if (boneIndex < 0 || boneIndex >= static_cast<int>(bones_.size())) return;
244 bones_[static_cast<size_t>(boneIndex)].weight = clampf(weight, 0.f, 1.f);
245}
246
247float ControlPose::getBoneWeight(int boneIndex) const {
248 if (boneIndex < 0 || boneIndex >= static_cast<int>(bones_.size())) return 0.f;
249 return bones_[static_cast<size_t>(boneIndex)].weight;
250}
251
252void ControlPose::readTargetIntoState(const AnimPose *target, bool snap) {
253 if (!target) return;
254 const int n = target->getBoneCount();
255 ensureBones(n);
256 for (int i = 0; i < n; ++i) {
257 const TransformTRS &t = target->local(i);
258 BoneState &b = bones_[static_cast<size_t>(i)];
259
260 auto assign = [snap](ScalarState &s, float value) {
261 s.x = value;
262 if (!s.hasPrev || snap) {
263 s.y = value;
264 s.yd = 0.f;
265 s.xp = value;
266 s.hasPrev = true;
267 }
268 };
269
270 assign(b.px, t.px);
271 assign(b.py, t.py);
272 assign(b.pz, t.pz);
273
274 // Shortest-path quaternion: flip target if needed relative to current.
275 float tqx = t.qx, tqy = t.qy, tqz = t.qz, tqw = t.qw;
276 if (b.qw.hasPrev) {
277 const float dot = b.qx.y * tqx + b.qy.y * tqy + b.qz.y * tqz + b.qw.y * tqw;
278 if (dot < 0.f) {
279 tqx = -tqx;
280 tqy = -tqy;
281 tqz = -tqz;
282 tqw = -tqw;
283 }
284 }
285 assign(b.qx, tqx);
286 assign(b.qy, tqy);
287 assign(b.qz, tqz);
288 assign(b.qw, tqw);
289
290 assign(b.sx, t.sx);
291 assign(b.sy, t.sy);
292 assign(b.sz, t.sz);
293 }
294}
295
297 if (!target) {
298 throw Exception("ControlPose::setTargetPose: target is null");
299 }
300 target_.copyFrom(target);
301 readTargetIntoState(&target_, false);
302 hasTarget_ = true;
303 writePoseFromState();
304}
305
307 if (!hasTarget_) return;
308 readTargetIntoState(&target_, true);
309 writePoseFromState();
310}
311
313 writePoseFromState();
314 return &pose_;
315}
316
318
319void ControlPose::stepScalar(float dt, float xd, ScalarState &s) {
320 const float omega = hzToOmega(frequencyHz_);
321 switch (integrator_) {
322 case Integrator::SecondOrder: stepSecondOrder(dt, s.x, xd, coeffs_, s.y, s.yd); break;
323 case Integrator::Spring: stepDampedSpring(dt, s.x, omega, dampingZeta_, s.y, s.yd); break;
324 case Integrator::Pd: stepPd(dt, s.x, xd, kp_, kd_, s.y, s.yd); break;
325 }
326}
327
328void ControlPose::writePoseFromState() {
329 const int n = static_cast<int>(bones_.size());
330 pose_.resize(n);
331 for (int i = 0; i < n; ++i) {
332 const BoneState &b = bones_[static_cast<size_t>(i)];
333 TransformTRS trs;
334 trs.px = b.px.y;
335 trs.py = b.py.y;
336 trs.pz = b.pz.y;
337 trs.qx = b.qx.y;
338 trs.qy = b.qy.y;
339 trs.qz = b.qz.y;
340 trs.qw = b.qw.y;
341 trs.sx = b.sx.y;
342 trs.sy = b.sy.y;
343 trs.sz = b.sz.y;
344 trs.normalizeRotation();
345
346 if (b.weight < 1.f - 1e-6f) {
347 // Blend dynamics output toward hard target.
348 TransformTRS hard = target_.local(i);
349 // Shortest path for hard target vs dynamics result.
350 const float dot = trs.qx * hard.qx + trs.qy * hard.qy + trs.qz * hard.qz + trs.qw * hard.qw;
351 if (dot < 0.f) {
352 hard.qx = -hard.qx;
353 hard.qy = -hard.qy;
354 hard.qz = -hard.qz;
355 hard.qw = -hard.qw;
356 }
357 trs = blendTRS(hard, trs, b.weight);
358 }
359 pose_.local(i) = trs;
360 }
361}
362
363void ControlPose::updateUnchecked(float dt) {
364 if (dt <= 0.f || !hasTarget_) return;
365
366 // Refresh targets from stored target_ (weights / integrator may have changed).
367 const int n = target_.getBoneCount();
368 ensureBones(n);
369 for (int i = 0; i < n; ++i) {
370 const TransformTRS &t = target_.local(i);
371 BoneState &b = bones_[static_cast<size_t>(i)];
372
373 auto prep = [](ScalarState &s, float value) {
374 if (!s.hasPrev) {
375 s.y = value;
376 s.yd = 0.f;
377 s.xp = value;
378 s.hasPrev = true;
379 }
380 s.x = value;
381 };
382
383 prep(b.px, t.px);
384 prep(b.py, t.py);
385 prep(b.pz, t.pz);
386
387 float tqx = t.qx, tqy = t.qy, tqz = t.qz, tqw = t.qw;
388 const float dot = b.qx.y * tqx + b.qy.y * tqy + b.qz.y * tqz + b.qw.y * tqw;
389 if (dot < 0.f) {
390 tqx = -tqx;
391 tqy = -tqy;
392 tqz = -tqz;
393 tqw = -tqw;
394 }
395 prep(b.qx, tqx);
396 prep(b.qy, tqy);
397 prep(b.qz, tqz);
398 prep(b.qw, tqw);
399
400 prep(b.sx, t.sx);
401 prep(b.sy, t.sy);
402 prep(b.sz, t.sz);
403
404 auto advance = [&](ScalarState &s) {
405 float xd = 0.f;
406 if (s.hasPrev && dt > 1e-8f) xd = (s.x - s.xp) / dt;
407 s.xp = s.x;
408 stepScalar(dt, xd, s);
409 };
410
411 if (b.weight <= 1e-6f) {
412 // Hard follow
413 auto hard = [](ScalarState &s) {
414 s.y = s.x;
415 s.yd = 0.f;
416 s.xp = s.x;
417 };
418 hard(b.px);
419 hard(b.py);
420 hard(b.pz);
421 hard(b.qx);
422 hard(b.qy);
423 hard(b.qz);
424 hard(b.qw);
425 hard(b.sx);
426 hard(b.sy);
427 hard(b.sz);
428 } else {
429 advance(b.px);
430 advance(b.py);
431 advance(b.pz);
432 advance(b.qx);
433 advance(b.qy);
434 advance(b.qz);
435 advance(b.qw);
436 // Renormalize quaternion state after component integration.
437 {
438 float len = std::sqrt(b.qx.y * b.qx.y + b.qy.y * b.qy.y + b.qz.y * b.qz.y + b.qw.y * b.qw.y);
439 if (len > 1e-8f) {
440 const float inv = 1.f / len;
441 b.qx.y *= inv;
442 b.qy.y *= inv;
443 b.qz.y *= inv;
444 b.qw.y *= inv;
445 } else {
446 b.qx.y = 0.f;
447 b.qy.y = 0.f;
448 b.qz.y = 0.f;
449 b.qw.y = 1.f;
450 }
451 }
452 advance(b.sx);
453 advance(b.sy);
454 advance(b.sz);
455 }
456 }
457 writePoseFromState();
458}
459
461 auto seconds = detail::secondsForStep(step, hasLastTick_, lastTick_, "ControlPose");
462 if (!seconds) return eve::Result<void>::failure(seconds.status());
463 updateUnchecked(std::move(seconds).takeValue());
464 lastTick_ = step.tick;
465 hasLastTick_ = true;
467}
468
470 auto step = detail::legacyStep(dt, hasLastTick_, lastTick_, "ControlPose");
471 if (!step) {
472 step.ignore("legacy ControlPose update");
473 return;
474 }
475 advance(std::move(step).takeValue()).ignore("legacy ControlPose update");
476}
477
478} // namespace eve::animation
LogicalId target
const std::string & s
std::string name
Definition ECS.cpp:154
glm::vec3 n
Definition Grass.cpp:63
std::string response
MeleePoint3 b
Definition MeleeHit.cpp:41
glm::dvec3 velocity
double dt
Object::Ptr value
float t
std::string kind
int count
float step
Definition TreeMesh.cpp:451
double weight
uint32_t index
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
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
TransformTRS & local(int boneIndex)
Local.
Definition AnimPose.cpp:130
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.
float getVelocity(const std::string &name) const
Returns the velocity.
void remove(const std::string &name)
Removes .
ControlAnim(float frequencyHz=3.f, float dampingZeta=1.f, float response=1.f)
Control anim.
void set(const std::string &name, float value)
Create/update a channel: current value snaps to value, velocity cleared.
void setTarget(const std::string &name, float value)
Move the tracking target (does not snap state). Creates channel if missing.
eve::Result< void > advance(const eve::SimulationStep &step)
Advance all channels by one scheduler-owned deterministic step.
float get(const std::string &name) const
Returns the value.
void setDamping(float dampingZeta)
Sets the damping.
void setFrequency(float frequencyHz)
Sets the frequency.
bool has(const std::string &name) const
True when active.
float getTarget(const std::string &name) const
Returns the target.
void setResponse(float response)
Sets the response.
std::string getIntegrator() const
Returns the integrator.
std::string getPropertyName(int index) const
Returns the property name.
void setIntegrator(const std::string &kind)
Integrator: "secondOrder" | "spring" | "pd". Invalid → exception.
void update(float dt)
Legacy seconds facade; explicitly forwards to advance().
void setTargetVelocity(const std::string &name, float velocity)
Optional explicit target velocity (used by secondOrder / pd).
void impulse(const std::string &name, float deltaVelocity)
Inject an instantaneous velocity impulse (procedural “hit”).
void setBoneWeight(int boneIndex, float weight)
Per-bone blend weight in [0,1]; 1 = full dynamics, 0 = hard snap to target.
void setDamping(float dampingZeta)
Sets the damping.
float getBoneWeight(int boneIndex) const
Returns the bone weight.
void update(float dt)
Legacy seconds facade; explicitly forwards to advance().
void setTargetPose(const AnimPose *target)
Copy target pose. Channels without prior state snap; existing state keeps momentum.
AnimPose * getPose()
Returns the pose.
void snapToTarget()
Snap current state to the last target without changing the target.
ControlPose(AnimSkeleton *skeleton)
Control pose.
std::string getIntegrator() const
Returns the integrator.
void setResponse(float response)
Sets the response.
void setFrequency(float frequencyHz)
Sets the frequency.
eve::Result< void > advance(const eve::SimulationStep &step)
Advance pose dynamics by one scheduler-owned deterministic step.
AnimPose * getTargetPose()
Returns the target pose.
void setIntegrator(const std::string &kind)
Sets the integrator.
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.
TransformTRS blendTRS(const TransformTRS &a, const TransformTRS &b, float t)
Blend trs.
Definition AnimMath.h:79
void stepPd(float dt, float target, float targetVel, float kp, float kd, float &y, float &yd)
Semi-implicit Euler PD step (unit mass): a = Kp (target − y) + Kd (targetVel − yd),...
void stepSecondOrder(float dt, float x, float xd, const SecondOrderCoeffs &c, float &y, float &yd)
Stable semi-implicit Euler step for a second-order tracker. Estimates input velocity from consecutive...
void pdGainsFromOmegaZeta(float omega, float zeta, float &kp, float &kd)
Unit-mass PD gains from natural frequency ω (rad/s) and damping ratio ζ.
constexpr float clampf(float v, float lo, float hi) noexcept
Clampf.
Definition AnimMath.h:34
SecondOrderCoeffs makeSecondOrderCoeffs(float frequencyHz, float dampingZeta, float response)
Build second-order coefficients from frequency (Hz), damping ζ, response r.
float hzToOmega(float frequencyHz)
ω (rad/s) from frequency in Hz.
void stepDampedSpring(float dt, float target, float angularFrequency, float dampingRatio, float &pos, float &vel)
Advance position/velocity relative to a set-point using closed-form spring step.
double dot(ForceVector a, ForceVector b)
Definition ForceMath.h:14
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Local TRS used by skeletal animation (quaternion xyzw).
Definition AnimMath.h:9