-
Notifications
You must be signed in to change notification settings - Fork 474
/
ImporterAnimation.cs
378 lines (326 loc) · 12.3 KB
/
ImporterAnimation.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using GLTF;
using GLTF.Schema;
using UnityEngine;
using UnityGLTF.Cache;
using UnityGLTF.Extensions;
namespace UnityGLTF
{
public partial class GLTFSceneImporter
{
#if UNITY_ANIMATION || !UNITY_2019_1_OR_NEWER
private static string RelativePathFrom(Transform self, Transform root)
{
var path = new List<String>();
for (var current = self; current != null; current = current.parent)
{
if (current == root)
{
return String.Join("/", path.ToArray());
}
path.Insert(0, current.name);
}
throw new Exception("no RelativePath");
}
protected virtual async Task BuildAnimationSamplers(GLTFAnimation animation, int animationId)
{
// look up expected data types
var typeMap = new Dictionary<int, string>();
foreach (var channel in animation.Channels)
{
typeMap[channel.Sampler.Id] = channel.Target.Path.ToString();
}
var samplers = _assetCache.AnimationCache[animationId].Samplers;
var samplersByType = new Dictionary<string, List<AttributeAccessor>>
{
{"time", new List<AttributeAccessor>(animation.Samplers.Count)}
};
for (var i = 0; i < animation.Samplers.Count; i++)
{
// no sense generating unused samplers
if (!typeMap.ContainsKey(i))
{
continue;
}
var samplerDef = animation.Samplers[i];
samplers[i].Interpolation = samplerDef.Interpolation;
// set up input accessors
BufferCacheData inputBufferCacheData = await GetBufferData(samplerDef.Input.Value.BufferView.Value.Buffer);
AttributeAccessor attributeAccessor = new AttributeAccessor
{
AccessorId = samplerDef.Input,
Stream = inputBufferCacheData.Stream,
Offset = inputBufferCacheData.ChunkOffset
};
samplers[i].Input = attributeAccessor;
samplersByType["time"].Add(attributeAccessor);
// set up output accessors
BufferCacheData outputBufferCacheData = await GetBufferData(samplerDef.Output.Value.BufferView.Value.Buffer);
attributeAccessor = new AttributeAccessor
{
AccessorId = samplerDef.Output,
Stream = outputBufferCacheData.Stream,
Offset = outputBufferCacheData.ChunkOffset
};
samplers[i].Output = attributeAccessor;
if (!samplersByType.ContainsKey(typeMap[i]))
{
samplersByType[typeMap[i]] = new List<AttributeAccessor>();
}
samplersByType[typeMap[i]].Add(attributeAccessor);
}
// populate attributeAccessors with buffer data
GLTFHelpers.BuildAnimationSamplers(ref samplersByType);
}
protected void SetAnimationCurve(
AnimationClip clip,
string relativePath,
string[] propertyNames,
NumericArray input,
NumericArray output,
InterpolationType mode,
Type curveType,
ValuesConvertion getConvertedValues)
{
var channelCount = propertyNames.Length;
var frameCount = input.AsFloats.Length;
// copy all the key frame data to cache
Keyframe[][] keyframes = new Keyframe[channelCount][];
for (var ci = 0; ci < channelCount; ++ci)
{
keyframes[ci] = new Keyframe[frameCount];
}
for (var i = 0; i < frameCount; ++i)
{
var time = input.AsFloats[i];
float[] values = null;
float[] inTangents = null;
float[] outTangents = null;
if (mode == InterpolationType.CUBICSPLINE)
{
// For cubic spline, the output will contain 3 values per keyframe; inTangent, dataPoint, and outTangent.
// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
var cubicIndex = i * 3;
inTangents = getConvertedValues(output, cubicIndex);
values = getConvertedValues(output, cubicIndex + 1);
outTangents = getConvertedValues(output, cubicIndex + 2);
}
else
{
// For other interpolation types, the output will only contain one value per keyframe
values = getConvertedValues(output, i);
}
for (var ci = 0; ci < channelCount; ++ci)
{
if (mode == InterpolationType.CUBICSPLINE)
{
keyframes[ci][i] = new Keyframe(time, values[ci], inTangents[ci], outTangents[ci]);
}
else
{
keyframes[ci][i] = new Keyframe(time, values[ci]);
}
}
}
if (mode == InterpolationType.LINEAR && channelCount == 4 && propertyNames.All(p => p == "localRotation.x" || p == "localRotation.y" || p == "localRotation.z" || p == "localRotation.w"))
{
Quaternion prev = Quaternion.identity;
for (int i = 0; i < keyframes[0].Length; i++)
{
Quaternion q = new Quaternion(keyframes[0][i].value, keyframes[1][i].value, keyframes[2][i].value, keyframes[3][i].value);
if (i > 0)
{
if (Quaternion.Dot(prev, q) < 0)
q = new Quaternion(-q.x, -q.y, -q.z, -q.w);
keyframes[0][i].value = q.x;
keyframes[1][i].value = q.y;
keyframes[2][i].value = q.z;
keyframes[3][i].value = q.w;
}
prev = q;
}
}
for (var ci = 0; ci < channelCount; ci++)
{
if (mode != InterpolationType.CUBICSPLINE)
{
// For cubic spline interpolation, the inTangents and outTangents are already explicitly defined.
// For the rest, set them appropriately.
for (var i = 0; i < keyframes[ci].Length; i++)
{
SetTangentMode(keyframes[ci], i, mode);
}
}
// copy all key frames data to animation curve and add it to the clip
AnimationCurve curve = new AnimationCurve(keyframes[ci]);
#if !UNITY_EDITOR
// Only in editor SetCurve works with non-legacy clips
if (clip.legacy)
#endif
clip.SetCurve(relativePath, curveType, propertyNames[ci], curve);
}
}
private static void SetTangentMode(Keyframe[] keyframes, int keyframeIndex, InterpolationType interpolation)
{
var key = keyframes[keyframeIndex];
switch (interpolation)
{
case InterpolationType.CATMULLROMSPLINE:
key.inTangent = 0;
key.outTangent = 0;
break;
case InterpolationType.LINEAR:
key.inTangent = GetCurveKeyframeLeftLinearSlope(keyframes, keyframeIndex);
key.outTangent = GetCurveKeyframeLeftLinearSlope(keyframes, keyframeIndex + 1);
break;
case InterpolationType.STEP:
key.inTangent = float.PositiveInfinity;
key.outTangent = 0;
break;
default:
throw new NotImplementedException();
}
keyframes[keyframeIndex] = key;
}
private static float GetCurveKeyframeLeftLinearSlope(Keyframe[] keyframes, int keyframeIndex)
{
if (keyframeIndex <= 0 || keyframeIndex >= keyframes.Length)
{
return 0;
}
var valueDelta = keyframes[keyframeIndex].value - keyframes[keyframeIndex - 1].value;
var timeDelta = keyframes[keyframeIndex].time - keyframes[keyframeIndex - 1].time;
if (timeDelta <= 0)
{
var k = keyframes[keyframeIndex];
k.time = keyframes[keyframeIndex - 1].time + Mathf.Epsilon + 1 / 100f;
keyframes[keyframeIndex] = k;
Debug.Log(LogType.Warning, "Time of subsequent animation keyframes is not increasing (glTF-Validator error ACCESSOR_ANIMATION_INPUT_NON_INCREASING)");
return float.PositiveInfinity;
}
return valueDelta / timeDelta;
}
protected async Task<AnimationClip> ConstructClip(Transform root, int animationId, CancellationToken cancellationToken)
{
GLTFAnimation animation = _gltfRoot.Animations[animationId];
AnimationCacheData animationCache = _assetCache.AnimationCache[animationId];
if (animationCache == null)
{
animationCache = new AnimationCacheData(animation.Samplers.Count);
_assetCache.AnimationCache[animationId] = animationCache;
}
else if (animationCache.LoadedAnimationClip != null)
{
return animationCache.LoadedAnimationClip;
}
// unpack accessors
await BuildAnimationSamplers(animation, animationId);
// init clip
AnimationClip clip = new AnimationClip
{
name = animation.Name ?? $"animation:{animationId}",
};
_assetCache.AnimationCache[animationId].LoadedAnimationClip = clip;
if (_options.AnimationMethod == AnimationMethod.Legacy)
clip.legacy = true;
foreach (AnimationChannel channel in animation.Channels)
{
AnimationSamplerCacheData samplerCache = animationCache.Samplers[channel.Sampler.Id];
if (channel.Target.Node == null)
{
// If a channel doesn't have a target node, then just skip it.
// This is legal and is present in one of the asset generator models, but means that animation doesn't actually do anything.
// https://github.com/KhronosGroup/glTF-Asset-Generator/tree/master/Output/Positive/Animation_NodeMisc
// Model 08
continue;
}
var node = await GetNode(channel.Target.Node.Id, cancellationToken);
string relativePath = RelativePathFrom(node.transform, root);
NumericArray input = samplerCache.Input.AccessorContent,
output = samplerCache.Output.AccessorContent;
string[] propertyNames;
var known = Enum.TryParse(channel.Target.Path, out GLTFAnimationChannelPath path);
if (!known) continue;
switch (path)
{
case GLTFAnimationChannelPath.translation:
propertyNames = new string[] { "localPosition.x", "localPosition.y", "localPosition.z" };
#if UNITY_EDITOR
// TODO technically this should be postprocessing in the ScriptedImporter instead,
// but performance is much better if we do it when constructing the clips
var factor = Context?.ImportScaleFactor ?? 1f;
#endif
SetAnimationCurve(clip, relativePath, propertyNames, input, output,
samplerCache.Interpolation, typeof(Transform),
(data, frame) =>
{
var position = data.AsVec3s[frame].ToUnityVector3Convert();
#if UNITY_EDITOR
return new float[] { position.x * factor, position.y * factor, position.z * factor};
#else
return new float[] { position.x, position.y, position.z };
#endif
});
break;
case GLTFAnimationChannelPath.rotation:
propertyNames = new string[] { "localRotation.x", "localRotation.y", "localRotation.z", "localRotation.w" };
SetAnimationCurve(clip, relativePath, propertyNames, input, output,
samplerCache.Interpolation, typeof(Transform),
(data, frame) =>
{
var rotation = data.AsVec4s[frame];
var quaternion = new GLTF.Math.Quaternion(rotation.X, rotation.Y, rotation.Z, rotation.W).ToUnityQuaternionConvert();
return new float[] { quaternion.x, quaternion.y, quaternion.z, quaternion.w };
});
break;
case GLTFAnimationChannelPath.scale:
propertyNames = new string[] { "localScale.x", "localScale.y", "localScale.z" };
SetAnimationCurve(clip, relativePath, propertyNames, input, output,
samplerCache.Interpolation, typeof(Transform),
(data, frame) =>
{
var scale = data.AsVec3s[frame].ToUnityVector3Raw();
return new float[] { scale.x, scale.y, scale.z };
});
break;
case GLTFAnimationChannelPath.weights:
var primitives = channel.Target.Node.Value.Mesh.Value.Primitives;
if (primitives[0].Targets == null) break;
var targetCount = primitives[0].Targets.Count;
for (int primitiveIndex = 0; primitiveIndex < primitives.Count; primitiveIndex++)
{
// see SceneImporter:156
// blend shapes are always called "Morphtarget" and always have frame weight 100 on import
var prim = primitives[primitiveIndex];
var targetNames = prim.TargetNames;
propertyNames = new string[targetCount];
for (var i = 0; i < targetCount; i++)
propertyNames[i] = _options.ImportBlendShapeNames ? ("blendShape." + (targetNames != null ? targetNames[i] : ("Morphtarget" + i))) : "blendShape."+i.ToString();
var frameFloats = new float[targetCount];
SetAnimationCurve(clip, relativePath, propertyNames, input, output,
samplerCache.Interpolation, typeof(SkinnedMeshRenderer),
(data, frame) =>
{
var allValues = data.AsFloats;
for (var k = 0; k < targetCount; k++)
frameFloats[k] = allValues[frame * targetCount + k];
return frameFloats;
});
}
break;
default:
Debug.Log(LogType.Warning, "Cannot read GLTF animation path");
break;
} // switch target type
} // foreach channel
// EnsureQuaternionContinuity results in unwanted tangents on the first and last keyframes > custom Solution in SetAnimationCurve
//clip.EnsureQuaternionContinuity();
return clip;
}
#endif
}
}