summaryrefslogtreecommitdiff
path: root/thirdparty/assimp/code/Common/SceneCombiner.cpp
blob: f7b13cc951282e23b3e1ce30f1095651a4f13a94 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------

Copyright (c) 2006-2019, assimp team


All rights reserved.

Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.

* Redistributions in binary form must reproduce the above
  copyright notice, this list of conditions and the
  following disclaimer in the documentation and/or other
  materials provided with the distribution.

* Neither the name of the assimp team, nor the names of its
  contributors may be used to endorse or promote products
  derived from this software without specific prior
  written permission of the assimp team.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

----------------------------------------------------------------------
*/

// TODO: refactor entire file to get rid of the "flat-copy" first approach
// to copying structures. This easily breaks in the most unintuitive way
// possible as new fields are added to assimp structures.

// ----------------------------------------------------------------------------
/** 
  * @file Implements Assimp::SceneCombiner. This is a smart utility
  *       class that combines multiple scenes, meshes, ... into one. Currently
  *       these utilities are used by the IRR and LWS loaders and the
  *       OptimizeGraph step.
  */
// ----------------------------------------------------------------------------
#include <assimp/SceneCombiner.h>
#include <assimp/StringUtils.h>
#include <assimp/fast_atof.h>
#include <assimp/metadata.h>
#include <assimp/Hash.h>
#include "time.h"
#include <assimp/DefaultLogger.hpp>
#include <assimp/scene.h>
#include <assimp/mesh.h>
#include <stdio.h>
#include "ScenePrivate.h"

