/
ColladaUtil.java
1666 lines (1386 loc) · 70.3 KB
/
ColladaUtil.java
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020-2024 The Defold Foundation
// Copyright 2014-2020 King
// Copyright 2009-2014 Ragnar Svensson, Christian Murray
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
package com.dynamo.bob.pipeline;
import java.io.File;
import java.io.FileInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.Map.Entry;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ArrayUtils;
import javax.vecmath.Matrix4d;
import javax.vecmath.Matrix4f;
import javax.vecmath.Point3f;
import javax.vecmath.Quat4d;
import javax.vecmath.Tuple3d;
import javax.vecmath.Tuple4d;
import javax.vecmath.Vector3d;
import javax.vecmath.Vector3f;
import javax.vecmath.Vector4d;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
// Sources:
// https://github.com/spidasoftware/jagatoo/blob/master/src/main/java/org/jagatoo/loaders/models/collada
import org.jagatoo.loaders.models.collada.stax.XMLAnimation;
import org.jagatoo.loaders.models.collada.stax.XMLAnimationClip;
import org.jagatoo.loaders.models.collada.stax.XMLAsset;
import org.jagatoo.loaders.models.collada.stax.XMLCOLLADA;
import org.jagatoo.loaders.models.collada.stax.XMLController;
import org.jagatoo.loaders.models.collada.stax.XMLGeometry;
import org.jagatoo.loaders.models.collada.stax.XMLInput;
import org.jagatoo.loaders.models.collada.stax.XMLInstanceGeometry;
import org.jagatoo.loaders.models.collada.stax.XMLLibraryAnimationClips;
import org.jagatoo.loaders.models.collada.stax.XMLLibraryAnimations;
import org.jagatoo.loaders.models.collada.stax.XMLLibraryControllers;
import org.jagatoo.loaders.models.collada.stax.XMLMesh;
import org.jagatoo.loaders.models.collada.stax.XMLSampler;
import org.jagatoo.loaders.models.collada.stax.XMLNode;
import org.jagatoo.loaders.models.collada.stax.XMLSkin;
import org.jagatoo.loaders.models.collada.stax.XMLSource;
import org.jagatoo.loaders.models.collada.stax.XMLVisualScene;
import org.jagatoo.loaders.models.collada.stax.XMLAsset.UpAxis;
import org.jagatoo.loaders.models.collada.stax.XMLVisualSceneExtra;
import org.jagatoo.loaders.models.collada.datastructs.animation.Bone;
import com.dynamo.bob.logging.Logger;
import com.dynamo.bob.util.MathUtil;
import com.dynamo.bob.util.MurmurHash;
import com.dynamo.bob.util.RigUtil;
import com.dynamo.bob.util.RigUtil.AnimationKey;
import com.dynamo.bob.util.RigUtil.Weight;
import com.dynamo.bob.util.TimeProfiler;
import com.dynamo.proto.DdfMath.Transform;
import com.dynamo.rig.proto.Rig;
import com.dynamo.rig.proto.Rig.AnimationInstanceDesc;
import com.dynamo.rig.proto.Rig.AnimationSetDesc;
import com.google.protobuf.TextFormat;
public class ColladaUtil {
static int BONE_NO_PARENT = 0xffffffff;
private static Logger logger = Logger.getLogger(ColladaUtil.class.getName());
static private class AssetSpace
{
public Matrix4d rotation;
public double unit;
AssetSpace() {
rotation = new Matrix4d();
rotation.setIdentity();
unit = 1.0;
}
}
public static AssetSpace getAssetSpace(XMLAsset asset)
{
AssetSpace assetSpace = new AssetSpace();
if (asset != null) {
if (asset.unit != null) {
assetSpace.unit = asset.unit.meter;
}
UpAxis upAxis = asset.upAxis != null ? asset.upAxis : UpAxis.Y_UP;
if (upAxis.equals(UpAxis.Z_UP)) {
assetSpace.rotation.setRow(0, new double[] {1.0, 0.0, 0.0, 0.0});
assetSpace.rotation.setRow(1, new double[] {0.0, 0.0, 1.0, 0.0});
assetSpace.rotation.setRow(2, new double[] {0.0, -1.0, 0.0, 0.0});
} else if (upAxis.equals(UpAxis.X_UP)) {
assetSpace.rotation.setRow(0, new double[] {0.0, -1.0, 0.0, 0.0});
assetSpace.rotation.setRow(1, new double[] {1.0, 0.0, 0.0, 0.0});
assetSpace.rotation.setRow(2, new double[] {0.0, 0.0, 1.0, 0.0});
} else {
assetSpace.rotation.setRow(0, new double[] {1.0, 0.0, 0.0, 0.0});
assetSpace.rotation.setRow(1, new double[] {0.0, 1.0, 0.0, 0.0});
assetSpace.rotation.setRow(2, new double[] {0.0, 0.0, 1.0, 0.0});
}
}
return assetSpace;
}
// private static void printVector3d(Vector3d v) {
// System.err.printf(" %f, %f, %f\n", v.getX(), v.getY(), v.getZ());
// }
private static void printVector4d(Vector4d v) {
System.err.printf(" %f, %f, %f, %f\n", v.getX(), v.getY(), v.getZ(), v.getW());
}
// private static void printQuat4d(Quat4d v) {
// System.err.printf(" %f, %f, %f, %f\n", v.getX(), v.getY(), v.getZ(), v.getW());
// }
private static void printMatrix4d(Matrix4d mat) {
Vector4d v = new Vector4d();
mat.getColumn(0, v); printVector4d(v);
mat.getColumn(1, v); printVector4d(v);
mat.getColumn(2, v); printVector4d(v);
mat.getColumn(3, v); printVector4d(v);
}
private static XMLInput findInput(List<XMLInput> inputs, String semantic, boolean required)
throws LoaderException {
for (XMLInput i : inputs) {
if (i.semantic.equals(semantic))
return i;
}
if (required)
throw new LoaderException(String.format("Input '%s' not found", semantic));
return null;
}
private static HashMap<String, XMLSource> getSourcesMap(List<XMLSource> sources) {
HashMap<String, XMLSource> sourcesMap;
sourcesMap = new HashMap<String, XMLSource>();
for (int i = 0; i < sources.size(); i++) {
XMLSource source = sources.get(i);
sourcesMap.put(source.id, source);
}
return sourcesMap;
}
public static XMLCOLLADA loadDAE(InputStream is) throws IOException, XMLStreamException, LoaderException {
XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty("javax.xml.stream.isCoalescing", true);
XMLStreamReader stream_reader = factory.createXMLStreamReader(is);
XMLCOLLADA collada = new XMLCOLLADA();
collada.parse(stream_reader);
return collada;
}
public static boolean load(InputStream is, Rig.MeshSet.Builder meshSetBuilder, Rig.AnimationSet.Builder animationSetBuilder, Rig.Skeleton.Builder skeletonBuilder) throws IOException, XMLStreamException, LoaderException {
XMLCOLLADA collada = loadDAE(is);
loadMesh(collada, meshSetBuilder, true, false);
loadSkeleton(collada, skeletonBuilder, new ArrayList<String>());
loadAnimations(collada, animationSetBuilder, "", new ArrayList<String>());
return true;
}
private static HashMap<String, XMLSource> getSamplersLUT(XMLAnimation animation) {
XMLSampler sampler = animation.samplers.get(0);
HashMap<String, XMLSource> samplersLUT = new HashMap<String, XMLSource>();
for (int i = 0; i < sampler.inputs.size(); i++) {
XMLInput input = sampler.inputs.get(i);
// Find source for sampler
XMLSource source = null;
for (int j = 0; j < animation.sources.size(); j++) {
if (animation.sources.get(j).id.equals(input.source)) {
source = animation.sources.get(j);
break;
}
}
samplersLUT.put(input.semantic, source);
}
return samplersLUT;
}
private static AnimationKey createKey(float t, boolean stepped, int componentSize) {
AnimationKey key = new AnimationKey();
key.t = t;
key.stepped = stepped;
key.value = new float[componentSize];
return key;
}
private static void toFloats(Tuple3d v, float[] f) {
f[0] = (float)v.getX();
f[1] = (float)v.getY();
f[2] = (float)v.getZ();
}
private static void toFloats(Tuple4d v, float[] f) {
f[0] = (float)v.getX();
f[1] = (float)v.getY();
f[2] = (float)v.getZ();
f[3] = (float)v.getW();
}
private static void ExtractMatrixKeys(Bone bone, Matrix4d localToParent, AssetSpace assetSpace, XMLAnimation animation, RigUtil.AnimationTrack posTrack, RigUtil.AnimationTrack rotTrack, RigUtil.AnimationTrack scaleTrack) {
Vector4d lastR = new Vector4d(0.0, 0.0, 0.0, 0.0);
int keyCount = animation.getInput().length;
float[] time = animation.getInput();
float[] values = animation.getOutput();
for (int key = 0; key < keyCount; ++key) {
int index = key * 16;
Matrix4d m = new Matrix4d(new Matrix4f(ArrayUtils.subarray(values, index, index + 16)));
if (assetSpace != null) {
m.m03 *= assetSpace.unit;
m.m13 *= assetSpace.unit;
m.m23 *= assetSpace.unit;
m.mul(assetSpace.rotation, m);
}
Vector3d p = new Vector3d();
Quat4d r = new Quat4d();
Vector3d s = new Vector3d();
MathUtil.decompose(m, p, r, s);
// Check if dot product of decomposed rotation and previous frame is < 0,
// if that is the case; flip rotation.
// This is to avoid a problem that can occur when we decompose the matrix and
// we get a quaternion representing the same rotation but in the opposite direction.
// See this answer on SO: http://stackoverflow.com/a/2887128
Vector4d rv = new Vector4d(r.x, r.y, r.z, r.w);
if (lastR.dot(rv) < 0.0) {
r.scale(-1.0);
rv.scale(-1.0);
}
lastR = rv;
float t = time[key];
AnimationKey posKey = createKey(t, false, 3);
toFloats(p, posKey.value);
posTrack.keys.add(posKey);
AnimationKey rotKey = createKey(t, false, 4);
toFloats(r, rotKey.value);
rotTrack.keys.add(rotKey);
AnimationKey scaleKey = createKey(t, false, 3);
toFloats(s, scaleKey.value);
scaleTrack.keys.add(scaleKey);
}
}
private static void ExtractKeys(Bone bone, Matrix4d localToParent, AssetSpace assetSpace, XMLAnimation animation, RigUtil.AnimationTrack posTrack, RigUtil.AnimationTrack rotTrack, RigUtil.AnimationTrack scaleTrack) throws LoaderException {
switch (animation.getType()) {
case TRANSLATE:
case SCALE:
case ROTATE:
throw new LoaderException("Currently only collada files with matrix animations are supported.");
case TRANSFORM:
case MATRIX:
ExtractMatrixKeys(bone, localToParent, assetSpace, animation, posTrack, rotTrack, scaleTrack);
break;
default:
throw new LoaderException(String.format("Animations of type %s are not supported.", animation.getType().name()));
}
}
private static Matrix4d getBoneLocalToParent(Bone bone) {
return new Matrix4d(MathUtil.vecmath2ToVecmath1(bone.bindMatrix));
}
private static void samplePosTrack(Rig.RigAnimation.Builder animBuilder, Rig.AnimationTrack.Builder animTrackBuilder, RigUtil.AnimationTrack track, double duration, double startTime, double sampleRate, double spf, boolean interpolate) {
if (track.keys.isEmpty())
return;
RigUtil.PositionBuilder positionBuilder = new RigUtil.PositionBuilder(animTrackBuilder);
RigUtil.sampleTrack(track, positionBuilder, startTime, duration, sampleRate, spf, true);
}
private static void sampleRotTrack(Rig.RigAnimation.Builder animBuilder, Rig.AnimationTrack.Builder animTrackBuilder, RigUtil.AnimationTrack track, double duration, double startTime, double sampleRate, double spf, boolean interpolate) {
if (track.keys.isEmpty())
return;
RigUtil.QuatRotationBuilder rotationBuilder = new RigUtil.QuatRotationBuilder(animTrackBuilder);
RigUtil.sampleTrack(track, rotationBuilder, startTime, duration, sampleRate, spf, true);
}
private static void sampleScaleTrack(Rig.RigAnimation.Builder animBuilder, Rig.AnimationTrack.Builder animTrackBuilder, RigUtil.AnimationTrack track, double duration, double startTime, double sampleRate, double spf, boolean interpolate) {
if (track.keys.isEmpty())
return;
RigUtil.ScaleBuilder scaleBuilder = new RigUtil.ScaleBuilder(animTrackBuilder);
RigUtil.sampleTrack(track, scaleBuilder, startTime, duration, sampleRate, spf, true);
}
public static void createAnimationTracks(Rig.RigAnimation.Builder animBuilder,
String boneName,
Bone bone,
RigUtil.AnimationTrack posTrack,
RigUtil.AnimationTrack rotTrack,
RigUtil.AnimationTrack sclTrack,
int boneIndex, double duration, double startTime, double sampleRate) {
double spf = 1.0 / sampleRate;
Rig.AnimationTrack.Builder animTrackBuilder = Rig.AnimationTrack.newBuilder();
animTrackBuilder.setBoneId(MurmurHash.hash64(boneName));
samplePosTrack(animBuilder, animTrackBuilder, posTrack, duration, startTime, sampleRate, spf, true);
sampleRotTrack(animBuilder, animTrackBuilder, rotTrack, duration, startTime, sampleRate, spf, true);
sampleScaleTrack(animBuilder, animTrackBuilder, sclTrack, duration, startTime, sampleRate, spf, true);
animBuilder.addTracks(animTrackBuilder.build());
}
private static class SortOnBoneIndex implements Comparator<Bone> {
public SortOnBoneIndex(HashMap<Long, Integer> boneRefMap) {
this.boneRefMap = boneRefMap;
}
public int compare(Bone a, Bone b) {
Long boneHashA = MurmurHash.hash64(a.getSourceId());
Long boneHashB = MurmurHash.hash64(b.getSourceId());
Integer refIndexA = this.boneRefMap.getOrDefault(boneHashA, 100000);
Integer refIndexB = this.boneRefMap.getOrDefault(boneHashB, 100000);
return refIndexA - refIndexB;
}
private HashMap<Long, Integer> boneRefMap;
}
private static void boneAnimToDDF(XMLCOLLADA collada, Rig.RigAnimation.Builder animBuilder, ArrayList<Bone> boneList, HashMap<Long, Integer> boneRefMap, HashMap<String, ArrayList<XMLAnimation>> boneToAnimations, double duration) throws LoaderException {
// Get scene framerate, start and end times if available
double sceneStartTime = 0.0;
double sceneEndTime = duration;
double sceneFrameRate = 30.0f;
if (collada.libraryVisualScenes.size() == 1) {
Collection<XMLVisualScene> scenes = collada.libraryVisualScenes.get(0).scenes.values();
XMLVisualScene scene = scenes.toArray(new XMLVisualScene[0])[0];
if (scene != null) {
XMLVisualSceneExtra sceneExtras = scene.extra;
if (sceneExtras != null) {
if (sceneExtras.startTime != null) {
sceneStartTime = sceneExtras.startTime;
}
if (sceneExtras.endTime != null) {
sceneEndTime = sceneExtras.endTime;
}
if (sceneExtras.framerate != null) {
sceneFrameRate = sceneExtras.framerate;
}
}
}
}
if (sceneStartTime > sceneEndTime) {
sceneEndTime = sceneStartTime;
}
duration = sceneEndTime - sceneStartTime;
animBuilder.setDuration((float)duration);
// We use the supplied framerate (if available) as samplerate to get correct timings when
// sampling the animation data. We used to have a static sample rate of 30, which would mean
// if the scene was saved with a different framerate the animation would either be too fast or too slow.
animBuilder.setSampleRate((float)sceneFrameRate);
if (boneList == null) {
return;
}
boneList.sort(new SortOnBoneIndex(boneRefMap));
// loop through each bone
double spf = 1.0 / sceneFrameRate;
for (int bi = 0; bi < boneList.size(); ++bi)
{
Bone bone = boneList.get(bi);
String boneId = bone.node.id;
// Lookup the index for the bone in the reference map.
// This is the bone index to use since we can't guarantee that that
// the bone hierarchy is stored as depth first, we need to depend on the
// supplied "JOINT" reference list from the skin entry.
Long boneHash = MurmurHash.hash64(bone.getSourceId());
Integer refIndex = boneRefMap.get(boneHash);
if (refIndex == null)
continue;
String boneName = bone.getSourceId();
if (bi == 0 || refIndex == 0)
{
boneName = "root";
}
Matrix4d localToParent = getBoneLocalToParent(bone);
AssetSpace assetSpace = getAssetSpace(collada.asset);
if (bi != 0) {
// Only apply up axis rotation for first bone.
assetSpace.rotation.setIdentity();
}
if (boneToAnimations.containsKey(boneId))
{
// search the animations for each bone
ArrayList<XMLAnimation> anims = boneToAnimations.get(boneId);
boolean anim_found = false;
for (XMLAnimation animation : anims) {
if (animation.getType() == null) {
continue;
}
RigUtil.AnimationTrack posTrack = new RigUtil.AnimationTrack();
posTrack.property = RigUtil.AnimationTrack.Property.POSITION;
RigUtil.AnimationTrack rotTrack = new RigUtil.AnimationTrack();
rotTrack.property = RigUtil.AnimationTrack.Property.ROTATION;
RigUtil.AnimationTrack sclTrack = new RigUtil.AnimationTrack();
sclTrack.property = RigUtil.AnimationTrack.Property.SCALE;
ExtractKeys(bone, localToParent, assetSpace, animation, posTrack, rotTrack, sclTrack);
createAnimationTracks(animBuilder, boneName, bone, posTrack, rotTrack, sclTrack, refIndex, (float)duration, sceneStartTime, sceneFrameRate);
break; // we only support one animation per file/bone
}
}
}
}
public interface ColladaResourceResolver {
public InputStream getResource(String resourceName) throws FileNotFoundException;
}
private static void loadAnimationClipIds(InputStream is, String parentId, ArrayList<String> animationIds) throws IOException, XMLStreamException, LoaderException {
XMLCOLLADA collada = loadDAE(is);
ArrayList<XMLLibraryAnimationClips> animClips = collada.libraryAnimationClips;
if(animClips.isEmpty()) {
if(!collada.libraryAnimations.isEmpty()) {
animationIds.add(parentId);
}
return;
}
for (XMLAnimationClip clip : animClips.get(0).animationClips.values()) {
if (clip.name != null) {
animationIds.add(parentId + "/" + clip.name);
} else if (clip.id != null) {
animationIds.add(parentId + "/" + clip.id);
} else {
throw new LoaderException("Animation clip must contain name or id.");
}
}
}
public static void loadAnimationIds(String resourceName, String parentId, ArrayList<String> animationIds, final ColladaResourceResolver resourceResolver) throws IOException, XMLStreamException, LoaderException {
InputStream is;
try {
is = resourceResolver.getResource(resourceName);
} catch (FileNotFoundException e) {
throw new IOException("Could not extract animation id from resource: " + resourceName);
}
String animId = FilenameUtils.getBaseName(resourceName);
if(resourceName.toLowerCase().endsWith(".dae")) {
loadAnimationClipIds(is, animId, animationIds);
return;
}
animId = (parentId.isEmpty() ? "" : parentId + "/") + animId;
InputStreamReader animset_isr = new InputStreamReader(is);
AnimationSetDesc.Builder animationDescBuilder = AnimationSetDesc.newBuilder();
TextFormat.merge(animset_isr, animationDescBuilder);
for(AnimationInstanceDesc animationSet : animationDescBuilder.getAnimationsList()) {
loadAnimationIds(animationSet.getAnimation(), animId, animationIds, resourceResolver);
}
}
public static void loadAnimations(InputStream is, Rig.AnimationSet.Builder animationSetBuilder, String parentAnimationId, ArrayList<String> animationIds) throws IOException, XMLStreamException, LoaderException {
XMLCOLLADA collada = loadDAE(is);
loadAnimations(collada, animationSetBuilder, parentAnimationId, animationIds);
}
public static void loadAnimations(XMLCOLLADA collada, Rig.AnimationSet.Builder animationSetBuilder, String animationId, ArrayList<String> animationIds) throws IOException, XMLStreamException, LoaderException {
if (collada.libraryAnimations.size() != 1) {
return;
}
List<String> boneRefArray = createBoneReferenceList(collada);
if (boneRefArray == null || boneRefArray.isEmpty()) {
return;
}
// Load skeleton to get bone bind poses
ArrayList<String> boneIds = new ArrayList<String>();
ArrayList<Bone> boneList = loadSkeleton(collada, boneIds);
HashMap<Long, Integer> boneRefMap = new HashMap<Long, Integer>();
int boneIndex = 0;
for (String boneId : boneIds) {
Long boneRef = MurmurHash.hash64(boneId);
boneRefMap.put(boneRef, boneIndex);
++boneIndex;
}
// Animation clips
ArrayList<XMLLibraryAnimationClips> animClips = collada.libraryAnimationClips;
XMLLibraryAnimations libraryAnimation = collada.libraryAnimations.get(0);
if(!animClips.isEmpty()) {
throw new LoaderException("Anmation clips are currently not supported.");
} else {
float totalAnimationLength = 0.0f;
HashMap<String, ArrayList<XMLAnimation>> boneToAnimations = new HashMap<String, ArrayList<XMLAnimation>>();
// Loop through all animations and build a bone-to-animations LUT
Iterator<Entry<String, XMLAnimation>> it = libraryAnimation.animations.entrySet().iterator();
while (it.hasNext()) {
XMLAnimation animation = (XMLAnimation)it.next().getValue();
if (animation.channels.size() == 0) {
continue;
}
String boneTarget = animation.getTargetBone();
if (!boneToAnimations.containsKey(boneTarget)) {
boneToAnimations.put(boneTarget, new ArrayList<XMLAnimation>());
}
boneToAnimations.get(boneTarget).add(animation);
// Figure out the total duration of the animation.
HashMap<String, XMLSource> samplersLUT = getSamplersLUT(animation);
XMLSource inputSampler = samplersLUT.get("INPUT");
float animLength = inputSampler.floatArray.floats[inputSampler.floatArray.count-1];
totalAnimationLength = Math.max(totalAnimationLength, animLength);
}
// If no clips are provided, add a "Default" clip that is the whole animation as one clip
Rig.RigAnimation.Builder animBuilder = Rig.RigAnimation.newBuilder();
boneAnimToDDF(collada, animBuilder, boneList, boneRefMap, boneToAnimations, totalAnimationLength);
animBuilder.setId(MurmurHash.hash64(animationId));
animationIds.add(animationId);
animationSetBuilder.addAnimations(animBuilder.build());
}
}
public static void loadMesh(InputStream is, Rig.MeshSet.Builder meshSetBuilder) throws IOException, XMLStreamException, LoaderException {
loadMesh(is, meshSetBuilder, false, false);
}
public static void loadMesh(InputStream is, Rig.MeshSet.Builder meshSetBuilder, boolean optimize, boolean splitMeshes) throws IOException, XMLStreamException, LoaderException {
XMLCOLLADA collada = loadDAE(is);
loadMesh(collada, meshSetBuilder, optimize, splitMeshes);
}
private static XMLNode getFirstNodeWithGeometry(Collection<XMLVisualScene> scenes) {
for (XMLVisualScene scene : scenes) {
for (XMLNode node : scene.nodes.values()) {
if (node.instanceGeometries.size() > 0) {
return node;
}
}
}
return null;
}
private static float[] toFloatArray(List<Float> a) {
float[] floatArray = new float[a.size()];
for (int i = 0 ; i < a.size(); i++) {
floatArray[i] = (float) a.get(i);
}
return floatArray;
}
private static int[] toIntArray(List<Integer> a) {
return a.stream().mapToInt(x -> x).toArray();
}
private static ModelImporter.Aabb calcAabb(float[] positions) {
ModelImporter.Aabb aabb = new ModelImporter.Aabb();
for (int i = 0; i < positions.length; i += 3) {
aabb.expand(positions[i+0], positions[i+1], positions[i+2]);
}
return aabb;
}
private static ModelImporter.Mesh createModelImporterMesh(List<Float> position_list,
List<Float> normal_list,
List<Float> texcoord_list,
List<Float> bone_weights_list,
List<Integer> bone_indices_list,
List<Integer> mesh_index_list,
ModelImporter.Material material) {
ModelImporter.Mesh mesh = new ModelImporter.Mesh();
mesh.name = "";
mesh.material = material;
mesh.positions = toFloatArray(position_list);
if (normal_list.size() > 0)
mesh.normals = toFloatArray(normal_list);
mesh.aabb = calcAabb(mesh.positions);
mesh.tangents = null;
mesh.colors = null;
if (bone_weights_list.size() > 0)
mesh.weights = toFloatArray(bone_weights_list);
if (bone_indices_list.size() > 0)
mesh.bones = toIntArray(bone_indices_list);
mesh.texCoords0NumComponents = 2;
if (texcoord_list.size() > 0)
mesh.texCoords0 = toFloatArray(texcoord_list);
mesh.texCoords1NumComponents = 0; // 2 or 3
mesh.texCoords1 = null;
if (mesh_index_list.size() > 0)
mesh.indices = toIntArray(mesh_index_list);
mesh.vertexCount = position_list.size() / 3;
mesh.indexCount = mesh_index_list.size();
return mesh;
}
public static void loadMesh(XMLCOLLADA collada, Rig.MeshSet.Builder meshSetBuilder, boolean optimize, boolean splitMeshes) throws IOException, XMLStreamException, LoaderException {
if (collada.libraryGeometries.size() != 1) {
if (collada.libraryGeometries.isEmpty()) {
return;
}
throw new LoaderException("Only a single geometry is supported");
}
// Use first geometry entry as default
XMLGeometry geom = collada.libraryGeometries.get(0).geometries.values().iterator().next();
// Find first node in visual scene tree that has a instance geometry
XMLNode sceneNode = null;
Matrix4d sceneNodeMatrix = null;
if (collada.libraryVisualScenes.size() > 0) {
sceneNode = getFirstNodeWithGeometry(collada.libraryVisualScenes.get(0).scenes.values());
if (sceneNode != null) {
XMLInstanceGeometry instanceGeo = sceneNode.instanceGeometries.get(0);
String geometryId = instanceGeo.url;
// Get node transform if available
sceneNodeMatrix = new Matrix4d(MathUtil.vecmath2ToVecmath1(sceneNode.matrix.matrix4f));
// Find geometry entry
for (XMLGeometry geomEntry : collada.libraryGeometries.get(0).geometries.values())
{
if (geomEntry.equals(geometryId)) {
geom = geomEntry;
break;
}
}
}
}
if (sceneNodeMatrix == null) {
sceneNodeMatrix = new Matrix4d();
sceneNodeMatrix.setIdentity();
}
XMLMesh mesh = geom.mesh;
if(mesh == null || mesh.triangles == null) {
return;
}
List<XMLSource> sources = mesh.sources;
HashMap<String, XMLSource> sourcesMap = getSourcesMap(sources);
XMLInput vpos_input = findInput(mesh.vertices.inputs, "POSITION", true);
XMLInput vertex_input = findInput(mesh.triangles.inputs, "VERTEX", true);
XMLInput normal_input = findInput(mesh.triangles.inputs, "NORMAL", false);
XMLInput texcoord_input = findInput(mesh.triangles.inputs, "TEXCOORD", false);
// Get bind shape from skin, if it exist
Matrix4d bindShapeMatrix = null;
XMLSkin skin = null;
if (!collada.libraryControllers.isEmpty()) {
skin = findFirstSkin(collada.libraryControllers.get(0));
if (skin != null && skin.bindShapeMatrix != null) {
bindShapeMatrix = new Matrix4d(MathUtil.vecmath2ToVecmath1(skin.bindShapeMatrix.matrix4f));
}
}
if (bindShapeMatrix == null) {
bindShapeMatrix = new Matrix4d();
bindShapeMatrix.setIdentity();
}
// Apply any matrix found for scene node
bindShapeMatrix.mul(sceneNodeMatrix);
// NOTE: Normals could be part of the vertex of specified directly in triangles...
int normalOffset;
if (normal_input != null) {
normalOffset = normal_input.offset;
} else {
normalOffset = 0;
normal_input = findInput(mesh.vertices.inputs, "NORMAL", false);
}
if (mesh.triangles.inputs.size() == 0)
throw new LoaderException("No inputs in triangles");
int stride = 0;
for (XMLInput i : mesh.triangles.inputs) {
stride = Math.max(stride, i.offset);
}
stride += 1;
XMLSource positions = sourcesMap.get(vpos_input.source);
XMLSource normals = null;
if (normal_input != null) {
normals = sourcesMap.get(normal_input.source);
}
XMLSource texcoords = null;
if (texcoord_input != null) {
texcoords = sourcesMap.get(texcoord_input.source);
}
// Apply the up-axis matrix on the bind shape matrix.
AssetSpace assetSpace = getAssetSpace(collada.asset);
Matrix4d assetSpaceMtx = new Matrix4d();
Matrix4d assetScaleMtx = new Matrix4d();
assetScaleMtx.setIdentity();
assetScaleMtx.setScale(assetSpace.unit);
assetSpaceMtx.mul(assetSpace.rotation, assetScaleMtx);
bindShapeMatrix.mul(assetSpaceMtx, bindShapeMatrix);
List<Float> position_list = new ArrayList<Float>(positions.floatArray.count);
for (int i = 0; i < positions.floatArray.count / 3; ++i) {
Point3f p = new Point3f(positions.floatArray.floats[i*3], positions.floatArray.floats[i*3+1], positions.floatArray.floats[i*3+2]);
bindShapeMatrix.transform(p);
position_list.add(p.getX());
position_list.add(p.getY());
position_list.add(p.getZ());
}
// Create a normal matrix which is the transposed inverse of
// the bind shape matrix (which already include the up axis matrix).
Matrix4f normalMatrix = new Matrix4f(bindShapeMatrix);
normalMatrix.invert();
normalMatrix.transpose();
List<Float> normal_list = new ArrayList<Float>();
if(normals != null) {
normal_list = new ArrayList<Float>(normals.floatArray.count);
for (int i = 0; i < normals.floatArray.count / 3; ++i) {
Vector3f n = new Vector3f(normals.floatArray.floats[i*3], normals.floatArray.floats[i*3+1], normals.floatArray.floats[i*3+2]);
normalMatrix.transform(n);
if (n.lengthSquared() > 0.0) {
n.normalize();
}
normal_list.add(n.getX());
normal_list.add(n.getY());
normal_list.add(n.getZ());
}
}
List<Float> texcoord_list;
if(texcoords == null) {
texcoord_list = new ArrayList<Float>(Arrays.asList(0f, 0f));
} else {
texcoord_list = new ArrayList<Float>(texcoords.floatArray.count);
for (int i = 0; i < texcoords.floatArray.count; i += 2 ) {
texcoord_list.add(texcoords.floatArray.floats[i]);
texcoord_list.add(texcoords.floatArray.floats[i+1]);
}
}
List<Integer> position_indices_list = new ArrayList<Integer>(mesh.triangles.count*3);
List<Integer> normal_indices_list = new ArrayList<Integer>(mesh.triangles.count*3);
List<Integer> texcoord_indices_list = new ArrayList<Integer>(mesh.triangles.count*3);
// Sometimes the <p> values can be -1 from Maya exports, we clamp it below to 0 instead.
// Similar solution as AssImp; https://github.com/assimp/assimp/blob/master/code/ColladaParser.cpp#L2336
for (int i = 0; i < mesh.triangles.count; ++i) {
for (int j = 0; j < 3; ++j) {
int idx = i * stride * 3 + vertex_input.offset;
int vert_idx = Math.max(0, mesh.triangles.p[idx + stride * j]);
position_indices_list.add(vert_idx);
if (normals != null) {
idx = i * stride * 3 + normalOffset;
vert_idx = Math.max(0, mesh.triangles.p[idx + stride * j]);
normal_indices_list.add(vert_idx);
}
if (texcoords == null) {
texcoord_indices_list.add(0);
} else {
idx = i * stride * 3 + texcoord_input.offset;
vert_idx = Math.max(0, mesh.triangles.p[idx + stride * j]);
texcoord_indices_list.add(vert_idx);
}
}
}
class MeshVertexIndex {
public int position, texcoord0, normal;
@Override
public final int hashCode() { // fnv 32 bit hash
int result = 0x811c9dc5;
result ^= position;
result *= 0x01000193;
result ^= texcoord0;
result *= 0x01000193;
result ^= normal;
result *= 0x01000193;
return result;
}
}
long tstart = System.currentTimeMillis();
TimeProfiler.start();
TimeProfiler.addData("optimizeVertices", "Colladautil");
// Build an optimized list of triangles from indices and instance (make unique) any vertices common attributes (position, normal etc.).
// We can then use this to quickly build am optimized indexed vertex buffer of any selected vertex elements in run-time without any sorting.
boolean mesh_has_normals = normal_indices_list.size() > 0;
List<MeshVertexIndex> shared_vertex_indices = new ArrayList<MeshVertexIndex>(mesh.triangles.count*3);
Map<Integer, Integer> shared_vertex_index_map = new HashMap<>();
List<Integer> mesh_index_list = new ArrayList<Integer>(mesh.triangles.count*3);
for (int i = 0; i < mesh.triangles.count*3; ++i) {
MeshVertexIndex ci = new MeshVertexIndex();
ci.position = position_indices_list.get(i);
ci.texcoord0 = texcoord_indices_list.get(i);
ci.normal = mesh_has_normals ? normal_indices_list.get(i) : 0;
int index = optimize ? (int)shared_vertex_index_map.getOrDefault(ci.hashCode(), -1) : -1;
if(index == -1) {
// create new vertex as this is not equal to any existing in generated list
index = shared_vertex_indices.size();
mesh_index_list.add(index);
shared_vertex_indices.add(ci);
shared_vertex_index_map.put(ci.hashCode(), index);
} else {
// shared vertex, add index to existing vertex in generating list instead of adding new
mesh_index_list.add(index);
}
}
TimeProfiler.stop();
long tend = System.currentTimeMillis();
logger.fine("ColladaUtil: Creating %d vertices (optimize: %s) took %f s", shared_vertex_indices.size(), optimize?"on":"off", (tend-tstart)/1000.0);
int vertex_count = shared_vertex_indices.size();
ArrayList<Integer> bone_indices_list = new ArrayList<Integer>(vertex_count*4);
ArrayList<Float> bone_weights_list = new ArrayList<Float>(vertex_count*4);
int max_bone_count = loadVertexWeights(collada, bone_weights_list, bone_indices_list);
// Bake the values again into our format
Float baked_position_list[] = new Float[vertex_count*3];
Float baked_normal_list[] = new Float[0];
Float baked_texcoord_list[] = new Float[0];
Integer baked_bone_indices_list[] = new Integer[0];
Float baked_bone_weights_list[] = new Float[0];
if (normal_list.size() > 0) {
baked_normal_list = new Float[vertex_count*3];
}
if (texcoord_list.size() > 0) {
baked_texcoord_list = new Float[vertex_count*2];
}
if (bone_indices_list.size() > 0) {
baked_bone_indices_list = new Integer[vertex_count*4];
baked_bone_weights_list = new Float[vertex_count*4];
}
for (int index : mesh_index_list) {
MeshVertexIndex ci = shared_vertex_indices.get(index);
for (int c = 0; c < 3; ++c)
{
baked_position_list[index*3+c] = position_list.get(ci.position*3+c);
if (normal_list.size() > 0)
baked_normal_list[index*3+c] = normal_list.get(ci.normal*3+c);
}
if (texcoord_list.size() > 0)
{
for (int c = 0; c < 2; ++c)
{
baked_texcoord_list[index*2+c] = texcoord_list.get(ci.texcoord0*2+c);
}
}
if (bone_indices_list.size() > 0)
{
// For the bones we use the index of the position
for (int c = 0; c < 4; ++c)
{
baked_bone_indices_list[index*4+c] = bone_indices_list.get(ci.position*4+c);
baked_bone_weights_list[index*4+c] = bone_weights_list.get(ci.position*4+c);
}
}
}
Rig.Model.Builder modelBuilder = Rig.Model.newBuilder();
ModelImporter.Material material = new ModelImporter.Material();
List<ModelImporter.Mesh> allMeshes = new ArrayList<>();
ModelImporter.Mesh miMesh = createModelImporterMesh(new ArrayList<>(Arrays.asList(baked_position_list)),
new ArrayList<>(Arrays.asList(baked_normal_list)),
new ArrayList<>(Arrays.asList(baked_texcoord_list)),
new ArrayList<>(Arrays.asList(baked_bone_weights_list)),
new ArrayList<>(Arrays.asList(baked_bone_indices_list)),
mesh_index_list,
material);
if (splitMeshes && vertex_count >= 65536) {
ModelUtil.splitMesh(miMesh, allMeshes);
} else {
allMeshes.add(miMesh);
}
for (ModelImporter.Mesh newMesh : allMeshes) {
modelBuilder.addMeshes(ModelUtil.loadMesh(newMesh));
}
String name = sceneNode != null ? sceneNode.name : null;
if (name == null) {
name = geom.name;
}
if (name == null) {
name = "unnamed";
}
modelBuilder.setId(MurmurHash.hash64(name));
Matrix4d transformd = new Matrix4d();
transformd.setIdentity();
Vector3d tPos = new Vector3d();
Quat4d tRot = new Quat4d();
Vector3d tScale = new Vector3d();
MathUtil.decompose(transformd, tPos, tRot, tScale);
Transform transform = MathUtil.vecmathToDDF(tPos, tRot, tScale);
modelBuilder.setLocal(transform);
meshSetBuilder.addModels(modelBuilder);
meshSetBuilder.setMaxBoneCount(max_bone_count);
ArrayList<ModelImporter.Bone> bones = loadSkeleton(collada);
if (bones != null) {
for (ModelImporter.Bone bone : bones) {
meshSetBuilder.addBoneList(MurmurHash.hash64(bone.name));
}
}
}
public static void loadSkeleton(InputStream is, com.dynamo.rig.proto.Rig.Skeleton.Builder skeletonBuilder, ArrayList<String> boneIds) throws IOException, XMLStreamException, LoaderException {
loadSkeleton(loadDAE(is), skeletonBuilder, boneIds);
}
private static Bone loadBone(XMLNode node, ArrayList<Bone> boneList, ArrayList<String> boneIds, AssetSpace assetSpace, HashMap<String, Matrix4d> boneTransforms) {
// Get the bone transform for this bone from the transform lookup map.
Matrix4d boneBindMatrix = new Matrix4d();
if (boneTransforms.containsKey(node.id)) {
boneBindMatrix = new Matrix4d(boneTransforms.get(node.id));
}