-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathColladaLoader.cc
2866 lines (2512 loc) · 92.3 KB
/
ColladaLoader.cc
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 (C) 2016 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*
*/
#include <sstream>
#include <unordered_map>
#include <map>
#include <vector>
#include <set>
#include <gz/math/Helpers.hh>
#include <gz/math/Matrix4.hh>
#include <gz/math/Vector2.hh>
#include <gz/math/Vector3.hh>
#include "tinyxml2.h"
#include "gz/common/graphics/Types.hh"
#include "gz/common/Console.hh"
#include "gz/common/Material.hh"
#include "gz/common/SubMesh.hh"
#include "gz/common/Mesh.hh"
#include "gz/common/Skeleton.hh"
#include "gz/common/SkeletonAnimation.hh"
#include "gz/common/SystemPaths.hh"
#include "gz/common/Util.hh"
#include "gz/common/ColladaLoader.hh"
using namespace ignition;
using namespace common;
using RawNodeAnim = std::map<double, std::vector<NodeTransform> >;
using RawSkeletonAnim = std::map<std::string, RawNodeAnim>;
namespace ignition
{
namespace common
{
/// \brief Private data for the ColladaLoader class
class ColladaLoader::Implementation
{
/// \brief scaling factor
public: double meter;
/// \brief COLLADA file name
public: std::string filename;
/// \brief material dictionary indexed by name
public: std::map<std::string, std::string> materialMap;
/// \brief root xml element of COLLADA data
public: tinyxml2::XMLElement *colladaXml;
/// \brief directory of COLLADA file name
public: std::string path;
/// \brief Name of the current node.
public: std::string currentNodeName;
/// \brief Map of collada POSITION ids to list of vectors.
public: std::map<std::string,
std::vector<math::Vector3d> > positionIds;
/// \brief Map of collada NORMAL ids to list of normals.
public: std::map<std::string,
std::vector<math::Vector3d> > normalIds;
/// \brief Map of collada TEXCOORD ids to list of texture coordinates.
public: std::map<std::string,
std::vector<math::Vector2d> >texcoordIds;
/// \brief Map of collada Material ids to Gazebo materials.
public: std::map<std::string, MaterialPtr> materialIds;
/// \brief Map of collada POSITION ids to a map of
/// duplicate positions.
public: std::map<std::string, std::map<unsigned int, unsigned int> >
positionDuplicateMap;
/// \brief Map of collada NORMAL ids to a map of
/// duplicate normals.
public: std::map<std::string, std::map<unsigned int, unsigned int> >
normalDuplicateMap;
/// \brief Map of collada TEXCOORD ids to a map of
/// duplicate texture coordinates.
public: std::map<std::string, std::map<unsigned int, unsigned int> >
texcoordDuplicateMap;
/// \brief Current scene being parsed
public: tinyxml2::XMLElement *currentScene = nullptr;
/// \brief Load a controller instance
/// \param[in] _contrXml Pointer to the control XML instance
/// \param[in] _skelXml Pointer the skeleton xml instance
/// \param[in] _transform A tranform to apply
/// \param[in,out] _mesh The mesh being loaded
public: void LoadController(tinyxml2::XMLElement *_contrXml,
std::vector<tinyxml2::XMLElement*> _skelXmls,
const math::Matrix4d &_transform,
Mesh *_mesh);
/// \brief Load animations for a skeleton
/// \param[in] _xml Animation XML instance
/// \param[in,out] _skel Pointer to the skeleton
public: void LoadAnimations(tinyxml2::XMLElement *_xml,
SkeletonPtr _skel);
/// \brief Load a set of animations for a skeleton
/// \param[in] _xml Pointer to the animation set XML instance
/// \param[in,out] _skel Pointer to the skeleton
public: void LoadAnimationSet(tinyxml2::XMLElement *_xml,
SkeletonPtr _skel);
/// \brief Load a single skeleton node
/// \param[in] _xml Pointer to the XML instance
/// \param[in,out] _parent Pointer to the Skeleton node parent
public: SkeletonNode *LoadSingleSkeletonNode(tinyxml2::XMLElement *_xml,
SkeletonNode *_parent);
/// \brief Load skeleton nodes
/// \param[in] _xml Pointer to the XML instance
/// \param[in,out] _parent Pointer to the Skeleton node parent
public: SkeletonNode *LoadSkeletonNodes(tinyxml2::XMLElement *_xml,
SkeletonNode *_parent);
/// \brief Set the tranform for a skeleton node
/// \param[in] _elem Pointer to the XML instance
/// \param[in,out] _node The skeleton node
public: void SetSkeletonNodeTransform(tinyxml2::XMLElement *_elem,
SkeletonNode *_node);
/// \brief Load geometry elements
/// \param[in] _xml Pointer to the XML instance
/// \param[in] _tranform Transform to apply to the loaded geometry
/// \param[in,out] _mesh Pointer to the mesh currently being loaded
public: void LoadGeometry(tinyxml2::XMLElement *_xml,
const math::Matrix4d &_transform,
Mesh *_mesh);
/// \brief Get an XML element by ID
/// \param[in] _parent The parent element
/// \param[in] _name String name of the element
/// \param[in] _id String ID of the element
/// \return XML element with the specified ID
public: tinyxml2::XMLElement *ElementId(tinyxml2::XMLElement *_parent,
const std::string &_name,
const std::string &_id);
/// \brief Get an XML element by ID
/// \param[in] _name String name of the element
/// \param[in] _id String ID of the element
/// \return XML element with the specified ID
public: tinyxml2::XMLElement *ElementId(const std::string &_name,
const std::string &_id);
/// \brief Load a node
/// \param[in] _elem Pointer to the node XML instance
/// \param[in,out] _mesh Pointer to the current mesh
/// \param[in] _transform Transform to apply to the node
public: void LoadNode(tinyxml2::XMLElement *_elem,
Mesh *_mesh,
const math::Matrix4d &_transform);
/// \brief Load a transform
/// \param[in] _elem Pointer to the transform XML instance
/// \return A Matrix4 transform
public: math::Matrix4d LoadNodeTransform(
tinyxml2::XMLElement *_elem);
/// \brief Load vertices
/// \param[in] _id String id of the vertices XML node
/// \param[in] _transform Transform to apply to all vertices
/// \param[out] _verts Holds the resulting vertices
/// \param[out] _norms Holds the resulting normals
public: void LoadVertices(const std::string &_id,
const math::Matrix4d &_transform,
std::vector<math::Vector3d> &_verts,
std::vector<math::Vector3d> &_norms);
/// \brief Load vertices
/// \param[in] _id String id of the vertices XML node
/// \param[in] _transform Transform to apply to all vertices
/// \param[out] _verts Holds the resulting vertices
/// \param[out] _norms Holds the resulting normals
/// \param[out] _vertDup Holds a map of duplicate position indices
/// \param[out] _normDup Holds a map of duplicate normal indices
public: void LoadVertices(const std::string &_id,
const math::Matrix4d &_transform,
std::vector<math::Vector3d> &_verts,
std::vector<math::Vector3d> &_norms,
std::map<unsigned int, unsigned int> &_vertDup,
std::map<unsigned int, unsigned int> &_normDup);
/// \brief Load positions
/// \param[in] _id String id of the XML node
/// \param[in] _transform Transform to apply to all positions
/// \param[out] _values Holds the resulting position values
/// \param[out] _duplicates Holds a map of duplicate position indices
public: void LoadPositions(const std::string &_id,
const math::Matrix4d &_transform,
std::vector<math::Vector3d> &_values,
std::map<unsigned int, unsigned int> &_duplicates);
/// \brief Load normals
/// \param[in] _id String id of the XML node
/// \param[in] _transform Transform to apply to all normals
/// \param[out] _values Holds the resulting normal values
/// \param[out] _duplicates Holds a map of duplicate normal indices
public: void LoadNormals(const std::string &_id,
const math::Matrix4d &_transform,
std::vector<math::Vector3d> &_values,
std::map<unsigned int, unsigned int> &_duplicates);
/// \brief Load texture coordinates
/// \param[in] _id String id of the XML node
/// \param[out] _values Holds the resulting uv values
/// \param[out] _duplicates Holds a map of duplicate uv indices
public: void LoadTexCoords(const std::string &_id,
std::vector<math::Vector2d> &_values,
std::map<unsigned int, unsigned int> &_duplicates);
/// \brief Load a material
/// \param _name Name of the material XML element
/// \return A pointer to the new material
public: MaterialPtr LoadMaterial(const std::string &_name);
/// \brief Load a color or texture
/// \param[in] _elem Pointer to the XML element
/// \param[in] _type One of {diffuse, ambient, emission}
/// \param[out] _mat Material to load the texture or color into
public: void LoadColorOrTexture(tinyxml2::XMLElement *_elem,
const std::string &_type,
MaterialPtr _mat);
/// \brief Load triangles
/// \param[in] _trianglesXml Pointer the triangles XML instance
/// \param[in] _transform Transform to apply to all triangles
/// \param[out] _mesh Mesh that is currently being loaded
public: void LoadTriangles(tinyxml2::XMLElement *_trianglesXml,
const math::Matrix4d &_transform,
Mesh *_mesh);
/// \brief Load a polygon list
/// \param[in] _polylistXml Pointer to the XML element
/// \param[in] _transform Transform to apply to each polygon
/// \param[out] _mesh Mesh that is currently being loaded
public: void LoadPolylist(tinyxml2::XMLElement *_polylistXml,
const math::Matrix4d &_transform,
Mesh *_mesh);
/// \brief Load lines
/// \param[in] _xml Pointer to the XML element
/// \param[in] _transform Transform to apply
/// \param[out] _mesh Mesh that is currently being loaded
public: void LoadLines(tinyxml2::XMLElement *_xml,
const math::Matrix4d &_transform,
Mesh *_mesh);
/// \brief Load an entire scene
/// \param[out] _mesh Mesh that is currently being loaded
public: void LoadScene(Mesh *_mesh);
/// \brief Load a float value
/// \param[out] _elem Pointer to the XML element
/// \return The float value
public: float LoadFloat(tinyxml2::XMLElement *_elem);
/// \brief Load a transparent material. NOT FULLY IMPLEMENTED
/// \param[in] _elem Pointer to the XML element
/// \param[out] _mat Material to hold the transparent properties
public: void LoadTransparent(tinyxml2::XMLElement *_elem,
MaterialPtr _mat);
/// \brief Merges a new root node to the skeleton
/// \details This will do 1 of the things:
/// 1: If `_mergeNode` is already part of the skeleton, do nothing
/// 2: If the skeleton's root is a descendent of `_mergeNode`, sets
/// the new root node as `_mergeNode`
/// 3: If the skeleton and `_mergeNode` is unrelated, creates a new
/// dummy root and adds both of them as childrens.
// 4: If a dummy root already exists but the merge node contains
// all its children, set the merge node as the new root.
/// \param[in] _skeleton skeleton to merge
/// \param[in] _mergeNode new root node to merge
public: void MergeSkeleton(SkeletonPtr _skeleton,
SkeletonNode *_mergeNode);
/// \brief Apply the the inv bind transform to the skeleton pose.
/// \remarks have to set the model transforms starting from the root in
/// breadth first order. Because setting the model transform also updates
/// the transform based on the parent's inv model transform. Setting the
/// child before the parent results in the child's transform being
/// calculated from the "old" parent model transform.
/// \param[in] _skeleton the skeleton to work on
public: void ApplyInvBindTransform(SkeletonPtr _skeleton);
};
/// \brief Helper data structure for loading collada geometries.
class GeometryIndices
{
/// \brief Index of a vertex in the collada <p> element
public: unsigned int vertexIndex;
/// \brief Index of a normal in the collada <p> element
public: unsigned int normalIndex;
/// \brief A map of texture coordinate set index to index of a texture
/// coordinate in the collada <p> element
public: std::map<unsigned int, unsigned int> texcoordIndex;
/// \brief Index of a vertex in the Gazebo mesh
public: unsigned int mappedIndex;
};
}
}
/////////////////////////////////////////////////
void hash_combine(std::size_t &_seed, const double &_v)
{
std::hash<double> hasher;
_seed ^= hasher(_v) + 0x9e3779b9 + (_seed << 6) + (_seed >> 2);
}
/////////////////////////////////////////////////
struct Vector3Hash
{
std::size_t operator()(const math::Vector3d &_v) const
{
std::size_t seed = 0;
hash_combine(seed, _v.X());
hash_combine(seed, _v.Y());
hash_combine(seed, _v.Z());
return seed;
}
};
/////////////////////////////////////////////////
struct Vector2dHash
{
std::size_t operator()(const math::Vector2d &_v) const
{
std::size_t seed = 0;
hash_combine(seed, _v.X());
hash_combine(seed, _v.Y());
return seed;
}
};
//////////////////////////////////////////////////
ColladaLoader::ColladaLoader()
: MeshLoader(), dataPtr(ignition::utils::MakeImpl<Implementation>())
{
this->dataPtr->meter = 1.0;
}
//////////////////////////////////////////////////
ColladaLoader::~ColladaLoader()
{
}
//////////////////////////////////////////////////
Mesh *ColladaLoader::Load(const std::string &_filename)
{
this->dataPtr->positionIds.clear();
this->dataPtr->normalIds.clear();
this->dataPtr->texcoordIds.clear();
this->dataPtr->materialIds.clear();
this->dataPtr->positionDuplicateMap.clear();
this->dataPtr->normalDuplicateMap.clear();
this->dataPtr->texcoordDuplicateMap.clear();
// reset scale
this->dataPtr->meter = 1.0;
tinyxml2::XMLDocument xmlDoc;
this->dataPtr->path.clear();
std::string separator("/");
#ifdef WIN32
separator = std::string("\\");
#endif
if (_filename.rfind(separator) != std::string::npos)
{
this->dataPtr->path = _filename.substr(0, _filename.rfind(separator));
}
this->dataPtr->filename = _filename;
if (xmlDoc.LoadFile(_filename.c_str()) != tinyxml2::XML_SUCCESS)
ignerr << "Unable to load collada file[" << _filename << "]\n";
this->dataPtr->colladaXml = xmlDoc.FirstChildElement("COLLADA");
if (!this->dataPtr->colladaXml)
ignerr << "Missing COLLADA tag\n";
if (std::string(this->dataPtr->colladaXml->Attribute("version")) != "1.4.0" &&
std::string(this->dataPtr->colladaXml->Attribute("version")) != "1.4.1")
ignerr << "Invalid collada file. Must be version 1.4.0 or 1.4.1\n";
tinyxml2::XMLElement *assetXml =
this->dataPtr->colladaXml->FirstChildElement("asset");
if (assetXml)
{
tinyxml2::XMLElement *unitXml = assetXml->FirstChildElement("unit");
if (unitXml && unitXml->Attribute("meter"))
this->dataPtr->meter = math::parseFloat(
unitXml->Attribute("meter"));
}
Mesh *mesh = new Mesh();
mesh->SetPath(this->dataPtr->path);
this->dataPtr->LoadScene(mesh);
if (mesh->HasSkeleton())
this->dataPtr->ApplyInvBindTransform(mesh->MeshSkeleton());
// This will make the model the correct size.
mesh->Scale(math::Vector3d(
this->dataPtr->meter, this->dataPtr->meter, this->dataPtr->meter));
if (mesh->HasSkeleton())
mesh->MeshSkeleton()->Scale(this->dataPtr->meter);
return mesh;
}
/////////////////////////////////////////////////
void ColladaLoader::Implementation::LoadScene(Mesh *_mesh)
{
auto *sceneXml = this->colladaXml->FirstChildElement("scene");
std::string sceneURL =
sceneXml->FirstChildElement("instance_visual_scene")->Attribute("url");
tinyxml2::XMLElement *visSceneXml = this->ElementId("visual_scene", sceneURL);
this->currentScene = visSceneXml;
if (!visSceneXml)
{
ignerr << "Unable to find visual_scene id ='" << sceneURL << "'\n";
return;
}
tinyxml2::XMLElement *nodeXml = visSceneXml->FirstChildElement("node");
while (nodeXml)
{
this->LoadNode(nodeXml, _mesh, math::Matrix4d::Identity);
nodeXml = nodeXml->NextSiblingElement("node");
}
}
/////////////////////////////////////////////////
void ColladaLoader::Implementation::LoadNode(
tinyxml2::XMLElement *_elem, Mesh *_mesh,
const math::Matrix4d &_transform)
{
tinyxml2::XMLElement *nodeXml;
tinyxml2::XMLElement *instGeomXml;
math::Matrix4d transform = this->LoadNodeTransform(_elem);
transform = _transform * transform;
nodeXml = _elem->FirstChildElement("node");
while (nodeXml)
{
this->LoadNode(nodeXml, _mesh, transform);
nodeXml = nodeXml->NextSiblingElement("node");
}
if (_elem->Attribute("name"))
{
this->currentNodeName = _elem->Attribute("name");
}
else
{
// if node does not have a name, then append the mesh in this node
// to the first ancestor node that has a name, i.e. this mesh becomes
// part of the parent / ancestor mesh
tinyxml2::XMLElement *parent =
dynamic_cast<tinyxml2::XMLElement *>(_elem->Parent());
std::string nodeName;
while (parent && std::string(parent->Value()) == "node")
{
const char *name = parent->Attribute("name");
if (name)
{
nodeName = name;
break;
}
}
if (nodeName.empty())
{
// if none of the ancestor node has a name, then create a custom name
static int nodeCounter = 0;
nodeName = "unnamed_submesh_" + std::to_string(nodeCounter++);
}
this->currentNodeName = nodeName;
}
if (_elem->FirstChildElement("instance_node"))
{
std::string nodeURLStr =
_elem->FirstChildElement("instance_node")->Attribute("url");
nodeXml = this->ElementId("node", nodeURLStr);
if (!nodeXml)
{
ignerr << "Unable to find node[" << nodeURLStr << "]\n";
return;
}
this->LoadNode(nodeXml, _mesh, transform);
return;
}
else
nodeXml = _elem;
instGeomXml = nodeXml->FirstChildElement("instance_geometry");
while (instGeomXml)
{
std::string geomURL = instGeomXml->Attribute("url");
tinyxml2::XMLElement *geomXml = this->ElementId("geometry", geomURL);
this->materialMap.clear();
tinyxml2::XMLElement *bindMatXml, *techniqueXml, *matXml;
bindMatXml = instGeomXml->FirstChildElement("bind_material");
while (bindMatXml)
{
if ((techniqueXml = bindMatXml->FirstChildElement("technique_common")))
{
matXml = techniqueXml->FirstChildElement("instance_material");
while (matXml)
{
std::string symbol = matXml->Attribute("symbol");
std::string target = matXml->Attribute("target");
this->materialMap[symbol] = target;
matXml = matXml->NextSiblingElement("instance_material");
}
}
bindMatXml = bindMatXml->NextSiblingElement("bind_material");
}
if (_mesh->HasSkeleton())
_mesh->MeshSkeleton()->SetNumVertAttached(0);
this->LoadGeometry(geomXml, transform, _mesh);
instGeomXml = instGeomXml->NextSiblingElement("instance_geometry");
}
tinyxml2::XMLElement *instContrXml =
nodeXml->FirstChildElement("instance_controller");
while (instContrXml)
{
std::string contrURL = instContrXml->Attribute("url");
tinyxml2::XMLElement *contrXml = this->ElementId("controller", contrURL);
this->materialMap.clear();
tinyxml2::XMLElement *bindMatXml, *techniqueXml, *matXml;
bindMatXml = instContrXml->FirstChildElement("bind_material");
while (bindMatXml)
{
if ((techniqueXml = bindMatXml->FirstChildElement("technique_common")))
{
matXml = techniqueXml->FirstChildElement("instance_material");
while (matXml)
{
std::string symbol = matXml->Attribute("symbol");
std::string target = matXml->Attribute("target");
this->materialMap[symbol] = target;
matXml = matXml->NextSiblingElement("instance_material");
}
}
bindMatXml = bindMatXml->NextSiblingElement("bind_material");
}
std::vector<tinyxml2::XMLElement*> rootNodeXmls;
for (tinyxml2::XMLElement *skelXml =
instContrXml->FirstChildElement("skeleton"); skelXml;
skelXml = skelXml->NextSiblingElement("skeleton"))
{
std::string rootURL = skelXml->GetText();
rootNodeXmls.emplace_back(this->ElementId(currentScene,
"node", rootURL));
}
// no skeleton tag present, assume whole scene is a skeleton
if (rootNodeXmls.empty())
{
for (tinyxml2::XMLElement *child =
this->currentScene->FirstChildElement();
child; child = child->NextSiblingElement())
{
rootNodeXmls.emplace_back(child);
}
}
this->LoadController(contrXml, rootNodeXmls, transform, _mesh);
instContrXml = instContrXml->NextSiblingElement("instance_controller");
}
}
/////////////////////////////////////////////////
math::Matrix4d ColladaLoader::Implementation::LoadNodeTransform(
tinyxml2::XMLElement *_elem)
{
math::Matrix4d transform(math::Matrix4d::Identity);
if (_elem->FirstChildElement("matrix"))
{
std::string matrixStr = _elem->FirstChildElement("matrix")->GetText();
std::istringstream iss(matrixStr);
std::vector<double> values(16);
for (unsigned int i = 0; i < 16; ++i)
iss >> values[i];
transform.Set(values[0], values[1], values[2], values[3],
values[4], values[5], values[6], values[7],
values[8], values[9], values[10], values[11],
values[12], values[13], values[14], values[15]);
}
else
{
if (_elem->FirstChildElement("translate"))
{
std::string transStr = _elem->FirstChildElement("translate")->GetText();
math::Vector3d translate;
std::istringstream stream(transStr);
stream >> translate;
// translate *= this->meter;
transform.SetTranslation(translate);
}
tinyxml2::XMLElement *rotateXml = _elem->FirstChildElement("rotate");
while (rotateXml)
{
math::Matrix3d mat;
math::Vector3d axis;
double angle;
std::string rotateStr = rotateXml->GetText();
std::istringstream iss(rotateStr);
iss >> axis.X() >> axis.Y() >> axis.Z();
iss >> angle;
mat.Axis(axis, IGN_DTOR(angle));
math::Matrix4d mat4(math::Matrix4d::Identity);
mat4 = mat;
transform = transform * mat4;
rotateXml = rotateXml->NextSiblingElement("rotate");
}
if (_elem->FirstChildElement("scale"))
{
std::string scaleStr = _elem->FirstChildElement("scale")->GetText();
math::Vector3d scale;
std::istringstream stream(scaleStr);
stream >> scale;
math::Matrix4d scaleMat;
scaleMat.Scale(scale);
transform = transform * scaleMat;
}
}
return transform;
}
/////////////////////////////////////////////////
void ColladaLoader::Implementation::LoadController(
tinyxml2::XMLElement *_contrXml,
std::vector<tinyxml2::XMLElement *> _skelXmls,
const math::Matrix4d &_transform,
Mesh *_mesh)
{
if (nullptr == _contrXml)
{
ignerr << "Can't load null controller element." << std::endl;
return;
}
tinyxml2::XMLElement *skinXml = _contrXml->FirstChildElement("skin");
if (nullptr == skinXml)
{
ignerr << "Failed to find skin element" << std::endl;
return;
}
std::string geomURL = skinXml->Attribute("source");
auto shapeMat = skinXml->FirstChildElement("bind_shape_matrix");
if (nullptr == shapeMat || nullptr == shapeMat->GetText())
{
ignerr << "Missing <bind_shape_matrix>" << std::endl;
return;
}
std::string matrixStr = shapeMat->GetText();
std::istringstream iss(matrixStr);
std::vector<double> values(16);
for (unsigned int i = 0; i < 16; ++i)
iss >> values[i];
math::Matrix4d bindTrans;
bindTrans.Set(values[0], values[1], values[2], values[3],
values[4], values[5], values[6], values[7],
values[8], values[9], values[10], values[11],
values[12], values[13], values[14], values[15]);
tinyxml2::XMLElement *jointsXml = skinXml->FirstChildElement("joints");
if (nullptr == jointsXml)
{
ignerr << "Failed to find <joints> element" << std::endl;
return;
}
std::string jointsURL, invBindMatURL;
tinyxml2::XMLElement *inputXml = jointsXml->FirstChildElement("input");
while (inputXml)
{
std::string semantic = inputXml->Attribute("semantic");
std::string source = inputXml->Attribute("source");
if (semantic == "JOINT")
jointsURL = source;
else if (semantic == "INV_BIND_MATRIX")
invBindMatURL = source;
inputXml = inputXml->NextSiblingElement("input");
}
if (jointsURL.empty())
{
ignwarn << "Missing semantic='JOINT' input source" << std::endl;
}
if (invBindMatURL.empty())
{
ignwarn << "Missing semantic='INV__BIND_MATRIX' input source" << std::endl;
}
jointsXml = this->ElementId("source", jointsURL);
if (!jointsXml)
{
ignerr << "Could not find node [" << jointsURL << "]. "
<< "Failed to parse skinning information in Collada file." << std::endl;
return;
}
auto nameArray = jointsXml->FirstChildElement("Name_array");
if (nullptr == nameArray)
{
ignerr << "Missing <Name_array>" << std::endl;
return;
}
std::string jointsStr = nameArray->GetText();
std::vector<std::string> joints = split(jointsStr, " \t\r\n");
// Load the skeleton
SkeletonPtr skeleton = nullptr;
if (_mesh->HasSkeleton())
skeleton = _mesh->MeshSkeleton();
for (tinyxml2::XMLElement *rootNodeXml : _skelXmls)
{
SkeletonNode *rootSkelNode =
this->LoadSkeletonNodes(rootNodeXml, nullptr);
if (nullptr == skeleton)
{
skeleton = SkeletonPtr(new Skeleton(rootSkelNode));
_mesh->SetSkeleton(skeleton);
}
else if (nullptr != rootSkelNode)
this->MergeSkeleton(skeleton, rootSkelNode);
}
if (nullptr == skeleton)
{
ignerr << "Failed to create skeleton." << std::endl;
return;
}
skeleton->SetBindShapeTransform(bindTrans);
tinyxml2::XMLElement *rootXml = _contrXml->GetDocument()->RootElement();
if (rootXml && rootXml->FirstChildElement("library_animations"))
{
this->LoadAnimations(rootXml->FirstChildElement("library_animations"),
skeleton);
}
tinyxml2::XMLElement *invBMXml = this->ElementId("source", invBindMatURL);
if (nullptr == invBMXml)
{
ignerr << "Could not find node[" << invBindMatURL << "]. "
<< "Faild to parse skinning information in Collada file." << std::endl;
return;
}
std::string posesStr = invBMXml->FirstChildElement("float_array")->GetText();
std::vector<std::string> strs = split(posesStr, " \t\r\n");
for (unsigned int i = 0; i < joints.size(); ++i)
{
auto node = skeleton->NodeByName(joints[i]);
if (nullptr == node)
{
ignerr << "Node [" << joints[i] << "] is null." << std::endl;
continue;
}
unsigned int id = i * 16;
math::Matrix4d mat;
mat.Set(math::parseFloat(strs[id + 0]),
math::parseFloat(strs[id + 1]),
math::parseFloat(strs[id + 2]),
math::parseFloat(strs[id + 3]),
math::parseFloat(strs[id + 4]),
math::parseFloat(strs[id + 5]),
math::parseFloat(strs[id + 6]),
math::parseFloat(strs[id + 7]),
math::parseFloat(strs[id + 8]),
math::parseFloat(strs[id + 9]),
math::parseFloat(strs[id + 10]),
math::parseFloat(strs[id + 11]),
math::parseFloat(strs[id + 12]),
math::parseFloat(strs[id + 13]),
math::parseFloat(strs[id + 14]),
math::parseFloat(strs[id + 15]));
node->SetInverseBindTransform(mat);
}
tinyxml2::XMLElement *vertWeightsXml =
skinXml->FirstChildElement("vertex_weights");
if (nullptr == vertWeightsXml)
{
ignerr << "Failed to find vertex_weights" << std::endl;
return;
}
inputXml = vertWeightsXml->FirstChildElement("input");
unsigned int jOffset = 0;
unsigned int wOffset = 0;
std::string weightsURL;
while (inputXml)
{
std::string semantic = inputXml->Attribute("semantic");
std::string source = inputXml->Attribute("source");
int offset = std::stoi(inputXml->Attribute("offset"));
if (semantic == "JOINT")
{
jOffset = offset;
}
else
{
if (semantic == "WEIGHT")
{
weightsURL = source;
wOffset = offset;
}
}
inputXml = inputXml->NextSiblingElement("input");
}
tinyxml2::XMLElement *weightsXml = this->ElementId("source", weightsURL);
std::string wString = weightsXml->FirstChildElement("float_array")->GetText();
std::vector<std::string> wStrs = split(wString, " \t\r\n");
std::vector<float> weights;
for (unsigned int i = 0; i < wStrs.size(); ++i)
weights.push_back(math::parseFloat(wStrs[i]));
std::string cString = vertWeightsXml->FirstChildElement("vcount")->GetText();
std::string vString = vertWeightsXml->FirstChildElement("v")->GetText();
std::vector<std::string> vCountStrs = split(cString, " \t\r\n");
std::vector<std::string> vStrs = split(vString, " \t\r\n");
std::vector<unsigned int> vCount;
std::vector<unsigned int> v;
for (unsigned int i = 0; i < vCountStrs.size(); ++i)
vCount.push_back(math::parseInt(vCountStrs[i]));
for (unsigned int i = 0; i < vStrs.size(); ++i)
v.push_back(math::parseInt(vStrs[i]));
skeleton->SetNumVertAttached(vCount.size());
unsigned int vIndex = 0;
for (unsigned int i = 0; i < vCount.size(); ++i)
{
for (unsigned int j = 0; j < vCount[i]; ++j)
{
skeleton->AddVertNodeWeight(i, joints[v[vIndex + jOffset]],
weights[v[vIndex + wOffset]]);
vIndex += (jOffset + wOffset + 1);
}
}
tinyxml2::XMLElement *geomXml = this->ElementId("geometry", geomURL);
this->LoadGeometry(geomXml, _transform, _mesh);
}
/////////////////////////////////////////////////
void ColladaLoader::Implementation::LoadAnimations(tinyxml2::XMLElement *_xml,
SkeletonPtr _skel)
{
tinyxml2::XMLElement *childXml = _xml->FirstChildElement("animation");
if (childXml->FirstChildElement("animation"))
{
while (childXml)
{
this->LoadAnimationSet(childXml, _skel);
childXml = childXml->NextSiblingElement("animation");
}
}
else
this->LoadAnimationSet(_xml, _skel);
}
/////////////////////////////////////////////////
void ColladaLoader::Implementation::LoadAnimationSet(tinyxml2::XMLElement *_xml,
SkeletonPtr _skel)
{
std::stringstream animName;
if (_xml->Attribute("name"))
{
animName << _xml->Attribute("name");
}
else
{
if (_xml->Attribute("id"))
animName << _xml->Attribute("id");
else
animName << "animation" << (_skel->AnimationCount() + 1);
}
RawSkeletonAnim animation;
tinyxml2::XMLElement *animXml = _xml->FirstChildElement("animation");
while (animXml)
{
tinyxml2::XMLElement *chanXml = animXml->FirstChildElement("channel");
while (chanXml)
{
std::string sourceURL = chanXml->Attribute("source");
std::string targetStr = chanXml->Attribute("target");
std::string targetBone = targetStr.substr(0, targetStr.find('/'));
char sep = '0';
if (targetStr.find('(') != std::string::npos)
sep = '(';
else
if (targetStr.find('.') != std::string::npos)
sep = '.';
std::string targetTrans;
if (sep == '0')
targetTrans = targetStr.substr(targetStr.find('/') + 1);
else
targetTrans = targetStr.substr(targetStr.find('/') + 1,
targetStr.find(sep) - targetStr.find('/') - 1);
std::string idxStr = targetStr.substr(targetStr.find(sep) + 1);
int idx1 = -1;
int idx2 = -1;
if (sep == '.')
{
idx1 = (idxStr == "X") ? 0 : ((idxStr == "Y") ? 1 : ((idxStr == "Z")
? 2 : ((idxStr == "ANGLE") ? 3 : -1)));
}
else
{
if (sep == '(')
{
std::string idx1Str = idxStr.substr(0, 1);
idx1 = math::parseInt(idx1Str);
if (idxStr.length() > 4)
{
std::string idx2Str = idxStr.substr(3, 1);
idx2 = math::parseInt(idx2Str);
}
}
}
tinyxml2::XMLElement *frameTimesXml = NULL;
tinyxml2::XMLElement *frameTransXml = NULL;