namespace Assimp {

// ------------------------------------------------------------------------------------------------
// Add a prefix to a string
inline
void PrefixString(aiString& string,const char* prefix, unsigned int len) {
    // If the string is already prefixed, we won't prefix it a second time
    if (string.length >= 1 && string.data[0] == '$')
        return;

    if (len+string.length>=MAXLEN-1) {
        ASSIMP_LOG_DEBUG("Can't add an unique prefix because the string is too long");
        ai_assert(false);
        return;
    }

    // Add the prefix
    ::memmove(string.data+len,string.data,string.length+1);
    ::memcpy (string.data, prefix, len);

    // And update the string's length
    string.length += len;
}

// ------------------------------------------------------------------------------------------------
// Add node identifiers to a hashing set
void SceneCombiner::AddNodeHashes(aiNode* node, std::set<unsigned int>& hashes) {
    // Add node name to hashing set if it is non-empty - empty nodes are allowed
    // and they can't have any anims assigned so its absolutely safe to duplicate them.
    if (node->mName.length) {
        hashes.insert( SuperFastHash(node->mName.data, static_cast<uint32_t>(node->mName.length)) );
    }

    // Process all children recursively
    for (unsigned int i = 0; i < node->mNumChildren;++i)
        AddNodeHashes(node->mChildren[i],hashes);
}

// ------------------------------------------------------------------------------------------------
// Add a name prefix to all nodes in a hierarchy
void SceneCombiner::AddNodePrefixes(aiNode* node, const char* prefix, unsigned int len) {
    ai_assert(NULL != prefix);
    PrefixString(node->mName,prefix,len);

    // Process all children recursively
    for ( unsigned int i = 0; i < node->mNumChildren; ++i ) {
        AddNodePrefixes( node->mChildren[ i ], prefix, len );
    }
}

// ------------------------------------------------------------------------------------------------
// Search for matching names
bool SceneCombiner::FindNameMatch(const aiString& name, std::vector<SceneHelper>& input, unsigned int cur) {
    const unsigned int hash = SuperFastHash(name.data, static_cast<uint32_t>(name.length));

    // Check whether we find a positive match in one of the given sets
    for (unsigned int i = 0; i < input.size(); ++i) {
        if (cur != i && input[i].hashes.find(hash) != input[i].hashes.end()) {
            return true;
        }
    }
    return false;
}

// ------------------------------------------------------------------------------------------------
// Add a name prefix to all nodes in a hierarchy if a hash match is found
void SceneCombiner::AddNodePrefixesChecked(aiNode* node, const char* prefix, unsigned int len,
        std::vector<SceneHelper>& input, unsigned int cur) {
    ai_assert(NULL != prefix);
    const unsigned int hash = SuperFastHash(node->mName.data, static_cast<uint32_t>(node->mName.length));

    // Check whether we find a positive match in one of the given sets
    for (unsigned int i = 0; i < input.size(); ++i) {
        if (cur != i && input[i].hashes.find(hash) != input[i].hashes.end()) {
            PrefixString(node->mName,prefix,len);
            break;
        }
    }

    // Process all children recursively
    for (unsigned int i = 0; i < node->mNumChildren;++i)
        AddNodePrefixesChecked(node->mChildren[i],prefix,len,input,cur);
}

// ------------------------------------------------------------------------------------------------
// Add an offset to all mesh indices in a node graph
void SceneCombiner::OffsetNodeMeshIndices (aiNode* node, unsigned int offset) {
    for (unsigned int i = 0; i < node->mNumMeshes;++i)
        node->mMeshes[i] += offset;

    for ( unsigned int i = 0; i < node->mNumChildren; ++i ) {
        OffsetNodeMeshIndices( node->mChildren[ i ], offset );
    }
}

// ------------------------------------------------------------------------------------------------
// Merges two scenes. Currently only used by the LWS loader.
void SceneCombiner::MergeScenes(aiScene** _dest,std::vector<aiScene*>& src, unsigned int flags) {
    if ( nullptr == _dest ) {
        return;
    }

    // if _dest points to NULL allocate a new scene. Otherwise clear the old and reuse it
    if (src.empty()) {
        if (*_dest) {
            (*_dest)->~aiScene();
            SceneCombiner::CopySceneFlat(_dest,src[0]);
        }
        else *_dest = src[0];
        return;
    }
    if (*_dest)(*_dest)->~aiScene();
    else *_dest = new aiScene();

    // Create a dummy scene to serve as master for the others
    aiScene* master = new aiScene();
    master->mRootNode = new aiNode();
    master->mRootNode->mName.Set("<MergeRoot>");

    std::vector<AttachmentInfo> srcList (src.size());
    for (unsigned int i = 0; i < srcList.size();++i)    {
        srcList[i] = AttachmentInfo(src[i],master->mRootNode);
    }

    // 'master' will be deleted afterwards
    MergeScenes (_dest, master, srcList, flags);
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::AttachToGraph (aiNode* attach, std::vector<NodeAttachmentInfo>& srcList) {
    unsigned int cnt;
    for ( cnt = 0; cnt < attach->mNumChildren; ++cnt ) {
        AttachToGraph( attach->mChildren[ cnt ], srcList );
    }

    cnt = 0;
    for (std::vector<NodeAttachmentInfo>::iterator it = srcList.begin();
         it != srcList.end(); ++it)
    {
        if ((*it).attachToNode == attach && !(*it).resolved)
            ++cnt;
    }

    if (cnt)    {
        aiNode** n = new aiNode*[cnt+attach->mNumChildren];
        if (attach->mNumChildren)   {
            ::memcpy(n,attach->mChildren,sizeof(void*)*attach->mNumChildren);
            delete[] attach->mChildren;
        }
        attach->mChildren = n;

        n += attach->mNumChildren;
        attach->mNumChildren += cnt;

        for (unsigned int i = 0; i < srcList.size();++i)    {
            NodeAttachmentInfo& att = srcList[i];
            if (att.attachToNode == attach && !att.resolved)    {
                *n = att.node;
                (**n).mParent = attach;
                ++n;

                // mark this attachment as resolved
                att.resolved = true;
            }
        }
    }
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::AttachToGraph ( aiScene* master, std::vector<NodeAttachmentInfo>& src) {
    ai_assert(NULL != master);
    AttachToGraph(master->mRootNode,src);
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::MergeScenes(aiScene** _dest, aiScene* master, std::vector<AttachmentInfo>& srcList, unsigned int flags) {
    if ( nullptr == _dest ) {
        return;
    }

    // if _dest points to NULL allocate a new scene. Otherwise clear the old and reuse it
    if (srcList.empty())    {
        if (*_dest) {
            SceneCombiner::CopySceneFlat(_dest,master);
        }
        else *_dest = master;
        return;
    }
    if (*_dest) {
        (*_dest)->~aiScene();
        new (*_dest) aiScene();
    }
    else *_dest = new aiScene();

    aiScene* dest = *_dest;

    std::vector<SceneHelper> src (srcList.size()+1);
    src[0].scene = master;
    for (unsigned int i = 0; i < srcList.size();++i)    {
        src[i+1] = SceneHelper( srcList[i].scene );
    }

    // this helper array specifies which scenes are duplicates of others
    std::vector<unsigned int> duplicates(src.size(),UINT_MAX);

    // this helper array is used as lookup table several times
    std::vector<unsigned int> offset(src.size());

    // Find duplicate scenes
    for (unsigned int i = 0; i < src.size();++i) {
        if (duplicates[i] != i && duplicates[i] != UINT_MAX) {
            continue;
        }

        duplicates[i] = i;
        for ( unsigned int a = i+1; a < src.size(); ++a)    {
            if (src[i].scene == src[a].scene) {
                duplicates[a] = i;
            }
        }
    }

    // Generate unique names for all named stuff?
    if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES)
    {
#if 0
        // Construct a proper random number generator
        boost::mt19937 rng(  );
        boost::uniform_int<> dist(1u,1 << 24u);
        boost::variate_generator<boost::mt19937&, boost::uniform_int<> > rndGen(rng, dist);
#endif
        for (unsigned int i = 1; i < src.size();++i)
        {
            //if (i != duplicates[i])
            //{
            //  // duplicate scenes share the same UID
            //  ::strcpy( src[i].id, src[duplicates[i]].id );
            //  src[i].idlen = src[duplicates[i]].idlen;

            //  continue;
            //}

            src[i].idlen = ai_snprintf(src[i].id, 32, "$%.6X$_",i);

            if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {

                // Compute hashes for all identifiers in this scene and store them
                // in a sorted table (for convenience I'm using std::set). We hash
                // just the node and animation channel names, all identifiers except
                // the material names should be caught by doing this.
                AddNodeHashes(src[i]->mRootNode,src[i].hashes);

                for (unsigned int a = 0; a < src[i]->mNumAnimations;++a) {
                    aiAnimation* anim = src[i]->mAnimations[a];
                    src[i].hashes.insert(SuperFastHash(anim->mName.data,static_cast<uint32_t>(anim->mName.length)));
                }
            }
        }
    }

    unsigned int cnt;

    // First find out how large the respective output arrays must be
    for ( unsigned int n = 0; n < src.size();++n )
    {
        SceneHelper* cur = &src[n];

        if (n == duplicates[n] || flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY)   {
            dest->mNumTextures   += (*cur)->mNumTextures;
            dest->mNumMaterials  += (*cur)->mNumMaterials;
            dest->mNumMeshes     += (*cur)->mNumMeshes;
        }

        dest->mNumLights     += (*cur)->mNumLights;
        dest->mNumCameras    += (*cur)->mNumCameras;
        dest->mNumAnimations += (*cur)->mNumAnimations;

        // Combine the flags of all scenes
        // We need to process them flag-by-flag here to get correct results
        // dest->mFlags ; //|= (*cur)->mFlags;
        if ((*cur)->mFlags & AI_SCENE_FLAGS_NON_VERBOSE_FORMAT) {
            dest->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;
        }
    }

    // generate the output texture list + an offset table for all texture indices
    if (dest->mNumTextures)
    {
        aiTexture** pip = dest->mTextures = new aiTexture*[dest->mNumMaterials];
        cnt = 0;
        for ( unsigned int n = 0; n < src.size();++n )
        {
            SceneHelper* cur = &src[n];
            for (unsigned int i = 0; i < (*cur)->mNumTextures;++i)
            {
                if (n != duplicates[n])
                {
                    if ( flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY)
                        Copy(pip,(*cur)->mTextures[i]);

                    else continue;
                }
                else *pip = (*cur)->mTextures[i];
                ++pip;
            }

            offset[n] = cnt;
            cnt = (unsigned int)(pip - dest->mTextures);
        }
    }

    // generate the output material list + an offset table for all material indices
    if (dest->mNumMaterials)
    {
        aiMaterial** pip = dest->mMaterials = new aiMaterial*[dest->mNumMaterials];
        cnt = 0;
        for ( unsigned int n = 0; n < src.size();++n )  {
            SceneHelper* cur = &src[n];
            for (unsigned int i = 0; i < (*cur)->mNumMaterials;++i)
            {
                if (n != duplicates[n])
                {
                    if ( flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY)
                        Copy(pip,(*cur)->mMaterials[i]);

                    else continue;
                }
                else *pip = (*cur)->mMaterials[i];

                if ((*cur)->mNumTextures != dest->mNumTextures)     {
                    // We need to update all texture indices of the mesh. So we need to search for
                    // a material property called '$tex.file'

                    for (unsigned int a = 0; a < (*pip)->mNumProperties;++a)
                    {
                        aiMaterialProperty* prop = (*pip)->mProperties[a];
                        if (!strncmp(prop->mKey.data,"$tex.file",9))
                        {
                            // Check whether this texture is an embedded texture.
                            // In this case the property looks like this: *<n>,
                            // where n is the index of the texture.
                            aiString& s = *((aiString*)prop->mData);
                            if ('*' == s.data[0])   {
                                // Offset the index and write it back ..
                                const unsigned int idx = strtoul10(&s.data[1]) + offset[n];
                                ASSIMP_itoa10(&s.data[1],sizeof(s.data)-1,idx);
                            }
                        }

                        // Need to generate new, unique material names?
                        else if (!::strcmp( prop->mKey.data,"$mat.name" ) && flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES)
                        {
                            aiString* pcSrc = (aiString*) prop->mData;
                            PrefixString(*pcSrc, (*cur).id, (*cur).idlen);
                        }
                    }
                }
                ++pip;
            }

            offset[n] = cnt;
            cnt = (unsigned int)(pip - dest->mMaterials);
        }
    }

    // generate the output mesh list + again an offset table for all mesh indices
    if (dest->mNumMeshes)
    {
        aiMesh** pip = dest->mMeshes = new aiMesh*[dest->mNumMeshes];
        cnt = 0;
        for ( unsigned int n = 0; n < src.size();++n )
        {
            SceneHelper* cur = &src[n];
            for (unsigned int i = 0; i < (*cur)->mNumMeshes;++i)
            {
                if (n != duplicates[n]) {
                    if ( flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY)
                        Copy(pip, (*cur)->mMeshes[i]);

                    else continue;
                }
                else *pip = (*cur)->mMeshes[i];

                // update the material index of the mesh
                (*pip)->mMaterialIndex +=  offset[n];
                ++pip;
            }

            // reuse the offset array - store now the mesh offset in it
            offset[n] = cnt;
            cnt = (unsigned int)(pip - dest->mMeshes);
        }
    }

    std::vector <NodeAttachmentInfo> nodes;
    nodes.reserve(srcList.size());

    // ----------------------------------------------------------------------------
    // Now generate the output node graph. We need to make those
    // names in the graph that are referenced by anims or lights
    // or cameras unique. So we add a prefix to them ... $<rand>_
    // We could also use a counter, but using a random value allows us to
    // use just one prefix if we are joining multiple scene hierarchies recursively.
    // Chances are quite good we don't collide, so we try that ...
    // ----------------------------------------------------------------------------

    // Allocate space for light sources, cameras and animations
    aiLight** ppLights = dest->mLights = (dest->mNumLights
        ? new aiLight*[dest->mNumLights] : NULL);

    aiCamera** ppCameras = dest->mCameras = (dest->mNumCameras
        ? new aiCamera*[dest->mNumCameras] : NULL);

    aiAnimation** ppAnims = dest->mAnimations = (dest->mNumAnimations
        ? new aiAnimation*[dest->mNumAnimations] : NULL);

    for ( int n = static_cast<int>(src.size()-1); n >= 0 ;--n ) /* !!! important !!! */
    {
        SceneHelper* cur = &src[n];
        aiNode* node;

        // To offset or not to offset, this is the question
        if (n != (int)duplicates[n])
        {
            // Get full scene-graph copy
            Copy( &node, (*cur)->mRootNode );
            OffsetNodeMeshIndices(node,offset[duplicates[n]]);

            if (flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY) {
                // (note:) they are already 'offseted' by offset[duplicates[n]]
                OffsetNodeMeshIndices(node,offset[n] - offset[duplicates[n]]);
            }
        }
        else // if (n == duplicates[n])
        {
            node = (*cur)->mRootNode;
            OffsetNodeMeshIndices(node,offset[n]);
        }
        if (n) // src[0] is the master node
            nodes.push_back(NodeAttachmentInfo( node,srcList[n-1].attachToNode,n ));

        // add name prefixes?
        if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES) {

            // or the whole scenegraph
            if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
                AddNodePrefixesChecked(node,(*cur).id,(*cur).idlen,src,n);
            }
            else AddNodePrefixes(node,(*cur).id,(*cur).idlen);

            // meshes
            for (unsigned int i = 0; i < (*cur)->mNumMeshes;++i)    {
                aiMesh* mesh = (*cur)->mMeshes[i];

                // rename all bones
                for (unsigned int a = 0; a < mesh->mNumBones;++a)   {
                    if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
                        if (!FindNameMatch(mesh->mBones[a]->mName,src,n))
                            continue;
                    }
                    PrefixString(mesh->mBones[a]->mName,(*cur).id,(*cur).idlen);
                }
            }
        }

        // --------------------------------------------------------------------
        // Copy light sources
        for (unsigned int i = 0; i < (*cur)->mNumLights;++i,++ppLights)
        {
            if (n != (int)duplicates[n]) // duplicate scene?
            {
                Copy(ppLights, (*cur)->mLights[i]);
            }
            else *ppLights = (*cur)->mLights[i];


            // Add name prefixes?
            if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES) {
                if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
                    if (!FindNameMatch((*ppLights)->mName,src,n))
                        continue;
                }

                PrefixString((*ppLights)->mName,(*cur).id,(*cur).idlen);
            }
        }

        // --------------------------------------------------------------------
        // Copy cameras
        for (unsigned int i = 0; i < (*cur)->mNumCameras;++i,++ppCameras)   {
            if (n != (int)duplicates[n]) // duplicate scene?
            {
                Copy(ppCameras, (*cur)->mCameras[i]);
            }
            else *ppCameras = (*cur)->mCameras[i];

            // Add name prefixes?
            if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES) {
                if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
                    if (!FindNameMatch((*ppCameras)->mName,src,n))
                        continue;
                }

                PrefixString((*ppCameras)->mName,(*cur).id,(*cur).idlen);
            }
        }

        // --------------------------------------------------------------------
        // Copy animations
        for (unsigned int i = 0; i < (*cur)->mNumAnimations;++i,++ppAnims)  {
            if (n != (int)duplicates[n]) // duplicate scene?
            {
                Copy(ppAnims, (*cur)->mAnimations[i]);
            }
            else *ppAnims = (*cur)->mAnimations[i];

            // Add name prefixes?
            if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES) {
                if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
                    if (!FindNameMatch((*ppAnims)->mName,src,n))
                        continue;
                }

                PrefixString((*ppAnims)->mName,(*cur).id,(*cur).idlen);

                // don't forget to update all node animation channels
                for (unsigned int a = 0; a < (*ppAnims)->mNumChannels;++a) {
                    if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
                        if (!FindNameMatch((*ppAnims)->mChannels[a]->mNodeName,src,n))
                            continue;
                    }

                    PrefixString((*ppAnims)->mChannels[a]->mNodeName,(*cur).id,(*cur).idlen);
                }
            }
        }
    }

    // Now build the output graph
    AttachToGraph ( master, nodes);
    dest->mRootNode = master->mRootNode;

    // Check whether we succeeded at building the output graph
    for (std::vector <NodeAttachmentInfo> ::iterator it = nodes.begin();
        it != nodes.end(); ++it)
    {
        if (!(*it).resolved) {
            if (flags & AI_INT_MERGE_SCENE_RESOLVE_CROSS_ATTACHMENTS) {
                // search for this attachment point in all other imported scenes, too.
                for ( unsigned int n = 0; n < src.size();++n ) {
                    if (n != (*it).src_idx) {
                        AttachToGraph(src[n].scene,nodes);
                        if ((*it).resolved)
                            break;
                    }
                }
            }
            if (!(*it).resolved) {
                ASSIMP_LOG_ERROR_F( "SceneCombiner: Failed to resolve attachment ", (*it).node->mName.data,
                    " ", (*it).attachToNode->mName.data );
            }
        }
    }

    // now delete all input scenes. Make sure duplicate scenes aren't
    // deleted more than one time
    for ( unsigned int n = 0; n < src.size();++n )  {
        if (n != duplicates[n]) // duplicate scene?
            continue;

        aiScene* deleteMe = src[n].scene;

        // We need to delete the arrays before the destructor is called -
        // we are reusing the array members
        delete[] deleteMe->mMeshes;     deleteMe->mMeshes     = NULL;
        delete[] deleteMe->mCameras;    deleteMe->mCameras    = NULL;
        delete[] deleteMe->mLights;     deleteMe->mLights     = NULL;
        delete[] deleteMe->mMaterials;  deleteMe->mMaterials  = NULL;
        delete[] deleteMe->mAnimations; deleteMe->mAnimations = NULL;

        deleteMe->mRootNode = NULL;

        // Now we can safely delete the scene
        delete deleteMe;
    }

    // Check flags
    if (!dest->mNumMeshes || !dest->mNumMaterials) {
        dest->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
    }

    // We're finished
}

