SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
AnimatorComponent.cpp
Go to the documentation of this file.
1#include <Core/GameObject.hpp>
2#include <Core/Logger.hpp>
8#include <algorithm>
9#include <cmath>
10
11namespace Sleak {
12
14 std::vector<AnimationClip*> clips)
15 : Component(owner), m_skeleton(skeleton), m_clips(std::move(clips)) {
16}
17
19 delete m_stateMachine;
20}
21
23 if (!m_skeleton || m_skeleton->GetBoneCount() == 0) {
24 SLEAK_WARN("AnimatorComponent: No skeleton or empty skeleton");
25 return false;
26 }
27
28 int boneCount = m_skeleton->GetBoneCount();
29 m_boneMatrices.resize(boneCount, Math::Matrix4::Identity());
30 m_boneMatricesB.resize(boneCount, Math::Matrix4::Identity());
31
32 // Create bone constant buffer at slot 3
33 uint32_t bufferSize = static_cast<uint32_t>(boneCount * sizeof(Math::Matrix4));
37 bufferSize,
38 nullptr));
39 m_boneBuffer->SetSlot(3);
40
41 // Initialize with identity matrices
42 m_boneBuffer->Update(m_boneMatrices.data(), bufferSize);
43
44 // Attach bone buffer to sibling MeshComponent so DrawIndexedCommand binds it
45 auto* meshComp = GetOwner()->GetComponent<MeshComponent>();
46 if (meshComp) {
47 meshComp->AddConstantBuffer(m_boneBuffer);
48 } else {
49 SLEAK_WARN("AnimatorComponent: No sibling MeshComponent found");
50 }
51
52 bIsInitialized = true;
53 SLEAK_INFO("AnimatorComponent: Initialized with {} bones, {} clips",
54 boneCount, m_clips.size());
55 return true;
56}
57
58void AnimatorComponent::Update(float deltaTime) {
59 if (!bIsInitialized)
60 return;
61
62 if (m_stateMachine) {
63 SampleRequest req = m_stateMachine->Update(deltaTime);
64
65 if (!req.clipA)
66 return;
67
68 if (req.clipB && req.blendWeight > 0.0f) {
69 // Blending two clips
70 ComputeBoneTransformsForClip(req.clipA, req.timeA, m_boneMatrices);
71 ComputeBoneTransformsForClip(req.clipB, req.timeB, m_boneMatricesB);
72 BlendBoneMatrices(m_boneMatrices, m_boneMatricesB,
73 req.blendWeight, m_boneMatrices);
74 } else {
75 // Single clip
76 ComputeBoneTransformsForClip(req.clipA, req.timeA, m_boneMatrices);
77 }
78
79 uint32_t bufferSize = static_cast<uint32_t>(
80 m_skeleton->GetBoneCount() * sizeof(Math::Matrix4));
81 m_boneBuffer->Update(m_boneMatrices.data(), bufferSize);
82 return;
83 }
84
85 if (!m_playing || m_currentClip < 0)
86 return;
87
88 AnimationClip* clip = m_clips[m_currentClip];
89 if (!clip) return;
90
91 m_currentTime += deltaTime * m_speed * clip->ticksPerSecond;
92
93 if (m_currentTime > clip->duration) {
94 if (m_loop) {
95 m_currentTime = std::fmod(m_currentTime, clip->duration);
96 } else {
97 m_currentTime = clip->duration;
98 m_playing = false;
99 }
100 }
101
102 ComputeBoneTransforms(m_currentTime);
103
104 uint32_t bufferSize = static_cast<uint32_t>(
105 m_skeleton->GetBoneCount() * sizeof(Math::Matrix4));
106 m_boneBuffer->Update(m_boneMatrices.data(), bufferSize);
107}
108
110 delete m_stateMachine;
111 m_stateMachine = new AnimationStateMachine();
112 return m_stateMachine;
113}
114
116 if (clip)
117 m_clips.push_back(clip);
118}
119
120void AnimatorComponent::ComputeBoneTransformsForClip(AnimationClip* clip, float animTime,
121 std::vector<Math::Matrix4>& outMatrices) {
123 int rootIdx = m_skeleton->GetRootNodeIndex();
124 if (rootIdx >= 0) {
125 ProcessNodeHierarchyForClip(rootIdx, identity, clip, animTime, outMatrices);
126 }
127}
128
129void AnimatorComponent::ProcessNodeHierarchyForClip(int nodeIndex,
130 const Math::Matrix4& parentTransform,
131 AnimationClip* clip, float animTime,
132 std::vector<Math::Matrix4>& outMatrices) {
133 const NodeData& node = m_skeleton->GetNode(nodeIndex);
134
135 Math::Matrix4 nodeTransform = node.defaultTransform;
136
137 const AnimationChannel* channel = clip->FindChannel(node.name);
138 if (channel) {
139 Math::Vector3D pos = InterpolatePosition(*channel, animTime);
140 Math::Quaternion rot = InterpolateRotation(*channel, animTime);
141 Math::Vector3D scl = InterpolateScale(*channel, animTime);
142
143 Math::Quaternion rotConj(rot.GetW(), -rot.GetX(), -rot.GetY(), -rot.GetZ());
144
145 Math::Matrix4 scaleMat = Math::Matrix4::Scale(scl);
146 Math::Matrix4 rotMat = Math::Matrix4::Rotate(rotConj);
148
149 nodeTransform = scaleMat * rotMat * transMat;
150 }
151
152 Math::Matrix4 globalTransform = nodeTransform * parentTransform;
153
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();
158 }
159
160 for (int childIdx : node.children) {
161 ProcessNodeHierarchyForClip(childIdx, globalTransform, clip, animTime, outMatrices);
162 }
163}
164
165void AnimatorComponent::BlendBoneMatrices(const std::vector<Math::Matrix4>& a,
166 const std::vector<Math::Matrix4>& b,
167 float weight,
168 std::vector<Math::Matrix4>& out) {
169 float w0 = 1.0f - weight;
170 float w1 = 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;
175 }
176 }
177 }
178}
179
180void AnimatorComponent::ComputeBoneTransforms(float animTime) {
182 int rootIdx = m_skeleton->GetRootNodeIndex();
183 if (rootIdx >= 0) {
184 ProcessNodeHierarchy(rootIdx, identity, animTime);
185 }
186}
187
188void AnimatorComponent::ProcessNodeHierarchy(int nodeIndex,
189 const Math::Matrix4& parentTransform,
190 float animTime) {
191 const NodeData& node = m_skeleton->GetNode(nodeIndex);
192 AnimationClip* clip = m_clips[m_currentClip];
193
194 Math::Matrix4 nodeTransform = node.defaultTransform;
195
196 const AnimationChannel* channel = clip->FindChannel(node.name);
197 if (channel) {
198 Math::Vector3D pos = InterpolatePosition(*channel, animTime);
199 Math::Quaternion rot = InterpolateRotation(*channel, animTime);
200 Math::Vector3D scl = InterpolateScale(*channel, animTime);
201
202 Math::Quaternion rotConj(rot.GetW(), -rot.GetX(), -rot.GetY(), -rot.GetZ());
203
204 Math::Matrix4 scaleMat = Math::Matrix4::Scale(scl);
205 Math::Matrix4 rotMat = Math::Matrix4::Rotate(rotConj);
207
208 nodeTransform = scaleMat * rotMat * transMat;
209 }
210
211 Math::Matrix4 globalTransform = nodeTransform * parentTransform;
212
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();
217 }
218
219 for (int childIdx : node.children) {
220 ProcessNodeHierarchy(childIdx, globalTransform, animTime);
221 }
222}
223
224/// Finds the keyframe pair straddling time and the lerp factor between them.
225template<typename T>
226static std::pair<int, float> FindKeyframe(const std::vector<Keyframe<T>>& keys, float time) {
227 if (keys.size() < 2) return {0, 0.0f};
228
229 // First key in [1, size - 1) later than time; the last key otherwise
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;
234 int next = idx + 1;
235 if (next >= static_cast<int>(keys.size()))
236 return {idx, 0.0f};
237
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))};
241}
242
243/// Componentwise vector lerp.
244static Math::Vector3D LerpVec3(const Math::Vector3D& a, const Math::Vector3D& b, float t) {
245 return Math::Vector3D(
246 a.GetX() + (b.GetX() - a.GetX()) * t,
247 a.GetY() + (b.GetY() - a.GetY()) * t,
248 a.GetZ() + (b.GetZ() - a.GetZ()) * t);
249}
250
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;
256
257 auto [idx, t] = FindKeyframe(keys, time);
258 if (idx + 1 >= static_cast<int>(keys.size())) return keys[idx].value;
259 return LerpVec3(keys[idx].value, keys[idx + 1].value, t);
260}
261
262Math::Quaternion AnimatorComponent::InterpolateRotation(
263 const AnimationChannel& channel, float time) {
264 auto& keys = channel.rotationKeys;
265 if (keys.empty()) return Math::Quaternion();
266 if (keys.size() == 1) return keys[0].value;
267
268 auto [idx, t] = FindKeyframe(keys, time);
269 if (idx + 1 >= static_cast<int>(keys.size())) return keys[idx].value;
270 return Slerp(keys[idx].value, keys[idx + 1].value, t);
271}
272
273Math::Vector3D AnimatorComponent::InterpolateScale(
274 const AnimationChannel& channel, float time) {
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;
278
279 auto [idx, t] = FindKeyframe(keys, time);
280 if (idx + 1 >= static_cast<int>(keys.size())) return keys[idx].value;
281 return LerpVec3(keys[idx].value, keys[idx + 1].value, t);
282}
283
284Math::Quaternion AnimatorComponent::Slerp(const Math::Quaternion& a,
285 const Math::Quaternion& b, float t) {
286 float dot = a.GetW() * b.GetW() + a.GetX() * b.GetX() +
287 a.GetY() * b.GetY() + a.GetZ() * b.GetZ();
288
289 Math::Quaternion b2 = b;
290 if (dot < 0.0f) {
291 b2 = Math::Quaternion(-b.GetW(), -b.GetX(), -b.GetY(), -b.GetZ());
292 dot = -dot;
293 }
294
295 if (dot > 0.9995f) {
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);
301 result.normalize();
302 return result;
303 }
304
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;
309
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);
315}
316
317void AnimatorComponent::Play(const std::string& clipName, bool loop) {
318 for (int i = 0; i < static_cast<int>(m_clips.size()); ++i) {
319 if (m_clips[i] && m_clips[i]->name == clipName) {
320 Play(i, loop);
321 return;
322 }
323 }
324 SLEAK_WARN("AnimatorComponent: Clip '{}' not found", clipName);
325}
326
327void AnimatorComponent::Play(int clipIndex, bool loop) {
328 if (clipIndex < 0 || clipIndex >= static_cast<int>(m_clips.size())) {
329 SLEAK_WARN("AnimatorComponent: Invalid clip index {}", clipIndex);
330 return;
331 }
332 m_currentClip = clipIndex;
333 m_currentTime = 0.0f;
334 m_loop = loop;
335 m_playing = true;
336}
337
339 m_playing = false;
340 m_currentTime = 0.0f;
341}
342
344 m_playing = false;
345}
346
348 if (m_currentClip >= 0)
349 m_playing = true;
350}
351
353 m_speed = speed;
354}
355
357 return m_speed;
358}
359
361 return m_playing;
362}
363
365 return m_currentTime;
366}
367
368const std::string& AnimatorComponent::GetCurrentClipName() const {
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;
372 return empty;
373}
374
378
379} // namespace Sleak
#define SLEAK_INFO(...)
Definition Logger.hpp:20
#define SLEAK_WARN(...)
Definition Logger.hpp:21
const std::string & GetCurrentClipName() const
AnimationStateMachine * CreateStateMachine()
Replaces any existing state machine with a fresh, empty one.
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.
virtual bool Initialize() override
Allocates the bone constant buffer and attaches it to the sibling MeshComponent.
friend class GameObject
Definition Component.hpp:88
GameObject * owner
Definition Component.hpp:84
Component(GameObject *object)
Definition Component.hpp:61
GameObject * GetOwner()
Definition Component.hpp:76
T * GetComponent()
Finds the first attached component of type T, or nullptr.
static Matrix< float, Rows, Rows > Identity()
Definition Matrix.hpp:194
static Matrix< float, 4, 4 > Rotate(const Quaternion &rotation)
Definition Matrix.hpp:371
static Matrix< float, 4, 4 > Scale(const Vector3D &scale)
Definition Matrix.hpp:376
static Matrix< float, 4, 4 > Translate(const Vector3D &translation)
Definition Matrix.hpp:359
Represents a quaternion for 3D rotations.
float GetY() const
Definition Vector.hpp:362
float GetX() const
Definition Vector.hpp:361
float GetZ() const
Definition Vector.hpp:363
static BufferBase * CreateBuffer(BufferType Type, uint32_t Size, void *Data)
Creates a buffer via the currently registered backend factory.
int GetRootNodeIndex() const
Definition Skeleton.hpp:84
Matrix< float, 4, 4 > Matrix4
Definition Matrix.hpp:404
Root namespace for everything the engine exposes.
Definition Camera.hpp:10
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.