14 std::vector<AnimationClip*> clips)
15 :
Component(
owner), m_skeleton(skeleton), m_clips(std::move(clips)) {
19 delete m_stateMachine;
23 if (!m_skeleton || m_skeleton->GetBoneCount() == 0) {
24 SLEAK_WARN(
"AnimatorComponent: No skeleton or empty skeleton");
28 int boneCount = m_skeleton->GetBoneCount();
33 uint32_t bufferSize =
static_cast<uint32_t
>(boneCount *
sizeof(
Math::Matrix4));
39 m_boneBuffer->SetSlot(3);
42 m_boneBuffer->Update(m_boneMatrices.data(), bufferSize);
47 meshComp->AddConstantBuffer(m_boneBuffer);
49 SLEAK_WARN(
"AnimatorComponent: No sibling MeshComponent found");
53 SLEAK_INFO(
"AnimatorComponent: Initialized with {} bones, {} clips",
54 boneCount, m_clips.size());
70 ComputeBoneTransformsForClip(req.
clipA, req.
timeA, m_boneMatrices);
71 ComputeBoneTransformsForClip(req.
clipB, req.
timeB, m_boneMatricesB);
72 BlendBoneMatrices(m_boneMatrices, m_boneMatricesB,
76 ComputeBoneTransformsForClip(req.
clipA, req.
timeA, m_boneMatrices);
79 uint32_t bufferSize =
static_cast<uint32_t
>(
81 m_boneBuffer->Update(m_boneMatrices.data(), bufferSize);
85 if (!m_playing || m_currentClip < 0)
93 if (m_currentTime > clip->
duration) {
95 m_currentTime = std::fmod(m_currentTime, clip->
duration);
102 ComputeBoneTransforms(m_currentTime);
104 uint32_t bufferSize =
static_cast<uint32_t
>(
106 m_boneBuffer->Update(m_boneMatrices.data(), bufferSize);
110 delete m_stateMachine;
112 return m_stateMachine;
117 m_clips.push_back(clip);
120void AnimatorComponent::ComputeBoneTransformsForClip(
AnimationClip* clip,
float animTime,
121 std::vector<Math::Matrix4>& outMatrices) {
125 ProcessNodeHierarchyForClip(rootIdx, identity, clip, animTime, outMatrices);
129void AnimatorComponent::ProcessNodeHierarchyForClip(
int nodeIndex,
132 std::vector<Math::Matrix4>& outMatrices) {
133 const NodeData& node = m_skeleton->GetNode(nodeIndex);
137 const AnimationChannel* channel = clip->FindChannel(node.name);
139 Math::Vector3D pos = InterpolatePosition(*channel, animTime);
140 Math::Quaternion rot = InterpolateRotation(*channel, animTime);
141 Math::Vector3D scl = InterpolateScale(*channel, animTime);
143 Math::Quaternion rotConj(rot.GetW(), -rot.GetX(), -rot.GetY(), -rot.GetZ());
149 nodeTransform = scaleMat * rotMat * transMat;
152 Math::Matrix4 globalTransform = nodeTransform * parentTransform;
154 if (node.boneIndex >= 0 && node.boneIndex <
static_cast<int>(outMatrices.size())) {
155 const Bone& bone = m_skeleton->GetBone(node.boneIndex);
156 outMatrices[node.boneIndex] = bone.offsetMatrix * globalTransform *
157 m_skeleton->GetGlobalInverseTransform();
160 for (
int childIdx : node.children) {
161 ProcessNodeHierarchyForClip(childIdx, globalTransform, clip, animTime, outMatrices);
165void AnimatorComponent::BlendBoneMatrices(
const std::vector<Math::Matrix4>& a,
166 const std::vector<Math::Matrix4>& b,
168 std::vector<Math::Matrix4>& out) {
169 float w0 = 1.0f - weight;
171 for (
size_t i = 0; i < a.size() && i < b.size(); ++i) {
172 for (
int r = 0; r < 4; ++r) {
173 for (
int c = 0; c < 4; ++c) {
174 out[i](r, c) = a[i](r, c) * w0 + b[i](r, c) * w1;
180void AnimatorComponent::ComputeBoneTransforms(
float animTime) {
182 int rootIdx = m_skeleton->GetRootNodeIndex();
184 ProcessNodeHierarchy(rootIdx, identity, animTime);
188void AnimatorComponent::ProcessNodeHierarchy(
int nodeIndex,
191 const NodeData& node = m_skeleton->GetNode(nodeIndex);
192 AnimationClip* clip = m_clips[m_currentClip];
196 const AnimationChannel* channel = clip->FindChannel(node.name);
198 Math::Vector3D pos = InterpolatePosition(*channel, animTime);
199 Math::Quaternion rot = InterpolateRotation(*channel, animTime);
200 Math::Vector3D scl = InterpolateScale(*channel, animTime);
202 Math::Quaternion rotConj(rot.GetW(), -rot.GetX(), -rot.GetY(), -rot.GetZ());
208 nodeTransform = scaleMat * rotMat * transMat;
211 Math::Matrix4 globalTransform = nodeTransform * parentTransform;
213 if (node.boneIndex >= 0 && node.boneIndex <
static_cast<int>(m_boneMatrices.size())) {
214 const Bone& bone = m_skeleton->GetBone(node.boneIndex);
215 m_boneMatrices[node.boneIndex] = bone.offsetMatrix * globalTransform *
216 m_skeleton->GetGlobalInverseTransform();
219 for (
int childIdx : node.children) {
220 ProcessNodeHierarchy(childIdx, globalTransform, animTime);
227 if (keys.size() < 2)
return {0, 0.0f};
230 auto upper = std::upper_bound(
231 keys.begin() + 1, keys.end() - 1, time,
232 [](
float t,
const Keyframe<T>& key) { return t < key.time; });
233 int idx =
static_cast<int>(upper - keys.begin()) - 1;
235 if (next >=
static_cast<int>(keys.size()))
238 float dt = keys[next].time - keys[idx].time;
239 float t = (dt > 0.0f) ? (time - keys[idx].time) / dt : 0.0f;
240 return {idx, std::max(0.0f, std::min(1.0f, t))};
251Math::Vector3D AnimatorComponent::InterpolatePosition(
252 const AnimationChannel& channel,
float time) {
253 auto& keys = channel.positionKeys;
254 if (keys.empty())
return Math::Vector3D(0.0f, 0.0f, 0.0f);
255 if (keys.size() == 1)
return keys[0].value;
258 if (idx + 1 >=
static_cast<int>(keys.size()))
return keys[idx].value;
259 return LerpVec3(keys[idx].value, keys[idx + 1].value, t);
264 auto& keys = channel.rotationKeys;
265 if (keys.empty())
return Math::Quaternion();
266 if (keys.size() == 1)
return keys[0].value;
269 if (idx + 1 >=
static_cast<int>(keys.size()))
return keys[idx].value;
270 return Slerp(keys[idx].value, keys[idx + 1].value, t);
275 auto& keys = channel.scaleKeys;
276 if (keys.empty())
return Math::Vector3D(1.0f, 1.0f, 1.0f);
277 if (keys.size() == 1)
return keys[0].value;
280 if (idx + 1 >=
static_cast<int>(keys.size()))
return keys[idx].value;
281 return LerpVec3(keys[idx].value, keys[idx + 1].value, t);
286 float dot = a.
GetW() * b.GetW() + a.GetX() * b.GetX() +
287 a.GetY() * b.GetY() + a.GetZ() * b.GetZ();
289 Math::Quaternion b2 = b;
291 b2 = Math::Quaternion(-b.GetW(), -b.GetX(), -b.GetY(), -b.GetZ());
296 Math::Quaternion result(
297 a.GetW() + (b2.GetW() - a.GetW()) * t,
298 a.GetX() + (b2.GetX() - a.GetX()) * t,
299 a.GetY() + (b2.GetY() - a.GetY()) * t,
300 a.GetZ() + (b2.GetZ() - a.GetZ()) * t);
305 float theta = std::acos(dot);
306 float sinTheta = std::sin(theta);
307 float wa = std::sin((1.0f - t) * theta) / sinTheta;
308 float wb = std::sin(t * theta) / sinTheta;
310 return Math::Quaternion(
311 a.GetW() * wa + b2.GetW() * wb,
312 a.GetX() * wa + b2.GetX() * wb,
313 a.GetY() * wa + b2.GetY() * wb,
314 a.GetZ() * wa + b2.GetZ() * wb);
318 for (
int i = 0; i < static_cast<int>(m_clips.size()); ++i) {
319 if (m_clips[i] && m_clips[i]->name == clipName) {
324 SLEAK_WARN(
"AnimatorComponent: Clip '{}' not found", clipName);
328 if (clipIndex < 0 || clipIndex >=
static_cast<int>(m_clips.size())) {
329 SLEAK_WARN(
"AnimatorComponent: Invalid clip index {}", clipIndex);
332 m_currentClip = clipIndex;
333 m_currentTime = 0.0f;
340 m_currentTime = 0.0f;
348 if (m_currentClip >= 0)
365 return m_currentTime;
369 static const std::string empty;
370 if (m_currentClip >= 0 && m_currentClip <
static_cast<int>(m_clips.size()))
371 return m_clips[m_currentClip]->name;
AnimationStateMachine()=default
const std::string & GetCurrentClipName() const
AnimationStateMachine * CreateStateMachine()
Replaces any existing state machine with a fresh, empty one.
float GetCurrentTime() const
void AddClip(AnimationClip *clip)
virtual void Update(float deltaTime) override
Samples the active state machine or clip and pushes the resulting bone matrices to the GPU.
RefPtr< RenderEngine::BufferBase > GetBoneBuffer() const
AnimatorComponent(GameObject *owner, Skeleton *skeleton, std::vector< AnimationClip * > clips)
void Play(const std::string &clipName, bool loop=true)
Switches to the clip by name, restarting from time zero.
void SetSpeed(float speed)
virtual bool Initialize() override
Allocates the bone constant buffer and attaches it to the sibling MeshComponent.
virtual ~AnimatorComponent()
Component(GameObject *object)
T * GetComponent()
Finds the first attached component of type T, or nullptr.
static Matrix< float, Rows, Rows > Identity()
static Matrix< float, 4, 4 > Rotate(const Quaternion &rotation)
static Matrix< float, 4, 4 > Scale(const Vector3D &scale)
static Matrix< float, 4, 4 > Translate(const Vector3D &translation)
Represents a quaternion for 3D rotations.
static BufferBase * CreateBuffer(BufferType Type, uint32_t Size, void *Data)
Creates a buffer via the currently registered backend factory.
int GetRootNodeIndex() const
Matrix< float, 4, 4 > Matrix4
Root namespace for everything the engine exposes.
static std::pair< int, float > FindKeyframe(const std::vector< Keyframe< T > > &keys, float time)
Finds the keyframe pair straddling time and the lerp factor between them.
static Math::Vector3D LerpVec3(const Math::Vector3D &a, const Math::Vector3D &b, float t)
Componentwise vector lerp.