// ------------------------------------------------------------------------------------------------
// Build a list of unique bones
void SceneCombiner::BuildUniqueBoneList(std::list<BoneWithHash>& asBones,
    std::vector<aiMesh*>::const_iterator it,
    std::vector<aiMesh*>::const_iterator end)
{
    unsigned int iOffset = 0;
    for (; it != end;++it)  {
        for (unsigned int l = 0; l < (*it)->mNumBones;++l)  {
            aiBone* p = (*it)->mBones[l];
            uint32_t itml = SuperFastHash(p->mName.data,(unsigned int)p->mName.length);

            std::list<BoneWithHash>::iterator it2  = asBones.begin();
            std::list<BoneWithHash>::iterator end2 = asBones.end();

            for (;it2 != end2;++it2)    {
                if ((*it2).first == itml)   {
                    (*it2).pSrcBones.push_back(BoneSrcIndex(p,iOffset));
                    break;
                }
            }
            if (end2 == it2)    {
                // need to begin a new bone entry
                asBones.push_back(BoneWithHash());
                BoneWithHash& btz = asBones.back();

                // setup members
                btz.first = itml;
                btz.second = &p->mName;
                btz.pSrcBones.push_back(BoneSrcIndex(p,iOffset));
            }
        }
        iOffset += (*it)->mNumVertices;
    }
}

