Debian Codegraph @

libs/gltfio/src/Animator.cpp

raw
1 /*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <gltfio/Animator.h>
18
19 #include "FFilamentAsset.h"
20 #include "FFilamentInstance.h"
21 #include "MorphHelper.h"
22 #include "math.h"
23 #include "upcast.h"
24
25 #include <filament/MaterialEnums.h>
26 #include <filament/RenderableManager.h>
27 #include <filament/TransformManager.h>
28
29 #include <utils/Log.h>
30
31 #include <math/mat4.h>
32 #include <math/quat.h>
33 #include <math/scalar.h>
34 #include <math/vec3.h>
35 #include <math/vec4.h>
36
37 #include <map>
38 #include <string>
39 #include <vector>
40
41 using namespace filament;
42 using namespace filament::math;
43 using namespace std;
44 using namespace utils;
45
46 namespace gltfio {
47
48 using TimeValues = map<float, size_t>;
49 using SourceValues = vector<float>;
50 using BoneVector = vector<filament::math::mat4f>;
51
52 struct Sampler {
53 TimeValues times;
54 SourceValues values;
55 enum { LINEAR, STEP, CUBIC } interpolation;
56 };
57
58 struct Channel {
59 const Sampler* sourceData;
60 Entity targetEntity;
61 enum { TRANSLATION, ROTATION, SCALE, WEIGHTS } transformType;
62 };
63
64 struct Animation {
65 float duration;
66 std::string name;
67 vector<Sampler> samplers;
68 vector<Channel> channels;
69 };
70
71 struct AnimatorImpl {
72 vector<Animation> animations;
73 BoneVector boneMatrices;
74 FFilamentAsset* asset = nullptr;
75 FFilamentInstance* instance = nullptr;
76 RenderableManager* renderableManager;
77 TransformManager* transformManager;
78 vector<float> weights;
79 MorphHelper* morpher;
80 void addChannels(const NodeMap& nodeMap, const cgltf_animation& srcAnim, Animation& dst);
81 void applyAnimation(const Channel& channel, float t, size_t prevIndex, size_t nextIndex);
82 };
83
84 static void createSampler(const cgltf_animation_sampler& src, Sampler& dst) {
85 // Copy the time values into a red-black tree.
86 const cgltf_accessor* timelineAccessor = src.input;
87 const uint8_t* timelineBlob = (const uint8_t*) timelineAccessor->buffer_view->buffer->data;
88 const float* timelineFloats = (const float*) (timelineBlob + timelineAccessor->offset +
89 timelineAccessor->buffer_view->offset);
90 for (size_t i = 0, len = timelineAccessor->count; i < len; ++i) {
91 dst.times[timelineFloats[i]] = i;
92 }
93
94 // Convert source data to float.
95 const cgltf_accessor* valuesAccessor = src.output;
96 switch (valuesAccessor->type) {
97 case cgltf_type_scalar:
98 dst.values.resize(valuesAccessor->count);
99 cgltf_accessor_unpack_floats(src.output, &dst.values[0], valuesAccessor->count);
100 break;
101 case cgltf_type_vec3:
102 dst.values.resize(valuesAccessor->count * 3);
103 cgltf_accessor_unpack_floats(src.output, &dst.values[0], valuesAccessor->count * 3);
104 break;
105 case cgltf_type_vec4:
106 dst.values.resize(valuesAccessor->count * 4);
107 cgltf_accessor_unpack_floats(src.output, &dst.values[0], valuesAccessor->count * 4);
108 break;
109 default:
110 GLTFIO_WARN("Unknown animation type.");
111 return;
112 }
113
114 switch (src.interpolation) {
115 case cgltf_interpolation_type_linear:
116 dst.interpolation = Sampler::LINEAR;
117 break;
118 case cgltf_interpolation_type_step:
119 dst.interpolation = Sampler::STEP;
120 break;
121 case cgltf_interpolation_type_cubic_spline:
122 dst.interpolation = Sampler::CUBIC;
123 break;
124 }
125 }
126
127 static void setTransformType(const cgltf_animation_channel& src, Channel& dst) {
128 switch (src.target_path) {
129 case cgltf_animation_path_type_translation:
130 dst.transformType = Channel::TRANSLATION;
131 break;
132 case cgltf_animation_path_type_rotation:
133 dst.transformType = Channel::ROTATION;
134 break;
135 case cgltf_animation_path_type_scale:
136 dst.transformType = Channel::SCALE;
137 break;
138 case cgltf_animation_path_type_weights:
139 dst.transformType = Channel::WEIGHTS;
140 break;
141 case cgltf_animation_path_type_invalid:
142 GLTFIO_WARN("Unsupported channel path.");
143 break;
144 }
145 }
146
147 static bool validateAnimation(const cgltf_animation& anim) {
148 for (cgltf_size j = 0; j < anim.channels_count; ++j) {
149 const cgltf_animation_channel& channel = anim.channels[j];
150 const cgltf_animation_sampler* sampler = channel.sampler;
151 if (!channel.target_node) {
152 continue;
153 }
154 if (!channel.sampler) {
155 return false;
156 }
157 cgltf_size components = 1;
158 if (channel.target_path == cgltf_animation_path_type_weights) {
159 if (!channel.target_node->mesh || !channel.target_node->mesh->primitives_count) {
160 return false;
161 }
162 components = channel.target_node->mesh->primitives[0].targets_count;
163 }
164 cgltf_size values = sampler->interpolation == cgltf_interpolation_type_cubic_spline ? 3 : 1;
165 if (sampler->input->count * components * values != sampler->output->count) {
166 return false;
167 }
168 }
169 return true;
170 }
171
172 Animator::Animator(FFilamentAsset* asset, FFilamentInstance* instance) {
173 assert(asset->mResourcesLoaded && asset->mSourceAsset);
174 mImpl = new AnimatorImpl();
175 mImpl->asset = asset;
176 mImpl->instance = instance;
177 mImpl->renderableManager = &asset->mEngine->getRenderableManager();
178 mImpl->transformManager = &asset->mEngine->getTransformManager();
179 mImpl->morpher = new MorphHelper(asset, instance);
180
181 const cgltf_data* srcAsset = asset->mSourceAsset->hierarchy;
182 const cgltf_animation* srcAnims = srcAsset->animations;
183 for (cgltf_size i = 0, len = srcAsset->animations_count; i < len; ++i) {
184 const cgltf_animation& anim = srcAnims[i];
185 if (!validateAnimation(anim)) {
186 GLTFIO_WARN("Disabling animation due to validation failure.");
187 return;
188 }
189 }
190
191 // Loop over the glTF animation definitions.
192 mImpl->animations.resize(srcAsset->animations_count);
193 for (cgltf_size i = 0, len = srcAsset->animations_count; i < len; ++i) {
194 const cgltf_animation& srcAnim = srcAnims[i];
195 Animation& dstAnim = mImpl->animations[i];
196 dstAnim.duration = 0;
197 if (srcAnim.name) {
198 dstAnim.name = srcAnim.name;
199 }
200
201 // Import each glTF sampler into a custom data structure.
202 cgltf_animation_sampler* srcSamplers = srcAnim.samplers;
203 dstAnim.samplers.resize(srcAnim.samplers_count);
204 for (cgltf_size j = 0, nsamps = srcAnim.samplers_count; j < nsamps; ++j) {
205 const cgltf_animation_sampler& srcSampler = srcSamplers[j];
206 Sampler& dstSampler = dstAnim.samplers[j];
207 createSampler(srcSampler, dstSampler);
208 if (dstSampler.times.size() > 1) {
209 float maxtime = (--dstSampler.times.end())->first;
210 dstAnim.duration = std::max(dstAnim.duration, maxtime);
211 }
212 }
213
214 // Import each glTF channel into a custom data structure.
215 if (instance) {
216 mImpl->addChannels(instance->nodeMap, srcAnim, dstAnim);
217 } else if (!asset->isInstanced()) {
218 mImpl->addChannels(asset->mNodeMap, srcAnim, dstAnim);
219 } else {
220 for (FFilamentInstance* instance : asset->mInstances) {
221 mImpl->addChannels(instance->nodeMap, srcAnim, dstAnim);
222 }
223 }
224 }
225 }
226
227 void Animator::addInstance(FFilamentInstance* instance) {
228 const cgltf_data* srcAsset = mImpl->asset->mSourceAsset->hierarchy;
229 const cgltf_animation* srcAnims = srcAsset->animations;
230 for (cgltf_size i = 0, len = srcAsset->animations_count; i < len; ++i) {
231 const cgltf_animation& srcAnim = srcAnims[i];
232 Animation& dstAnim = mImpl->animations[i];
233 mImpl->addChannels(instance->nodeMap, srcAnim, dstAnim);
234 }
235 }
236
237 Animator::~Animator() {
238 delete mImpl->morpher;
239 delete mImpl;
240 }
241
242 size_t Animator::getAnimationCount() const {
243 return mImpl->animations.size();
244 }
245
246 void Animator::applyAnimation(size_t animationIndex, float time) const {
247 const Animation& anim = mImpl->animations[animationIndex];
248 TransformManager* transformManager = mImpl->transformManager;
249 RenderableManager* renderableManager = mImpl->renderableManager;
250 time = fmod(time, anim.duration);
251 for (const auto& channel : anim.channels) {
252 const Sampler* sampler = channel.sourceData;
253 if (sampler->times.size() < 2) {
254 continue;
255 }
256
257 const TimeValues& times = sampler->times;
258
259 // Find the first keyframe after the given time, or the keyframe that matches it exactly.
260 TimeValues::const_iterator iter = times.lower_bound(time);
261
262 // Compute the interpolant (between 0 and 1) and determine the keyframe pair.
263 float t = 0.0f;
264 size_t nextIndex;
265 size_t prevIndex;
266 if (iter == times.end()) {
267 nextIndex = times.size() - 1;
268 prevIndex = nextIndex;
269 } else if (iter == times.begin()) {
270 nextIndex = 0;
271 prevIndex = 0;
272 } else {
273 TimeValues::const_iterator prev = iter; --prev;
274 nextIndex = iter->second;
275 prevIndex = prev->second;
276 const float nextTime = iter->first;
277 const float prevTime = prev->first;
278 float deltaTime = nextTime - prevTime;
279 assert(deltaTime >= 0);
280 if (deltaTime > 0) {
281 t = (time - prevTime) / deltaTime;
282 }
283 }
284
285 if (sampler->interpolation == Sampler::STEP) {
286 t = 0.0f;
287 }
288
289 mImpl->applyAnimation(channel, t, prevIndex, nextIndex);
290 }
291 }
292
293 void Animator::updateBoneMatrices() {
294 auto renderableManager = mImpl->renderableManager;
295 auto transformManager = mImpl->transformManager;
296
297 auto update = [=](const SkinVector& skins, BoneVector& boneVector) {
298 for (const auto& skin : skins) {
299 size_t njoints = skin.joints.size();
300 boneVector.resize(njoints);
301 for (const auto& entity : skin.targets) {
302 auto renderable = renderableManager->getInstance(entity);
303 if (!renderable) {
304 continue;
305 }
306 mat4f inverseGlobalTransform;
307 auto xformable = transformManager->getInstance(entity);
308 if (xformable) {
309 inverseGlobalTransform = inverse(transformManager->getWorldTransform(xformable));
310 }
311 for (size_t boneIndex = 0; boneIndex < njoints; ++boneIndex) {
312 const auto& joint = skin.joints[boneIndex];
313 TransformManager::Instance jointInstance = transformManager->getInstance(joint);
314 mat4f globalJointTransform = transformManager->getWorldTransform(jointInstance);
315 boneVector[boneIndex] =
316 inverseGlobalTransform *
317 globalJointTransform *
318 skin.inverseBindMatrices[boneIndex];
319 }
320 renderableManager->setBones(renderable, boneVector.data(), boneVector.size());
321 }
322 }
323 };
324
325 if (mImpl->instance) {
326 update(mImpl->instance->skins, mImpl->boneMatrices);
327 } else if (!mImpl->asset->isInstanced()) {
328 update(mImpl->asset->mSkins, mImpl->boneMatrices);
329 } else {
330 for (FFilamentInstance* instance : mImpl->asset->mInstances) {
331 update(instance->skins, mImpl->boneMatrices);
332 }
333 }
334 }
335
336 float Animator::getAnimationDuration(size_t animationIndex) const {
337 return mImpl->animations[animationIndex].duration;
338 }
339
340 const char* Animator::getAnimationName(size_t animationIndex) const {
341 return mImpl->animations[animationIndex].name.c_str();
342 }
343
344
345 void AnimatorImpl::addChannels(const NodeMap& nodeMap, const cgltf_animation& srcAnim,
346 Animation& dst) {
347 cgltf_animation_channel* srcChannels = srcAnim.channels;
348 cgltf_animation_sampler* srcSamplers = srcAnim.samplers;
349 const Sampler* samplers = dst.samplers.data();
350 for (cgltf_size j = 0, nchans = srcAnim.channels_count; j < nchans; ++j) {
351 const cgltf_animation_channel& srcChannel = srcChannels[j];
352 auto iter = nodeMap.find(srcChannel.target_node);
353 if (UTILS_UNLIKELY(iter == nodeMap.end())) {
354 if (GLTFIO_VERBOSE) {
355 slog.w << "No scene root contains node ";
356 if (srcChannel.target_node->name) {
357 slog.w << "'" << srcChannel.target_node->name << "' ";
358 }
359 slog.w << "for animation ";
360 if (srcAnim.name) {
361 slog.w << "'" << srcAnim.name << "' ";
362 }
363 slog.w << "in channel " << j << io::endl;
364 }
365 continue;
366 }
367 Entity targetEntity = iter.value();
368 Channel dstChannel;
369 dstChannel.sourceData = samplers + (srcChannel.sampler - srcSamplers);
370 dstChannel.targetEntity = targetEntity;
371 setTransformType(srcChannel, dstChannel);
372 dst.channels.push_back(dstChannel);
373 }
374 }
375
376 void AnimatorImpl::applyAnimation(const Channel& channel, float t, size_t prevIndex,
377 size_t nextIndex) {
378 const Sampler* sampler = channel.sourceData;
379 const TimeValues& times = sampler->times;
380 TransformManager::Instance node = transformManager->getInstance(channel.targetEntity);
381
382 // Perform the interpolation. This is a simple but inefficient implementation; Filament
383 // stores transforms as mat4's but glTF animation is based on TRS (translation rotation
384 // scale).
385 mat4f xform = transformManager->getTransform(node);
386 float3 scale;
387 quatf rotation;
388 float3 translation;
389 decomposeMatrix(xform, &translation, &rotation, &scale);
390
391 switch (channel.transformType) {
392
393 case Channel::SCALE: {
394 const float3* srcVec3 = (const float3*) sampler->values.data();
395 if (sampler->interpolation == Sampler::CUBIC) {
396 float3 vert0 = srcVec3[prevIndex * 3 + 1];
397 float3 tang0 = srcVec3[prevIndex * 3 + 2];
398 float3 tang1 = srcVec3[nextIndex * 3];
399 float3 vert1 = srcVec3[nextIndex * 3 + 1];
400 scale = cubicSpline(vert0, tang0, vert1, tang1, t);
401 } else {
402 scale = ((1 - t) * srcVec3[prevIndex]) + (t * srcVec3[nextIndex]);
403 }
404 break;
405 }
406
407 case Channel::TRANSLATION: {
408 const float3* srcVec3 = (const float3*) sampler->values.data();
409 if (sampler->interpolation == Sampler::CUBIC) {
410 float3 vert0 = srcVec3[prevIndex * 3 + 1];
411 float3 tang0 = srcVec3[prevIndex * 3 + 2];
412 float3 tang1 = srcVec3[nextIndex * 3];
413 float3 vert1 = srcVec3[nextIndex * 3 + 1];
414 translation = cubicSpline(vert0, tang0, vert1, tang1, t);
415 } else {
416 translation = ((1 - t) * srcVec3[prevIndex]) + (t * srcVec3[nextIndex]);
417 }
418 break;
419 }
420
421 case Channel::ROTATION: {
422 const quatf* srcQuat = (const quatf*) sampler->values.data();
423 if (sampler->interpolation == Sampler::CUBIC) {
424 quatf vert0 = srcQuat[prevIndex * 3 + 1];
425 quatf tang0 = srcQuat[prevIndex * 3 + 2];
426 quatf tang1 = srcQuat[nextIndex * 3];
427 quatf vert1 = srcQuat[nextIndex * 3 + 1];
428 rotation = normalize(cubicSpline(vert0, tang0, vert1, tang1, t));
429 } else {
430 rotation = slerp(srcQuat[prevIndex], srcQuat[nextIndex], t);
431 }
432 break;
433 }
434
435 case Channel::WEIGHTS: {
436 const float* const samplerValues = sampler->values.data();
437 assert(sampler->values.size() % times.size() == 0);
438 const int valuesPerKeyframe = sampler->values.size() / times.size();
439
440 if (sampler->interpolation == Sampler::CUBIC) {
441 assert(valuesPerKeyframe % 3 == 0);
442 const int numMorphTargets = valuesPerKeyframe / 3;
443 const float* const inTangents = samplerValues;
444 const float* const splineVerts = samplerValues + numMorphTargets;
445 const float* const outTangents = samplerValues + numMorphTargets * 2;
446
447 weights.resize(numMorphTargets);
448 for (int comp = 0; comp < numMorphTargets; ++comp) {
449 float vert0 = splineVerts[comp + prevIndex * valuesPerKeyframe];
450 float tang0 = outTangents[comp + prevIndex * valuesPerKeyframe];
451 float tang1 = inTangents[comp + nextIndex * valuesPerKeyframe];
452 float vert1 = splineVerts[comp + nextIndex * valuesPerKeyframe];
453 weights[comp] = cubicSpline(vert0, tang0, vert1, tang1, t);
454 }
455 } else {
456 weights.resize(valuesPerKeyframe);
457 for (int comp = 0; comp < valuesPerKeyframe; ++comp) {
458 float previous = samplerValues[comp + prevIndex * valuesPerKeyframe];
459 float current = samplerValues[comp + nextIndex * valuesPerKeyframe];
460 weights[comp] = (1 - t) * previous + t * current;
461 }
462 }
463
464 morpher->applyWeights(channel.targetEntity, weights.data(), weights.size());
465 return;
466 }
467 }
468
469 xform = composeMatrix(translation, rotation, scale);
470 transformManager->setTransform(node, xform);
471 }
472
473 } // namespace gltfio