-
Notifications
You must be signed in to change notification settings - Fork 474
/
GLTFRecorder.cs
486 lines (414 loc) · 15.5 KB
/
GLTFRecorder.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#define USE_ANIMATION_POINTER
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using GLTF.Schema;
using Unity.Profiling;
using UnityEngine;
using Object = UnityEngine.Object;
namespace UnityGLTF.Timeline
{
public class GLTFRecorder
{
public GLTFRecorder(Transform root, bool recordBlendShapes = true, bool recordRootInWorldSpace = false, bool recordAnimationPointer = false)
{
if (!root)
throw new ArgumentNullException(nameof(root), "Please provide a root transform to record.");
this.root = root;
this.recordBlendShapes = recordBlendShapes;
this.recordRootInWorldSpace = recordRootInWorldSpace;
this.recordAnimationPointer = recordAnimationPointer;
}
/// <summary>
/// Optionally assign a list of transforms to be recorded, other transforms will be ignored
/// </summary>
internal ICollection<Transform> recordingList = null;
private bool AllowRecordingTransform(Transform tr) => recordingList == null || recordingList.Contains(tr);
private Transform root;
private Dictionary<Transform, AnimationData> data = new Dictionary<Transform, AnimationData>(64);
private double startTime;
private double lastRecordedTime;
private bool hasRecording;
private bool isRecording;
private readonly bool recordBlendShapes;
private readonly bool recordRootInWorldSpace;
private readonly bool recordAnimationPointer;
public bool HasRecording => hasRecording;
public bool IsRecording => isRecording;
public double LastRecordedTime => lastRecordedTime;
public string AnimationName = "Recording";
public delegate void OnBeforeAddAnimationDataDelegate(PostAnimationData animationData);
public delegate void OnPostExportDelegate(PostExportArgs animationData);
/// <summary>
/// Callback to modify the animation data before it is added to the animation.
/// Is called once for each track after the recording has ended. This is a non destructive callback,
/// so the original recorded data is not modified. Every time you call EndRecording to the save the gltf/glb,
/// you can modify the data again.
/// </summary>
public OnBeforeAddAnimationDataDelegate OnBeforeAddAnimationData;
/// <summary>
/// Callback to modify or add additional data to the gltf root after the recording has ended and animation
/// data is added to the animation.
/// </summary>
public OnPostExportDelegate OnPostExport;
public class PostExportArgs
{
public Bounds AnimationTranslationBounds { get; private set; }
public GLTFSceneExporter Exporter { get; private set; }
public GLTFRoot GltfRoot { get; private set; }
internal PostExportArgs(Bounds animationTranslationBounds, GLTFSceneExporter exporter, GLTFRoot gltfRoot)
{
this.AnimationTranslationBounds = animationTranslationBounds;
this.Exporter = exporter;
this.GltfRoot = gltfRoot;
}
}
public class PostAnimationData
{
internal AnimationData.Track animationTrack;
public float[] Times;
public object[] Values;
public Object AnimatedObject => animationTrack.animatedObject;
public string PropertyName => animationTrack.propertyName;
internal PostAnimationData(AnimationData.Track tr, float[] times, object[] values)
{
this.animationTrack = tr;
this.Times = times;
this.Values = values;
}
}
internal class AnimationData
{
internal Transform tr;
private SkinnedMeshRenderer smr;
private bool recordBlendShapes;
private bool inWorldSpace = false;
private bool recordAnimationPointer;
#if USE_ANIMATION_POINTER
private static List<ExportPlan> exportPlans;
private static MaterialPropertyBlock materialPropertyBlock = new MaterialPropertyBlock();
internal List<Track> tracks = new List<Track>();
internal class ExportPlan
{
public string propertyName;
public Type dataType;
public Func<Transform, Object> GetTarget;
public Func<Transform, Object, AnimationData, object> GetData;
public ExportPlan(string propertyName, Type dataType, Func<Transform, Object> GetTarget, Func<Transform, Object, AnimationData, object> GetData)
{
this.propertyName = propertyName;
this.dataType = dataType;
this.GetTarget = GetTarget;
this.GetData = GetData;
}
public object Sample(AnimationData data)
{
var target = GetTarget(data.tr);
return GetData(data.tr, target, data);
}
}
#endif
public AnimationData(Transform tr, double time, bool zeroScale = false, bool recordBlendShapes = true, bool inWorldSpace = false, bool recordAnimationPointer = false)
{
this.tr = tr;
this.smr = tr.GetComponent<SkinnedMeshRenderer>();
this.recordBlendShapes = recordBlendShapes;
this.inWorldSpace = inWorldSpace;
this.recordAnimationPointer = recordAnimationPointer;
if (exportPlans == null)
{
exportPlans = new List<ExportPlan>();
exportPlans.Add(new ExportPlan("translation", typeof(Vector3), x => x, (tr0, _, options) => options.inWorldSpace ? tr0.position : tr0.localPosition));
exportPlans.Add(new ExportPlan("rotation", typeof(Quaternion), x => x, (tr0, _, options) =>
{
var q = options.inWorldSpace ? tr0.rotation : tr0.localRotation;
return new Quaternion(q.x, q.y, q.z, q.w);
}));
exportPlans.Add(new ExportPlan("scale", typeof(Vector3), x => x, (tr0, _, options) => options.inWorldSpace ? tr0.lossyScale : tr0.localScale));
if (recordBlendShapes)
{
exportPlans.Add(new ExportPlan("weights", typeof(float[]),
x => x.GetComponent<SkinnedMeshRenderer>(), (tr0, x, options) =>
{
if (x is SkinnedMeshRenderer skinnedMesh && skinnedMesh.sharedMesh)
{
var mesh = skinnedMesh.sharedMesh;
var blendShapeCount = mesh.blendShapeCount;
if (blendShapeCount == 0) return null;
var weights = new float[blendShapeCount];
for (var i = 0; i < blendShapeCount; i++)
weights[i] = skinnedMesh.GetBlendShapeWeight(i);
return weights;
}
return null;
}));
}
if (recordAnimationPointer)
{
// TODO add other animation pointer export plans
exportPlans.Add(new ExportPlan("baseColorFactor", typeof(Color), x => x.GetComponent<MeshRenderer>() ? x.GetComponent<MeshRenderer>().sharedMaterial : null, (tr0, mat, options) =>
{
var r = tr0.GetComponent<Renderer>();
if (r.HasPropertyBlock())
{
r.GetPropertyBlock(materialPropertyBlock);
#if UNITY_2021_1_OR_NEWER
if (materialPropertyBlock.HasColor("_BaseColor")) return materialPropertyBlock.GetColor("_BaseColor").linear;
if (materialPropertyBlock.HasColor("_Color")) return materialPropertyBlock.GetColor("_Color").linear;
if (materialPropertyBlock.HasColor("baseColorFactor")) return materialPropertyBlock.GetColor("baseColorFactor").linear;
#else
var c = materialPropertyBlock.GetColor("_BaseColor");
if (c.r != 0 || c.g != 0 || c.b != 0 || c.a != 0) return c;
c = materialPropertyBlock.GetColor("_Color");
if (c.r != 0 || c.g != 0 || c.b != 0 || c.a != 0) return c;
// this leaves an edge case where someone is actually animating color to black:
// in that case, the un-animated color would now be exported...
#endif
}
if (mat is Material m && m)
{
if (m.HasProperty("_BaseColor")) return m.GetColor("_BaseColor").linear;
if (m.HasProperty("_Color")) return m.GetColor("_Color").linear;
if (m.HasProperty("baseColorFactor")) return m.GetColor("baseColorFactor").linear;
}
return null;
}));
}
}
foreach (var plan in exportPlans)
{
if (plan.GetTarget(tr)) {
tracks.Add(new Track(this, plan, time));
}
}
}
internal class Track
{
public Object animatedObject => plan.GetTarget(tr.tr);
public string propertyName => plan.propertyName;
// TODO sample as floats?
public float[] times => samples.Keys.Select(x => (float) x).ToArray();
public object[] values => samples.Values.ToArray();
private AnimationData tr;
private ExportPlan plan;
private Dictionary<double, object> samples;
private object lastSample;
public Track(AnimationData tr, ExportPlan plan, double time)
{
this.tr = tr;
this.plan = plan;
samples = new Dictionary<double, object>();
SampleIfChanged(time);
}
public void SampleIfChanged(double time)
{
var value = plan.Sample(tr);
if (value == null || (value is Object o && !o))
return;
if (!value.Equals(lastSample))
{
samples[time] = value;
lastSample = value;
}
}
}
public void Update(double time)
{
foreach (var track in tracks)
{
track.SampleIfChanged(time);
}
}
}
public void StartRecording(double time)
{
startTime = time;
lastRecordedTime = time;
var trs = root.GetComponentsInChildren<Transform>(true);
data.Clear();
foreach (var tr in trs)
{
if (!AllowRecordingTransform(tr)) continue;
data.Add(tr, new AnimationData(tr, 0, !tr.gameObject.activeSelf, recordBlendShapes, recordRootInWorldSpace && tr == root, recordAnimationPointer));
}
isRecording = true;
hasRecording = true;
}
public void UpdateRecording(double time)
{
if (!isRecording)
{
throw new InvalidOperationException($"{nameof(GLTFRecorder)} isn't recording, but {nameof(UpdateRecording)} was called. This is invalid.");
}
if (time <= lastRecordedTime)
{
Debug.LogWarning("Can't record backwards in time, please avoid this.");
return;
}
var currentTime = time - startTime;
var trs = root.GetComponentsInChildren<Transform>(true);
foreach (var tr in trs)
{
if (!AllowRecordingTransform(tr)) continue;
if (!data.ContainsKey(tr))
{
// insert "empty" frame with scale=0,0,0 because this object might have just appeared in this frame
var emptyData = new AnimationData(tr, lastRecordedTime, true, recordBlendShapes, recordAnimationPointer);
data.Add(tr, emptyData);
// insert actual keyframe
data[tr].Update(currentTime);
}
else
data[tr].Update(currentTime);
}
lastRecordedTime = time;
}
internal void EndRecording(out Dictionary<Transform, AnimationData> param)
{
param = null;
if (!hasRecording) return;
param = data;
}
public void EndRecording(string filename, string sceneName = "scene", GLTFSettings settings = null)
{
if (!hasRecording) return;
var dir = Path.GetDirectoryName(filename);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) Directory.CreateDirectory(dir);
using (var filestream = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
EndRecording(filestream, sceneName, settings);
}
}
public void EndRecording(Stream stream, string sceneName = "scene", GLTFSettings settings = null)
{
if (!hasRecording) return;
isRecording = false;
Debug.Log("Gltf Recording saved. Tracks: " + data.Count + ", Total Keyframes: " + data.Sum(x => x.Value.tracks.Sum(y => y.values.Count())));
if (!settings)
{
var adjustedSettings = Object.Instantiate(GLTFSettings.GetOrCreateSettings());
adjustedSettings.ExportDisabledGameObjects = true;
adjustedSettings.ExportAnimations = false;
settings = adjustedSettings;
}
if (!recordBlendShapes)
settings.BlendShapeExportProperties = GLTFSettings.BlendShapeExportPropertyFlags.None;
var logHandler = new StringBuilderLogHandler();
var exporter = new GLTFSceneExporter(new Transform[] { root }, new ExportOptions(settings)
{
AfterSceneExport = PostExport,
logger = new Logger(logHandler),
});
exporter.SaveGLBToStream(stream, sceneName);
logHandler.LogAndClear();
}
private void PostExport(GLTFSceneExporter exporter, GLTFRoot gltfRoot)
{
// this would include animation from the original root
// exporter.ExportAnimationFromNode(ref root);
GLTFAnimation anim = new GLTFAnimation();
anim.Name = AnimationName;
CollectAndProcessAnimation(exporter, anim, true, out Bounds translationBounds);
if (anim.Channels.Count > 0 && anim.Samplers.Count > 0)
gltfRoot.Animations.Add(anim);
OnPostExport?.Invoke( new PostExportArgs(translationBounds, exporter, gltfRoot));
}
private static void SafeDestroy(Object obj)
{
if (Application.isEditor)
Object.DestroyImmediate(obj);
else
Object.Destroy(obj);
}
private static ProfilerMarker processAnimationMarker = new ProfilerMarker("Process Animation");
private static ProfilerMarker simplifyKeyframesMarker = new ProfilerMarker("Simplify Keyframes");
private static ProfilerMarker convertValuesMarker = new ProfilerMarker("Convert Values to Arrays");
private void CollectAndProcessAnimation(GLTFSceneExporter gltfSceneExporter, GLTFAnimation anim, bool calculateTranslationBounds, out Bounds translationBounds)
{
var gotFirstValue = false;
translationBounds = new Bounds();
foreach (var kvp in data)
{
processAnimationMarker.Begin();
foreach (var tr in kvp.Value.tracks)
{
if (tr.times.Length == 0) continue;
var postAnimation = new PostAnimationData(tr, tr.times, tr.values);
OnBeforeAddAnimationData?.Invoke(postAnimation);
if (calculateTranslationBounds && tr.propertyName == "translation")
{
for (var i = 0; i < postAnimation.Values.Length; i++)
{
var vec = (Vector3) postAnimation.Values[i];
if (!gotFirstValue)
{
translationBounds = new Bounds(vec, Vector3.zero);
gotFirstValue = true;
}
else
{
translationBounds.Encapsulate(vec);
}
}
}
gltfSceneExporter.RemoveUnneededKeyframes(ref postAnimation.Times, ref postAnimation.Values);
gltfSceneExporter.AddAnimationData(tr.animatedObject, tr.propertyName, anim, postAnimation.Times, postAnimation.Values);
}
processAnimationMarker.End();
}
}
private class StringBuilderLogHandler : ILogHandler
{
private readonly StringBuilder sb = new StringBuilder();
private string LogTypeToLog(LogType logType)
{
#if UNITY_EDITOR
// create strings with <color> tags
switch (logType)
{
case LogType.Error:
return "<color=red>[" + logType + "]</color>";
case LogType.Assert:
return "<color=red>[" + logType + "]</color>";
case LogType.Warning:
return "<color=yellow>[" + logType + "]</color>";
case LogType.Log:
return "[" + logType + "]";
case LogType.Exception:
return "<color=red>[" + logType + "]</color>";
default:
return "[" + logType + "]";
}
#else
return "[" + logType + "]";
#endif
}
public void LogFormat(LogType logType, Object context, string format, params object[] args) => sb.AppendLine($"{LogTypeToLog(logType)} {string.Format(format, args)} [Context: {context}]");
public void LogException(Exception exception, Object context) => sb.AppendLine($"{LogTypeToLog(LogType.Exception)} {exception} [Context: {context}]");
public void LogAndClear()
{
if(sb.Length > 0)
{
var str = sb.ToString();
#if UNITY_2019_1_OR_NEWER
var logType = LogType.Log;
#if UNITY_EDITOR
if (str.IndexOf("[Error]", StringComparison.Ordinal) > -1 ||
str.IndexOf("[Exception]", StringComparison.Ordinal) > -1 ||
str.IndexOf("[Assert]", StringComparison.Ordinal) > -1)
logType = LogType.Error;
else if (str.IndexOf("[Warning]", StringComparison.Ordinal) > -1)
logType = LogType.Warning;
#endif
Debug.LogFormat(logType, LogOption.NoStacktrace, null, "Export Messages:" + "\n{0}", sb.ToString());
#else
Debug.Log(string.Format("Export Messages:" + "\n{0}", str));
#endif
}
sb.Clear();
}
}
}
}