// ------------------------------------------------------------------------------------------------
// Merge a list of bones
void SceneCombiner::MergeBones(aiMesh* out,std::vector<aiMesh*>::const_iterator it,
    std::vector<aiMesh*>::const_iterator end)
{
    if ( nullptr == out || out->mNumBones == 0 ) {
        return;
    }

    // find we need to build an unique list of all bones.
    // we work with hashes to make the comparisons MUCH faster,
    // at least if we have many bones.
    std::list<BoneWithHash> asBones;
    BuildUniqueBoneList( asBones, it, end );

    // now create the output bones
    out->mNumBones = 0;
    out->mBones = new aiBone*[asBones.size()];

    for (std::list<BoneWithHash>::const_iterator boneIt = asBones.begin(),boneEnd = asBones.end(); boneIt != boneEnd; ++boneIt )  {
        // Allocate a bone and setup it's name
        aiBone* pc = out->mBones[out->mNumBones++] = new aiBone();
        pc->mName = aiString( *( boneIt->second ));

        std::vector< BoneSrcIndex >::const_iterator wend = boneIt->pSrcBones.end();

        // Loop through all bones to be joined for this bone
        for (std::vector< BoneSrcIndex >::const_iterator wmit = boneIt->pSrcBones.begin(); wmit != wend; ++wmit)  {
            pc->mNumWeights += (*wmit).first->mNumWeights;

            // NOTE: different offset matrices for bones with equal names
            // are - at the moment - not handled correctly.
            if (wmit != boneIt->pSrcBones.begin() && pc->mOffsetMatrix != wmit->first->mOffsetMatrix) {
                ASSIMP_LOG_WARN("Bones with equal names but different offset matrices can't be joined at the moment");
                continue;
            }
            pc->mOffsetMatrix = wmit->first->mOffsetMatrix;
        }

        // Allocate the vertex weight array
        aiVertexWeight* avw = pc->mWeights = new aiVertexWeight[pc->mNumWeights];

        // And copy the final weights - adjust the vertex IDs by the
        // face index offset of the corresponding mesh.
        for (std::vector< BoneSrcIndex >::const_iterator wmit = (*boneIt).pSrcBones.begin(); wmit != (*boneIt).pSrcBones.end(); ++wmit) {
            if (wmit == wend) {
                break;
            }

            aiBone* pip = (*wmit).first;
            for (unsigned int mp = 0; mp < pip->mNumWeights;++mp,++avw) {
                const aiVertexWeight& vfi = pip->mWeights[mp];
                avw->mWeight = vfi.mWeight;
                avw->mVertexId = vfi.mVertexId + (*wmit).second;
            }
        }
    }
}

