载入中...
搜索中...
未找到
OrientationWarping.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <functional>
5#include <simplesquirrel/simplesquirrel.hpp>
6#include <stdexcept>
7#include <string>
8#include <vector>
10#include "animation/AnimPose.h"
13#include "common/Diagnostic.h"
16
17// OrientationWarping.cpp
18namespace eve::animation {
19namespace {
20constexpr int kMaxSpineBones = 32;
21constexpr int kMaxIkBones = 16;
22
24
25float wrapPi(float radians) { return std::remainder(radians, 6.28318530718f); }
26
27float planarSpeed(float x, float z) { return std::sqrt(x * x + z * z); }
28
29float signedPlanarAngle(float fromX, float fromZ, float toX, float toZ) {
30 return wrapPi(std::atan2(toX, toZ) - std::atan2(fromX, fromZ));
31}
32
33float interpTo(float current, float target, float dt, float speed) {
34 const float delta = wrapPi(target - current);
35 if (speed <= 0.f) return target;
36 const float step = std::clamp(dt * speed, 0.f, 1.f);
37 return wrapPi(current + delta * step);
38}
39
40void setWorldRotation(AnimPose& pose, const AnimSkeleton& skeleton, int bone, float qx, float qy, float qz, float qw) {
41 const int parent = skeleton.getParent(bone);
42 float lx, ly, lz, lw;
43 if (parent < 0) {
44 lx = qx;
45 ly = qy;
46 lz = qz;
47 lw = qw;
48 } else {
49 const auto& parentWorld = pose.world(parent);
50 multiplyQuat(-parentWorld.qx, -parentWorld.qy, -parentWorld.qz, parentWorld.qw, qx, qy, qz, qw, lx, ly, lz, lw);
51 }
52 pose.setLocalRotation(bone, lx, ly, lz, lw);
53}
54
55void addWorldYaw(AnimPose& pose, const AnimSkeleton& skeleton, int bone, float yaw) {
56 pose.computeWorld(&skeleton);
57 const auto& world = pose.world(bone);
58 float qx, qy, qz, qw;
59 const float half = yaw * 0.5f;
60 multiplyQuat(0.f, std::sin(half), 0.f, std::cos(half), world.qx, world.qy, world.qz, world.qw, qx, qy, qz, qw);
61 setWorldRotation(pose, skeleton, bone, qx, qy, qz, qw);
62}
63
64bool validBoneList(const AnimSkeleton& skeleton, int root, std::span<const int> bones, int maxCount) {
65 if (bones.size() > static_cast<std::size_t>(maxCount)) return false;
66 for (std::size_t i = 0; i < bones.size(); ++i) {
67 if (bones[i] < 0 || bones[i] >= skeleton.getBoneCount() || bones[i] == root) return false;
68 for (std::size_t j = 0; j < i; ++j)
69 if (bones[i] == bones[j]) return false;
70 }
71 return true;
72}
73} // namespace
74
77 int rootBone = -1;
78 std::vector<int> spineBones;
79 std::vector<int> ikBones;
80 float distributedAlpha = 0.5f;
81 float angleThreshold = 2.35619449019f; // 135 degrees
82 float interpSpeed = 8.f;
83 float minSpeed = 0.1f;
84 float appliedAngle = 0.f;
85 float targetAngle = 0.f;
86 bool enabled = true;
87};
88
89OrientationWarping::OrientationWarping() : impl_(std::make_unique<Impl>()) {}
91
92eve::Result<void> OrientationWarping::configure(AnimSkeleton& skeleton, int rootBone, std::span<const int> spineBones,
93 std::span<const int> ikBones) {
94 if (rootBone < 0 || rootBone >= skeleton.getBoneCount())
96 "root bone must belong to the skeleton",
97 "orientationWarping", {}, "animation"));
98 if (!validBoneList(skeleton, rootBone, spineBones, kMaxSpineBones))
100 eve::DiagnosticCode::InvalidArgument, "spine bones must be unique valid indices distinct from the root",
101 "orientationWarping", {}, "animation"));
102 if (!validBoneList(skeleton, rootBone, ikBones, kMaxIkBones))
104 eve::DiagnosticCode::InvalidArgument, "ik bones must be unique valid indices distinct from the root",
105 "orientationWarping", {}, "animation"));
106 for (int spine : spineBones)
107 for (int ik : ikBones)
108 if (spine == ik)
110 "a bone cannot be both spine and ik",
111 "orientationWarping", {}, "animation"));
112 impl_->skeleton = &skeleton;
113 impl_->rootBone = rootBone;
114 impl_->spineBones.assign(spineBones.begin(), spineBones.end());
115 impl_->ikBones.assign(ikBones.begin(), ikBones.end());
116 impl_->appliedAngle = 0.f;
117 impl_->targetAngle = 0.f;
119}
120
122 if (!std::isfinite(alpha) || alpha < 0.f || alpha > 1.f)
124 "distributed alpha must be finite in [0,1]",
125 "orientationWarping", {}, "animation"));
126 impl_->distributedAlpha = alpha;
128}
129
130float OrientationWarping::getDistributedAlpha() const { return impl_->distributedAlpha; }
131
133 if (!std::isfinite(radians) || radians <= 0.f || radians > 3.14159265359f + 1e-6f)
135 "angle threshold must be finite in (0, pi]",
136 "orientationWarping", {}, "animation"));
137 impl_->angleThreshold = radians;
139}
140
141float OrientationWarping::getAngleThreshold() const { return impl_->angleThreshold; }
142
144 if (!std::isfinite(speed) || speed < 0.f || speed > 100.f)
146 "rotation interp speed must be finite in [0,100]",
147 "orientationWarping", {}, "animation"));
148 impl_->interpSpeed = speed;
150}
151
152float OrientationWarping::getRotationInterpSpeed() const { return impl_->interpSpeed; }
153
155 if (!std::isfinite(metresPerSecond) || metresPerSecond < 0.f || metresPerSecond > 100.f)
157 "minimum root-motion speed must be finite in [0,100]",
158 "orientationWarping", {}, "animation"));
159 impl_->minSpeed = metresPerSecond;
161}
162
163float OrientationWarping::getMinRootMotionSpeed() const { return impl_->minSpeed; }
164
165void OrientationWarping::setEnabled(bool enabled) { impl_->enabled = enabled; }
166bool OrientationWarping::isEnabled() const { return impl_->enabled; }
167
169 impl_->appliedAngle = 0.f;
170 impl_->targetAngle = 0.f;
171}
172
173eve::Result<void> OrientationWarping::apply(AnimPose& pose, float locomotionX, float locomotionZ, float animatedX,
174 float animatedZ, float dt) {
175 if (!impl_->skeleton)
177 eve::DiagnosticCode::InvalidArgument, "configure a skeleton before applying orientation warp",
178 "orientationWarping", {}, "animation"));
179 if (pose.getBoneCount() != impl_->skeleton->getBoneCount())
181 "pose bone count must match the skeleton",
182 "orientationWarping", {}, "animation"));
183 if (!std::isfinite(dt) || dt < 0.f || dt > 1.f)
185 eve::DiagnosticCode::InvalidArgument, "dt must be finite in [0,1]", "orientationWarping", {}, "animation"));
186 for (float value : {locomotionX, locomotionZ, animatedX, animatedZ})
187 if (!std::isfinite(value))
189 eve::DiagnosticCode::InvalidArgument, "locomotion and animated velocities must be finite",
190 "orientationWarping", {}, "animation"));
191 for (int i = 0; i < pose.getBoneCount(); ++i) {
192 const auto& t = pose.local(i);
193 for (float value : {t.px, t.py, t.pz, t.qx, t.qy, t.qz, t.qw, t.sx, t.sy, t.sz})
194 if (!std::isfinite(value))
196 "pose locals must be finite",
197 "orientationWarping", {}, "animation"));
198 }
199
200 float target = 0.f;
201 if (planarSpeed(locomotionX, locomotionZ) >= impl_->minSpeed &&
202 planarSpeed(animatedX, animatedZ) >= impl_->minSpeed) {
203 const float angle = signedPlanarAngle(animatedX, animatedZ, locomotionX, locomotionZ);
204 if (std::fabs(angle) < impl_->angleThreshold) target = angle;
205 }
206 const float applied = interpTo(impl_->appliedAngle, target, dt, impl_->interpSpeed);
207 if (!impl_->enabled) {
208 impl_->targetAngle = target;
209 impl_->appliedAngle = applied;
211 }
212 if (std::fabs(applied) <= 1e-6f) {
213 impl_->targetAngle = target;
214 impl_->appliedAngle = 0.f;
216 }
217
218 AnimPose next;
219 next.copyFrom(&pose);
220 next.computeWorld(impl_->skeleton);
221 struct SavedRotation {
222 int bone = 0;
223 float qx = 0.f, qy = 0.f, qz = 0.f, qw = 1.f;
224 };
225 std::vector<SavedRotation> ikWorld;
226 ikWorld.reserve(impl_->ikBones.size());
227 for (int bone : impl_->ikBones) {
228 const auto& world = next.world(bone);
229 ikWorld.push_back({bone, world.qx, world.qy, world.qz, world.qw});
230 }
231
232 const float spineShare = impl_->spineBones.empty() ? 0.f : impl_->distributedAlpha;
233 addWorldYaw(next, *impl_->skeleton, impl_->rootBone, applied * (1.f - spineShare));
234 if (!impl_->spineBones.empty()) {
235 const float perBone = applied * spineShare / static_cast<float>(impl_->spineBones.size());
236 for (int bone : impl_->spineBones) addWorldYaw(next, *impl_->skeleton, bone, perBone);
237 }
238 next.computeWorld(impl_->skeleton);
239 for (const auto& saved : ikWorld)
240 setWorldRotation(next, *impl_->skeleton, saved.bone, saved.qx, saved.qy, saved.qz, saved.qw);
241 next.computeWorld(impl_->skeleton);
242
243 pose.copyFrom(&next);
244 impl_->targetAngle = target;
245 impl_->appliedAngle = applied;
247}
248
249float OrientationWarping::getAppliedAngle() const { return impl_->appliedAngle; }
250float OrientationWarping::getTargetAngle() const { return impl_->targetAngle; }
251AnimSkeleton* OrientationWarping::getSkeleton() const { return impl_->skeleton; }
252int OrientationWarping::getRootBone() const { return impl_->rootBone; }
253int OrientationWarping::getSpineBoneCount() const { return static_cast<int>(impl_->spineBones.size()); }
254int OrientationWarping::getIkBoneCount() const { return static_cast<int>(impl_->ikBones.size()); }
255} // namespace eve::animation
256
257// OrientationWarpingBindings.cpp
258namespace eve::animation {
259namespace {
260
261constexpr const char* kSource = "animation.bindings";
262
263std::vector<int> copyBoneArray(ssq::Array values, const char* label, int maximum) {
264 if (values.size() > static_cast<std::size_t>(maximum))
265 throw std::runtime_error(std::string(label) + " exceeds the supported bone count");
266 std::vector<int> bones;
267 bones.reserve(values.size());
268 for (std::size_t i = 0; i < values.size(); ++i) bones.push_back(values.get<int>(i));
269 return bones;
270}
271
272} // namespace
273
274void exposeOrientationWarpingBindings(ssq::Table& table) {
275 const script::BindContext bind{table.getHandle(), kSource};
276 auto cls = table.addClass<OrientationWarping>(
277 "OrientationWarping", std::function<OrientationWarping*()>([] { return new OrientationWarping(); }), true);
279 cls, "configure",
280 [bind](OrientationWarping* self, AnimSkeleton* skeleton, int root, ssq::Array spine, ssq::Array ik) {
281 if (!skeleton) return bind.failInvalid("configure requires a skeleton");
282 try {
283 auto spineBones = copyBoneArray(spine, "spine bones", 32);
284 auto ikBones = copyBoneArray(ik, "ik bones", 16);
285 return script::projectResult(bind.vm(), self->configure(*skeleton, root, spineBones, ikBones));
286 } catch (const std::exception& error) {
287 return bind.failInvalid(error.what());
288 }
289 });
290 script::bindMethod(cls, "setDistributedAlpha", [bind](OrientationWarping* self, float alpha) {
291 return script::projectResult(bind.vm(), self->setDistributedAlpha(alpha));
292 });
294 script::bindMethod(cls, "setAngleThreshold", [bind](OrientationWarping* self, float radians) {
295 return script::projectResult(bind.vm(), self->setAngleThreshold(radians));
296 });
298 script::bindMethod(cls, "setRotationInterpSpeed", [bind](OrientationWarping* self, float speed) {
299 return script::projectResult(bind.vm(), self->setRotationInterpSpeed(speed));
300 });
302 script::bindMethod(cls, "setMinRootMotionSpeed", [bind](OrientationWarping* self, float speed) {
303 return script::projectResult(bind.vm(), self->setMinRootMotionSpeed(speed));
304 });
309 script::bindMethod(cls, "apply",
310 [bind](OrientationWarping* self, AnimPose* pose, float locomotionX, float locomotionZ,
311 float animatedX, float animatedZ, float dt) {
312 if (!pose) return bind.failInvalid("apply requires a pose");
314 bind.vm(), self->apply(*pose, locomotionX, locomotionZ, animatedX, animatedZ, dt));
315 });
322}
323} // namespace eve::animation
double z
double x
LogicalId target
int root
Definition AnimSmr.cpp:119
eve::EntitySpatialPose pose
float yaw
Definition BushMesh.cpp:37
bool applied
Stable, structured diagnostics shared by engine modules.
HSQOBJECT cls
Definition ECS.cpp:39
DiagnosticCode code
float maximum[3]
const ColourScope * parent
std::vector< Bone > bones
std::uint32_t bone
std::string label
double dt
std::string error
Definition Package.cpp:174
std::set< std::string > values
Object::Ptr value
float t
double current
Per-translation-unit VM + diagnostic-source helper for Squirrel bindings.
The single Squirrel projection for common Result, Status and Value.
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.
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
3D bone hierarchy + bind-pose local TRS for skeletal animation. Independent of ik::Skeleton3D (FABRIK...
int getBoneCount() const
Returns the bone count.
Planar orientation warp applied after motion matching, never fed back into search.
int getSpineBoneCount() const
Returns the spine bone count.
eve::Result< void > setDistributedAlpha(float alpha)
Set how much of the warp is distributed onto the spine chain.
~OrientationWarping()
Release owned interpolation state; the borrowed skeleton is not accessed.
AnimSkeleton * getSkeleton() const
Borrowed skeleton from the last successful configure, or null. @ownership Borrowed; ownership remains...
void reset()
Clear smoothed yaw so the next apply starts from zero.
eve::Result< void > apply(AnimPose &pose, float locomotionX, float locomotionZ, float animatedX, float animatedZ, float dt)
Warp a local pose so animated planar velocity aligns with locomotion velocity.
float getAppliedAngle() const
Smoothed yaw last applied to a pose, radians, positive from +Z toward +X.
eve::Result< void > setAngleThreshold(float radians)
Set the inclusive planar-angle magnitude that disables warping.
eve::Result< void > setMinRootMotionSpeed(float metresPerSecond)
Set the planar speed below which either direction is treated as stationary.
eve::Result< void > setRotationInterpSpeed(float speed)
Set how quickly the applied yaw approaches the target, matching Unreal FInterpTo.
int getIkBoneCount() const
Returns the ik bone count.
void setEnabled(bool enabled)
Enable or disable pose mutation. Disabled apply calls still recompute the target.
bool isEnabled() const
True when enabled.
eve::Result< void > configure(AnimSkeleton &skeleton, int rootBone, std::span< const int > spineBones={}, std::span< const int > ikBones={})
Atomically bind a skeleton and bone lists used by later apply calls.
OrientationWarping()
Construct an unconfigured warper with no borrowed skeleton.
float getTargetAngle() const
Unsmoothed target yaw from the last successful apply, radians.
int getRootBone() const
Returns the root bone.
Pins the active VM and a stable diagnostic source for one expose() TU.
void multiplyQuat(float ax, float ay, float az, float aw, float bx, float by, float bz, float bw, float &ox, float &oy, float &oz, float &ow)
Hamilton product a * b for unit quaternions (xyzw).
Definition AnimMath.h:94
void exposeOrientationWarpingBindings(ssq::Table &table)
Register the owning OrientationWarping Squirrel surface.
void bindMethod(ssq::Class &cls, const char *name, F &&fn)
Register one script method while keeping a literal name for Binding Contracts.
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
bool enabled