// ------------------------------------------------------------------------------------------------
// Merge a list of meshes
void SceneCombiner::MergeMeshes(aiMesh** _out, unsigned int /*flags*/,
    std::vector<aiMesh*>::const_iterator begin,
    std::vector<aiMesh*>::const_iterator end)
{
    if ( nullptr == _out ) {
        return;
    }

    if (begin == end)   {
        *_out = NULL; // no meshes ...
        return;
    }

    // Allocate the output mesh
    aiMesh* out = *_out = new aiMesh();
    out->mMaterialIndex = (*begin)->mMaterialIndex;

    std::string name;
    // Find out how much output storage we'll need
    for (std::vector<aiMesh*>::const_iterator it = begin; it != end; ++it) {
        const char *meshName( (*it)->mName.C_Str() );
        name += std::string( meshName );
        if ( it != end - 1 ) {
            name += ".";
        }
        out->mNumVertices   += (*it)->mNumVertices;
        out->mNumFaces      += (*it)->mNumFaces;
        out->mNumBones      += (*it)->mNumBones;

        // combine primitive type flags
        out->mPrimitiveTypes |= (*it)->mPrimitiveTypes;
    }
    out->mName.Set( name.c_str() );

    if (out->mNumVertices) {
        aiVector3D* pv2;

        // copy vertex positions
        if ((**begin).HasPositions())   {

            pv2 = out->mVertices = new aiVector3D[out->mNumVertices];
            for (std::vector<aiMesh*>::const_iterator it = begin; it != end; ++it)  {
                if ((*it)->mVertices)   {
                    ::memcpy(pv2,(*it)->mVertices,(*it)->mNumVertices*sizeof(aiVector3D));
                }
                else ASSIMP_LOG_WARN("JoinMeshes: Positions expected but input mesh contains no positions");
                pv2 += (*it)->mNumVertices;
            }
        }
        // copy normals
        if ((**begin).HasNormals()) {

            pv2 = out->mNormals = new aiVector3D[out->mNumVertices];
            for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it)   {
                if ((*it)->mNormals)    {
                    ::memcpy(pv2,(*it)->mNormals,(*it)->mNumVertices*sizeof(aiVector3D));
                } else {
                    ASSIMP_LOG_WARN( "JoinMeshes: Normals expected but input mesh contains no normals" );
                }
                pv2 += (*it)->mNumVertices;
            }
        }
        // copy tangents and bi-tangents
        if ((**begin).HasTangentsAndBitangents())   {

            pv2 = out->mTangents = new aiVector3D[out->mNumVertices];
            aiVector3D* pv2b = out->mBitangents = new aiVector3D[out->mNumVertices];

            for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
                if ((*it)->mTangents)   {
                    ::memcpy(pv2, (*it)->mTangents,  (*it)->mNumVertices*sizeof(aiVector3D));
                    ::memcpy(pv2b,(*it)->mBitangents,(*it)->mNumVertices*sizeof(aiVector3D));
                } else {
                    ASSIMP_LOG_WARN( "JoinMeshes: Tangents expected but input mesh contains no tangents" );
                }
                pv2  += (*it)->mNumVertices;
                pv2b += (*it)->mNumVertices;
            }
        }
        // copy texture coordinates
        unsigned int n = 0;
        while ((**begin).HasTextureCoords(n)) {
            out->mNumUVComponents[n] = (*begin)->mNumUVComponents[n];

            pv2 = out->mTextureCoords[n] = new aiVector3D[out->mNumVertices];
            for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it)   {
                if ((*it)->mTextureCoords[n])   {
                    ::memcpy(pv2,(*it)->mTextureCoords[n],(*it)->mNumVertices*sizeof(aiVector3D));
                } else {
                    ASSIMP_LOG_WARN( "JoinMeshes: UVs expected but input mesh contains no UVs" );
                }
                pv2 += (*it)->mNumVertices;
            }
            ++n;
        }
        // copy vertex colors
        n = 0;
        while ((**begin).HasVertexColors(n))    {
            aiColor4D *pVec2 = out->mColors[n] = new aiColor4D[out->mNumVertices];
            for ( std::vector<aiMesh*>::const_iterator it = begin; it != end; ++it )   {
                if ((*it)->mColors[n])  {
                    ::memcpy( pVec2, (*it)->mColors[ n ], (*it)->mNumVertices * sizeof( aiColor4D ) ) ;
                } else {
                    ASSIMP_LOG_WARN( "JoinMeshes: VCs expected but input mesh contains no VCs" );
                }
                pVec2 += (*it)->mNumVertices;
            }
            ++n;
        }
    }

    if (out->mNumFaces) // just for safety
    {
        // copy faces
        out->mFaces = new aiFace[out->mNumFaces];
        aiFace* pf2 = out->mFaces;

        unsigned int ofs = 0;
        for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it)   {
            for (unsigned int m = 0; m < (*it)->mNumFaces;++m,++pf2)    {
                aiFace& face = (*it)->mFaces[m];
                pf2->mNumIndices = face.mNumIndices;
                pf2->mIndices = face.mIndices;

                if (ofs)    {
                    // add the offset to the vertex
                    for (unsigned int q = 0; q < face.mNumIndices; ++q)
                        face.mIndices[q] += ofs;
                }
                face.mIndices = NULL;
            }
            ofs += (*it)->mNumVertices;
        }
    }

    // bones - as this is quite lengthy, I moved the code to a separate function
    if (out->mNumBones)
        MergeBones(out,begin,end);

    // delete all source meshes
    for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it)
        delete *it;
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::MergeMaterials(aiMaterial** dest,
        std::vector<aiMaterial*>::const_iterator begin,
        std::vector<aiMaterial*>::const_iterator end)
{
    if ( nullptr == dest ) {
        return;
    }

    if (begin == end)   {
        *dest = NULL; // no materials ...
        return;
    }

    // Allocate the output material
    aiMaterial* out = *dest = new aiMaterial();

    // Get the maximal number of properties
    unsigned int size = 0;
    for (std::vector<aiMaterial*>::const_iterator it = begin; it != end; ++it) {
        size += (*it)->mNumProperties;
    }

    out->Clear();
    delete[] out->mProperties;

    out->mNumAllocated = size;
    out->mNumProperties = 0;
    out->mProperties = new aiMaterialProperty*[out->mNumAllocated];

    for (std::vector<aiMaterial*>::const_iterator it = begin; it != end; ++it) {
        for(unsigned int i = 0; i < (*it)->mNumProperties; ++i) {
            aiMaterialProperty* sprop = (*it)->mProperties[i];

            // Test if we already have a matching property
            const aiMaterialProperty* prop_exist;
            if(aiGetMaterialProperty(out, sprop->mKey.C_Str(), sprop->mSemantic, sprop->mIndex, &prop_exist) != AI_SUCCESS) {
                // If not, we add it to the new material
                aiMaterialProperty* prop = out->mProperties[out->mNumProperties] = new aiMaterialProperty();

                prop->mDataLength = sprop->mDataLength;
                prop->mData = new char[prop->mDataLength];
                ::memcpy(prop->mData, sprop->mData, prop->mDataLength);

                prop->mIndex    = sprop->mIndex;
                prop->mSemantic = sprop->mSemantic;
                prop->mKey      = sprop->mKey;
                prop->mType     = sprop->mType;

                out->mNumProperties++;
            }
        }
    }
}

// ------------------------------------------------------------------------------------------------
template <typename Type>
inline
void CopyPtrArray (Type**& dest, const Type* const * src, ai_uint num) {
    if (!num) {
        dest = NULL;
        return;
    }
    dest = new Type*[num];
    for (ai_uint i = 0; i < num;++i) {
        SceneCombiner::Copy(&dest[i],src[i]);
    }
}

// ------------------------------------------------------------------------------------------------
template <typename Type>
inline
void GetArrayCopy(Type*& dest, ai_uint num ) {
    if ( !dest ) {
        return;
    }
    Type* old = dest;

    dest = new Type[num];
    ::memcpy(dest, old, sizeof(Type) * num);
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::CopySceneFlat(aiScene** _dest,const aiScene* src) {
    if ( nullptr == _dest || nullptr == src ) {
        return;
    }

    // reuse the old scene or allocate a new?
    if (*_dest) {
        (*_dest)->~aiScene();
        new (*_dest) aiScene();
    } else {
        *_dest = new aiScene();
    }

    ::memcpy(*_dest,src,sizeof(aiScene));
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::CopyScene(aiScene** _dest,const aiScene* src,bool allocate) {
    if ( nullptr == _dest || nullptr == src ) {
        return;
    }

    if (allocate) {
        *_dest = new aiScene();
    }
    aiScene* dest = *_dest;
    ai_assert(nullptr != dest);

    // copy metadata
    if ( nullptr != src->mMetaData ) {
        dest->mMetaData = new aiMetadata( *src->mMetaData );
    }

    // copy animations
    dest->mNumAnimations = src->mNumAnimations;
    CopyPtrArray(dest->mAnimations,src->mAnimations,
        dest->mNumAnimations);

    // copy textures
    dest->mNumTextures = src->mNumTextures;
    CopyPtrArray(dest->mTextures,src->mTextures,
        dest->mNumTextures);

    // copy materials
    dest->mNumMaterials = src->mNumMaterials;
    CopyPtrArray(dest->mMaterials,src->mMaterials,
        dest->mNumMaterials);

    // copy lights
    dest->mNumLights = src->mNumLights;
    CopyPtrArray(dest->mLights,src->mLights,
        dest->mNumLights);

    // copy cameras
    dest->mNumCameras = src->mNumCameras;
    CopyPtrArray(dest->mCameras,src->mCameras,
        dest->mNumCameras);

    // copy meshes
    dest->mNumMeshes = src->mNumMeshes;
    CopyPtrArray(dest->mMeshes,src->mMeshes,
        dest->mNumMeshes);

    // now - copy the root node of the scene (deep copy, too)
    Copy( &dest->mRootNode, src->mRootNode);

    // and keep the flags ...
    dest->mFlags = src->mFlags;

    // source private data might be NULL if the scene is user-allocated (i.e. for use with the export API)
    if (dest->mPrivate != NULL) {
        ScenePriv(dest)->mPPStepsApplied = ScenePriv(src) ? ScenePriv(src)->mPPStepsApplied : 0;
    }
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::Copy( aiMesh** _dest, const aiMesh* src ) {
    if ( nullptr == _dest || nullptr == src ) {
        return;
    }

    aiMesh* dest = *_dest = new aiMesh();

    // get a flat copy
    ::memcpy(dest,src,sizeof(aiMesh));

    // and reallocate all arrays
    GetArrayCopy( dest->mVertices,   dest->mNumVertices );
    GetArrayCopy( dest->mNormals ,   dest->mNumVertices );
    GetArrayCopy( dest->mTangents,   dest->mNumVertices );
    GetArrayCopy( dest->mBitangents, dest->mNumVertices );

    unsigned int n = 0;
    while (dest->HasTextureCoords(n))
        GetArrayCopy( dest->mTextureCoords[n++],   dest->mNumVertices );

    n = 0;
    while (dest->HasVertexColors(n))
        GetArrayCopy( dest->mColors[n++],   dest->mNumVertices );

    // make a deep copy of all bones
    CopyPtrArray(dest->mBones,dest->mBones,dest->mNumBones);

    // make a deep copy of all faces
    GetArrayCopy(dest->mFaces,dest->mNumFaces);
    for (unsigned int i = 0; i < dest->mNumFaces;++i) {
        aiFace& f = dest->mFaces[i];
        GetArrayCopy(f.mIndices,f.mNumIndices);
    }

    // make a deep copy of all blend shapes
    CopyPtrArray(dest->mAnimMeshes, dest->mAnimMeshes, dest->mNumAnimMeshes);
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::Copy(aiAnimMesh** _dest, const aiAnimMesh* src) {
    if (nullptr == _dest || nullptr == src) {
        return;
    }

    aiAnimMesh* dest = *_dest = new aiAnimMesh();

    // get a flat copy
    ::memcpy(dest, src, sizeof(aiAnimMesh));

    // and reallocate all arrays
    GetArrayCopy(dest->mVertices, dest->mNumVertices);
    GetArrayCopy(dest->mNormals, dest->mNumVertices);
    GetArrayCopy(dest->mTangents, dest->mNumVertices);
    GetArrayCopy(dest->mBitangents, dest->mNumVertices);

    unsigned int n = 0;
    while (dest->HasTextureCoords(n))
        GetArrayCopy(dest->mTextureCoords[n++], dest->mNumVertices);

    n = 0;
    while (dest->HasVertexColors(n))
        GetArrayCopy(dest->mColors[n++], dest->mNumVertices);
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::Copy (aiMaterial** _dest, const aiMaterial* src) {
    if ( nullptr == _dest || nullptr == src ) {
        return;
    }

    aiMaterial* dest = (aiMaterial*) ( *_dest = new aiMaterial() );

    dest->Clear();
    delete[] dest->mProperties;

    dest->mNumAllocated  =  src->mNumAllocated;
    dest->mNumProperties =  src->mNumProperties;
    dest->mProperties    =  new aiMaterialProperty* [dest->mNumAllocated];

    for (unsigned int i = 0; i < dest->mNumProperties;++i)
    {
        aiMaterialProperty* prop  = dest->mProperties[i] = new aiMaterialProperty();
        aiMaterialProperty* sprop = src->mProperties[i];

        prop->mDataLength = sprop->mDataLength;
        prop->mData = new char[prop->mDataLength];
        ::memcpy(prop->mData,sprop->mData,prop->mDataLength);

        prop->mIndex    = sprop->mIndex;
        prop->mSemantic = sprop->mSemantic;
        prop->mKey      = sprop->mKey;
        prop->mType     = sprop->mType;
    }
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::Copy(aiTexture** _dest, const aiTexture* src) {
    if ( nullptr == _dest || nullptr == src ) {
        return;
    }

    aiTexture* dest = *_dest = new aiTexture();

    // get a flat copy
    ::memcpy(dest,src,sizeof(aiTexture));

    // and reallocate all arrays. We must do it manually here
    const char* old = (const char*)dest->pcData;
    if (old)
    {
        unsigned int cpy;
        if (!dest->mHeight)cpy = dest->mWidth;
        else cpy = dest->mHeight * dest->mWidth * sizeof(aiTexel);

        if (!cpy)
        {
            dest->pcData = NULL;
            return;
        }
        // the cast is legal, the aiTexel c'tor does nothing important
        dest->pcData = (aiTexel*) new char[cpy];
        ::memcpy(dest->pcData, old, cpy);
    }
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::Copy( aiAnimation** _dest, const aiAnimation* src ) {
    if ( nullptr == _dest || nullptr == src ) {
        return;
    }

    aiAnimation* dest = *_dest = new aiAnimation();

    // get a flat copy
    ::memcpy(dest,src,sizeof(aiAnimation));

    // and reallocate all arrays
    CopyPtrArray( dest->mChannels, src->mChannels, dest->mNumChannels );
    CopyPtrArray( dest->mMorphMeshChannels, src->mMorphMeshChannels, dest->mNumMorphMeshChannels );
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::Copy(aiNodeAnim** _dest, const aiNodeAnim* src) {
    if ( nullptr == _dest || nullptr == src ) {
        return;
    }

    aiNodeAnim* dest = *_dest = new aiNodeAnim();

    // get a flat copy
    ::memcpy(dest,src,sizeof(aiNodeAnim));

    // and reallocate all arrays
    GetArrayCopy( dest->mPositionKeys, dest->mNumPositionKeys );
    GetArrayCopy( dest->mScalingKeys,  dest->mNumScalingKeys );
    GetArrayCopy( dest->mRotationKeys, dest->mNumRotationKeys );
}

void SceneCombiner::Copy(aiMeshMorphAnim** _dest, const aiMeshMorphAnim* src) {
    if ( nullptr == _dest || nullptr == src ) {
        return;
    }

    aiMeshMorphAnim* dest = *_dest = new aiMeshMorphAnim();

    // get a flat copy
    ::memcpy(dest,src,sizeof(aiMeshMorphAnim));

    // and reallocate all arrays
    GetArrayCopy( dest->mKeys, dest->mNumKeys );
    for (ai_uint i = 0; i < dest->mNumKeys;++i) {
        dest->mKeys[i].mValues = new unsigned int[dest->mKeys[i].mNumValuesAndWeights];
        dest->mKeys[i].mWeights = new double[dest->mKeys[i].mNumValuesAndWeights];
        ::memcpy(dest->mKeys[i].mValues, src->mKeys[i].mValues, dest->mKeys[i].mNumValuesAndWeights * sizeof(unsigned int));
        ::memcpy(dest->mKeys[i].mWeights, src->mKeys[i].mWeights, dest->mKeys[i].mNumValuesAndWeights * sizeof(double));
    }
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::Copy( aiCamera** _dest,const  aiCamera* src) {
    if ( nullptr == _dest || nullptr == src ) {
        return;
    }

    aiCamera* dest = *_dest = new aiCamera();

    // get a flat copy, that's already OK
    ::memcpy(dest,src,sizeof(aiCamera));
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::Copy(aiLight** _dest, const aiLight* src) {
    if ( nullptr == _dest || nullptr == src ) {
        return;
    }

    aiLight* dest = *_dest = new aiLight();

    // get a flat copy, that's already OK
    ::memcpy(dest,src,sizeof(aiLight));
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::Copy(aiBone** _dest, const aiBone* src) {
    if ( nullptr == _dest || nullptr == src ) {
        return;
    }

    aiBone* dest = *_dest = new aiBone();

    // get a flat copy
    ::memcpy(dest,src,sizeof(aiBone));

    // and reallocate all arrays
    GetArrayCopy( dest->mWeights, dest->mNumWeights );
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::Copy     (aiNode** _dest, const aiNode* src)
{
    ai_assert(NULL != _dest && NULL != src);

    aiNode* dest = *_dest = new aiNode();

    // get a flat copy
    ::memcpy(dest,src,sizeof(aiNode));

    if (src->mMetaData) {
        Copy(&dest->mMetaData, src->mMetaData);
    }

    // and reallocate all arrays
    GetArrayCopy( dest->mMeshes, dest->mNumMeshes );
    CopyPtrArray( dest->mChildren, src->mChildren,dest->mNumChildren);

	// need to set the mParent fields to the created aiNode.
	for( unsigned int i = 0; i < dest->mNumChildren; i ++ ) {
		dest->mChildren[i]->mParent = dest;
	}
}

// ------------------------------------------------------------------------------------------------
void SceneCombiner::Copy(aiMetadata** _dest, const aiMetadata* src) {
    if ( nullptr == _dest || nullptr == src ) {
        return;
    }

    if ( 0 == src->mNumProperties ) {
        return;
    }

    aiMetadata* dest = *_dest = aiMetadata::Alloc( src->mNumProperties );
    std::copy(src->mKeys, src->mKeys + src->mNumProperties, dest->mKeys);

    dest->mValues = new aiMetadataEntry[src->mNumProperties];
    for (unsigned int i = 0; i < src->mNumProperties; ++i) {
        aiMetadataEntry& in = src->mValues[i];
        aiMetadataEntry& out = dest->mValues[i];
        out.mType = in.mType;
        switch (dest->mValues[i].mType) {
            case AI_BOOL:
                out.mData = new bool(*static_cast<bool*>(in.mData));
                break;
            case AI_INT32:
                out.mData = new int32_t(*static_cast<int32_t*>(in.mData));
                break;
            case AI_UINT64:
                out.mData = new uint64_t(*static_cast<uint64_t*>(in.mData));
                break;
            case AI_FLOAT:
                out.mData = new float(*static_cast<float*>(in.mData));
                break;
            case AI_DOUBLE:
                out.mData = new double(*static_cast<double*>(in.mData));
                break;
            case AI_AISTRING:
                out.mData = new aiString(*static_cast<aiString*>(in.mData));
                break;
            case AI_AIVECTOR3D:
                out.mData = new aiVector3D(*static_cast<aiVector3D*>(in.mData));
                break;
            default:
                ai_assert(false);
                break;
        }
    }
}

} // Namespace Assimp