-
Notifications
You must be signed in to change notification settings - Fork 0
/
fbxloader.cpp
1511 lines (1313 loc) · 65.4 KB
/
fbxloader.cpp
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
#include "fbxloader.h"
#include <glew.h>
#include <algorithm>
using namespace std;
using namespace tinyobj;
#ifdef IOS_REF
#undef IOS_REF
#define IOS_REF (*(pManager->GetIOSettings()))
#endif
typedef struct
{
std::vector<int> vertexControlIndices; // translate gl_VertexID to control point index
std::vector<int> vertexJointIndices; // 4 joints for one vertex
std::vector<float> vertexJointWeights; // 4 joint weights for one vertex
std::vector<std::vector<float> > jointTransformMatrices; // 16 float column major matrix for each joint for each frame
int num_frames;
} animation_t;
vector<shape_t> gShapes;
vector<material_t> gMaterials;
vector<animation_t> gAnimations;
vector<shape_t> gShapeAnim;
bool LoadScene(FbxManager* pManager, FbxScene* pScene, FbxArray<FbxString*> pAnimStackNameArray, const char* pFilename);
void LoadCacheRecursive(FbxScene* pScene, FbxNode * pNode, FbxAMatrix& pParentGlobalPosition, FbxTime& pTime);
void LoadAnimationRecursive(FbxScene* pScene, FbxNode * pNode, FbxAMatrix& pParentGlobalPosition, FbxTime& pTime);
void InitializeSdkObjects(FbxManager*& pManager, FbxScene*& pScene);
void DestroySdkObjects(FbxManager* pManager, bool pExitStatus);
void DisplayMetaData(FbxScene* pScene);
void DisplayHierarchy(FbxScene* pScene);
void DisplayHierarchy(FbxNode* pNode, int pDepth);
FbxAMatrix GetGlobalPosition(FbxNode* pNode, const FbxTime& pTime, FbxPose* pPose = NULL, FbxAMatrix* pParentGlobalPosition = NULL);
FbxAMatrix GetPoseMatrix(FbxPose* pPose, int pNodeIndex);
FbxAMatrix GetGeometry(FbxNode* pNode);
void MatrixScale(FbxAMatrix& pMatrix, double pValue);
void MatrixAddToDiagonal(FbxAMatrix& pMatrix, double pValue);
void MatrixAdd(FbxAMatrix& pDstMatrix, FbxAMatrix& pSrcMatrix);
void ComputeSkinDeformation(FbxAMatrix& pGlobalPosition, FbxMesh* pMesh, FbxTime& pTime, FbxVector4* pVertexArray, FbxPose* pPose);
void ComputeShapeDeformation(FbxMesh* pMesh, FbxTime& pTime, FbxAnimLayer * pAnimLayer, FbxVector4* pVertexArray);
void ComputeClusterDeformation(FbxAMatrix& pGlobalPosition, FbxMesh* pMesh, FbxCluster* pCluster, FbxAMatrix& pVertexTransformMatrix, FbxTime pTime, FbxPose* pPose);
void GetFbxAnimation(fbx_handles &handles, std::vector<tinyobj::shape_t> &shapes, float frame)
{
if (handles.lScene != 0)
{
frame = min(max(frame, 0.0f), 1.0f);
FbxTimeSpan lTimeLineTimeSpan;
handles.lScene->GetGlobalSettings().GetTimelineDefaultTimeSpan(lTimeLineTimeSpan);
FbxTime lTime = lTimeLineTimeSpan.GetStart() + ((lTimeLineTimeSpan.GetStop() - lTimeLineTimeSpan.GetStart()) / 10000) * (10000 * frame);
gShapeAnim.clear();
FbxAMatrix lDummyGlobalPosition;
LoadAnimationRecursive(handles.lScene, handles.lScene->GetRootNode(), lDummyGlobalPosition, lTime);
shapes = gShapeAnim;
}
}
bool LoadFbx(fbx_handles &handles, vector<shape_t> &shapes, vector<material_t> &materials, std::string err, const char* pFileName)
{
gShapes.clear();
gMaterials.clear();
gAnimations.clear();
bool lResult;
InitializeSdkObjects(handles.lSdkManager, handles.lScene);
lResult = LoadScene(handles.lSdkManager, handles.lScene, handles.lAnimStackNameArray, pFileName);
if (lResult == false)
{
FBXSDK_printf("\n\nAn error occurred while loading the scene...");
DestroySdkObjects(handles.lSdkManager, lResult);
return false;
}
else
{
// Display the scene.
// DisplayMetaData(handles.lScene);
// FBXSDK_printf("\n\n---------\nHierarchy\n---------\n\n");
// DisplayHierarchy(handles.lScene);
// Load data.
FbxAMatrix lDummyGlobalPosition;
FbxTimeSpan lTimeLineTimeSpan;
handles.lScene->GetGlobalSettings().GetTimelineDefaultTimeSpan(lTimeLineTimeSpan);
FbxTime lTime = lTimeLineTimeSpan.GetStart();
LoadCacheRecursive(handles.lScene, handles.lScene->GetRootNode(), lDummyGlobalPosition, lTime);
}
shapes = gShapes;
materials = gMaterials;
return true;
}
void ReleaseFbx(fbx_handles &handles)
{
if (handles.lScene)
{
bool lResult;
DestroySdkObjects(handles.lSdkManager, lResult);
FbxArrayDelete(handles.lAnimStackNameArray);
handles.lSdkManager = 0;
handles.lScene = 0;
}
}
void DisplayHierarchy(FbxScene* pScene)
{
int i;
FbxNode* lRootNode = pScene->GetRootNode();
for (i = 0; i < lRootNode->GetChildCount(); i++)
{
DisplayHierarchy(lRootNode->GetChild(i), 0);
}
}
void DisplayHierarchy(FbxNode* pNode, int pDepth)
{
FbxString lString;
int i;
for (i = 0; i < pDepth; i++)
{
lString += " ";
}
lString += pNode->GetName();
lString += "\n";
FBXSDK_printf(lString.Buffer());
for (i = 0; i < pNode->GetChildCount(); i++)
{
DisplayHierarchy(pNode->GetChild(i), pDepth + 1);
}
}
void InitializeSdkObjects(FbxManager*& pManager, FbxScene*& pScene)
{
//The first thing to do is to create the FBX Manager which is the object allocator for almost all the classes in the SDK
pManager = FbxManager::Create();
if (!pManager)
{
FBXSDK_printf("Error: Unable to create FBX Manager!\n");
exit(1);
}
else FBXSDK_printf("Autodesk FBX SDK version %s\n", pManager->GetVersion());
//Create an IOSettings object. This object holds all import/export settings.
FbxIOSettings* ios = FbxIOSettings::Create(pManager, IOSROOT);
pManager->SetIOSettings(ios);
//Load plugins from the executable directory (optional)
FbxString lPath = FbxGetApplicationDirectory();
pManager->LoadPluginsDirectory(lPath.Buffer());
//Create an FBX scene. This object holds most objects imported/exported from/to files.
pScene = FbxScene::Create(pManager, "My Scene");
if (!pScene)
{
FBXSDK_printf("Error: Unable to create FBX scene!\n");
exit(1);
}
}
bool LoadScene(FbxManager* pManager, FbxScene* pScene, FbxArray<FbxString*> pAnimStackNameArray, const char* pFilename)
{
int lFileMajor, lFileMinor, lFileRevision;
int lSDKMajor, lSDKMinor, lSDKRevision;
int i, lAnimStackCount;
bool lStatus;
char lPassword[1024];
// Get the file version number generate by the FBX SDK.
FbxManager::GetFileFormatVersion(lSDKMajor, lSDKMinor, lSDKRevision);
// Create an importer.
FbxImporter* lImporter = FbxImporter::Create(pManager, "");
// Initialize the importer by providing a filename.
const bool lImportStatus = lImporter->Initialize(pFilename, -1, pManager->GetIOSettings());
lImporter->GetFileVersion(lFileMajor, lFileMinor, lFileRevision);
if (!lImportStatus)
{
FbxString error = lImporter->GetStatus().GetErrorString();
FBXSDK_printf("Call to FbxImporter::Initialize() failed.\n");
FBXSDK_printf("Error returned: %s\n\n", error.Buffer());
if (lImporter->GetStatus().GetCode() == FbxStatus::eInvalidFileVersion)
{
FBXSDK_printf("FBX file format version for this FBX SDK is %d.%d.%d\n", lSDKMajor, lSDKMinor, lSDKRevision);
FBXSDK_printf("FBX file format version for file '%s' is %d.%d.%d\n\n", pFilename, lFileMajor, lFileMinor, lFileRevision);
}
return false;
}
FBXSDK_printf("FBX file format version for this FBX SDK is %d.%d.%d\n", lSDKMajor, lSDKMinor, lSDKRevision);
if (lImporter->IsFBX())
{
FBXSDK_printf("FBX file format version for file '%s' is %d.%d.%d\n\n", pFilename, lFileMajor, lFileMinor, lFileRevision);
// From this point, it is possible to access animation stack information without
// the expense of loading the entire file.
FBXSDK_printf("Animation Stack Information\n");
lAnimStackCount = lImporter->GetAnimStackCount();
FBXSDK_printf(" Number of Animation Stacks: %d\n", lAnimStackCount);
FBXSDK_printf(" Current Animation Stack: \"%s\"\n", lImporter->GetActiveAnimStackName().Buffer());
FBXSDK_printf("\n");
for (i = 0; i < lAnimStackCount; i++)
{
FbxTakeInfo* lTakeInfo = lImporter->GetTakeInfo(i);
FBXSDK_printf(" Animation Stack %d\n", i);
FBXSDK_printf(" Name: \"%s\"\n", lTakeInfo->mName.Buffer());
FBXSDK_printf(" Description: \"%s\"\n", lTakeInfo->mDescription.Buffer());
// Change the value of the import name if the animation stack should be imported
// under a different name.
FBXSDK_printf(" Import Name: \"%s\"\n", lTakeInfo->mImportName.Buffer());
// Set the value of the import state to false if the animation stack should be not
// be imported.
FBXSDK_printf(" Import State: %s\n", lTakeInfo->mSelect ? "true" : "false");
FBXSDK_printf("\n");
}
}
// Import the scene.
lStatus = lImporter->Import(pScene);
if (lStatus == false && lImporter->GetStatus().GetCode() == FbxStatus::ePasswordError)
{
FBXSDK_printf("Please enter password: ");
lPassword[0] = '\0';
FBXSDK_CRT_SECURE_NO_WARNING_BEGIN
scanf("%s", lPassword);
FBXSDK_CRT_SECURE_NO_WARNING_END
FbxString lString(lPassword);
IOS_REF.SetStringProp(IMP_FBX_PASSWORD, lString);
IOS_REF.SetBoolProp(IMP_FBX_PASSWORD_ENABLE, true);
lStatus = lImporter->Import(pScene);
if (lStatus == false && lImporter->GetStatus().GetCode() == FbxStatus::ePasswordError)
{
FBXSDK_printf("\nPassword is wrong, import aborted.\n");
}
}
if (lStatus)
{
// Convert Axis System to up = Y Axis, Right-Handed Coordinate (OpenGL Style)
FbxAxisSystem SceneAxisSystem = pScene->GetGlobalSettings().GetAxisSystem();
FbxAxisSystem OurAxisSystem(FbxAxisSystem::eYAxis, FbxAxisSystem::eParityOdd, FbxAxisSystem::eRightHanded);
if (SceneAxisSystem != OurAxisSystem)
{
OurAxisSystem.ConvertScene(pScene);
}
// Convert Unit System to what is used in this example, if needed
FbxSystemUnit SceneSystemUnit = pScene->GetGlobalSettings().GetSystemUnit();
if (SceneSystemUnit.GetScaleFactor() != 100.0)
{
//The unit in this example is centimeter.
FbxSystemUnit::m.ConvertScene(pScene);
}
// Get the list of all the animation stack.
pScene->FillAnimStackNameArray(pAnimStackNameArray);
// Convert mesh, NURBS and patch into triangle mesh
FbxGeometryConverter lGeomConverter(pManager);
lGeomConverter.Triangulate(pScene, true);
}
// Destroy the importer.
lImporter->Destroy();
return lStatus;
}
void DestroySdkObjects(FbxManager* pManager, bool pExitStatus)
{
//Delete the FBX Manager. All the objects that have been allocated using the FBX Manager and that haven't been explicitly destroyed are also automatically destroyed.
if (pManager) pManager->Destroy();
if (pExitStatus) FBXSDK_printf("Program Success!\n");
}
void DisplayMetaData(FbxScene* pScene)
{
FbxDocumentInfo* sceneInfo = pScene->GetSceneInfo();
if (sceneInfo)
{
FBXSDK_printf("\n\n--------------------\nMeta-Data\n--------------------\n\n");
FBXSDK_printf(" Title: %s\n", sceneInfo->mTitle.Buffer());
FBXSDK_printf(" Subject: %s\n", sceneInfo->mSubject.Buffer());
FBXSDK_printf(" Author: %s\n", sceneInfo->mAuthor.Buffer());
FBXSDK_printf(" Keywords: %s\n", sceneInfo->mKeywords.Buffer());
FBXSDK_printf(" Revision: %s\n", sceneInfo->mRevision.Buffer());
FBXSDK_printf(" Comment: %s\n", sceneInfo->mComment.Buffer());
FbxThumbnail* thumbnail = sceneInfo->GetSceneThumbnail();
if (thumbnail)
{
FBXSDK_printf(" Thumbnail:\n");
switch (thumbnail->GetDataFormat())
{
case FbxThumbnail::eRGB_24:
FBXSDK_printf(" Format: RGB\n");
break;
case FbxThumbnail::eRGBA_32:
FBXSDK_printf(" Format: RGBA\n");
break;
}
switch (thumbnail->GetSize())
{
default:
break;
case FbxThumbnail::eNotSet:
FBXSDK_printf(" Size: no dimensions specified (%ld bytes)\n", thumbnail->GetSizeInBytes());
break;
case FbxThumbnail::e64x64:
FBXSDK_printf(" Size: 64 x 64 pixels (%ld bytes)\n", thumbnail->GetSizeInBytes());
break;
case FbxThumbnail::e128x128:
FBXSDK_printf(" Size: 128 x 128 pixels (%ld bytes)\n", thumbnail->GetSizeInBytes());
}
}
}
}
// Get specific property value and connected texture if any.
// Value = Property value * Factor property value (if no factor property, multiply by 1).
FbxDouble3 GetMaterialProperty(const FbxSurfaceMaterial * pMaterial,
const char * pPropertyName,
const char * pFactorPropertyName,
string & pTextureName)
{
FbxDouble3 lResult(0, 0, 0);
const FbxProperty lProperty = pMaterial->FindProperty(pPropertyName);
const FbxProperty lFactorProperty = pMaterial->FindProperty(pFactorPropertyName);
if (lProperty.IsValid() && lFactorProperty.IsValid())
{
lResult = lProperty.Get<FbxDouble3>();
double lFactor = lFactorProperty.Get<FbxDouble>();
if (lFactor != 1)
{
lResult[0] *= lFactor;
lResult[1] *= lFactor;
lResult[2] *= lFactor;
}
}
if (lProperty.IsValid())
{
const int lTextureCount = lProperty.GetSrcObjectCount<FbxFileTexture>();
if (lTextureCount)
{
const FbxFileTexture* lTexture = lProperty.GetSrcObject<FbxFileTexture>();
if (lTexture)
{
pTextureName = lTexture->GetFileName();
}
}
}
return lResult;
}
void LoadAnimationRecursive(FbxScene* pScene, FbxNode *pNode, FbxAMatrix& pParentGlobalPosition, FbxTime& pTime)
{
FbxAMatrix lGlobalPosition = GetGlobalPosition(pNode, pTime, 0, &pParentGlobalPosition);
const int lMaterialCount = pNode->GetMaterialCount();
FbxNodeAttribute* lNodeAttribute = pNode->GetNodeAttribute();
if (lNodeAttribute)
{
// Bake mesh as VBO(vertex buffer object) into GPU.
if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eMesh)
{
FbxMesh * lMesh = pNode->GetMesh();
if (lMesh)
{
const int lPolygonCount = lMesh->GetPolygonCount();
bool lAllByControlPoint = true; // => true: glDrawElements / false: glDrawArrays
// Count the polygon count of each material
FbxLayerElementArrayTemplate<int>* lMaterialIndice = NULL;
FbxGeometryElement::EMappingMode lMaterialMappingMode = FbxGeometryElement::eNone;
if (lMesh->GetElementMaterial())
{
lMaterialIndice = &lMesh->GetElementMaterial()->GetIndexArray();
lMaterialMappingMode = lMesh->GetElementMaterial()->GetMappingMode();
}
// Congregate all the data of a mesh to be cached in VBOs.
// If normal or UV is by polygon vertex, record all vertex attributes by polygon vertex.
bool lHasNormal = lMesh->GetElementNormalCount() > 0;
bool lHasUV = lMesh->GetElementUVCount() > 0;
FbxGeometryElement::EMappingMode lNormalMappingMode = FbxGeometryElement::eNone;
FbxGeometryElement::EMappingMode lUVMappingMode = FbxGeometryElement::eNone;
if (lHasNormal)
{
lNormalMappingMode = lMesh->GetElementNormal(0)->GetMappingMode();
if (lNormalMappingMode == FbxGeometryElement::eNone)
{
lHasNormal = false;
}
if (lHasNormal && lNormalMappingMode != FbxGeometryElement::eByControlPoint)
{
lAllByControlPoint = false;
}
}
if (lHasUV)
{
lUVMappingMode = lMesh->GetElementUV(0)->GetMappingMode();
if (lUVMappingMode == FbxGeometryElement::eNone)
{
lHasUV = false;
}
if (lHasUV && lUVMappingMode != FbxGeometryElement::eByControlPoint)
{
lAllByControlPoint = false;
}
}
// Allocate the array memory, by control point or by polygon vertex.
int lPolygonVertexCount = lMesh->GetControlPointsCount();
if (!lAllByControlPoint)
{
lPolygonVertexCount = lPolygonCount * 3;
}
vector<float> lVertices;
lVertices.resize(lPolygonVertexCount * 3);
vector<unsigned int> lIndices;
lIndices.resize(lPolygonCount * 3);
// Populate the array with vertex attribute, if by control point.
FbxVector4 * lControlPoints = lMesh->GetControlPoints();
/////////////////////////
if((FbxSkin *)lMesh->GetDeformer(0, FbxDeformer::eSkin) != 0)
{
lControlPoints = new FbxVector4[lMesh->GetControlPointsCount()];
memcpy(lControlPoints, lMesh->GetControlPoints(), lMesh->GetControlPointsCount() * sizeof(FbxVector4));
// select the base layer from the animation stack
FbxAnimStack * lCurrentAnimationStack = pScene->GetSrcObject<FbxAnimStack>(0);
// we assume that the first animation layer connected to the animation stack is the base layer
// (this is the assumption made in the FBXSDK)
FbxAnimLayer *mCurrentAnimLayer = lCurrentAnimationStack->GetMember<FbxAnimLayer>();
// ComputeShapeDeformation(lMesh, pTime, mCurrentAnimLayer, lControlPoints);
FbxAMatrix lGeometryOffset = GetGeometry(pNode);
FbxAMatrix lGlobalOffPosition = lGlobalPosition * lGeometryOffset;
ComputeSkinDeformation(lGlobalOffPosition, lMesh, pTime, lControlPoints, NULL);
}
/////////////////////////
vector<int> vertexControlIndices;
FbxVector4 lCurrentVertex;
FbxVector4 lCurrentNormal;
FbxVector2 lCurrentUV;
if (lAllByControlPoint)
{
for (int lIndex = 0; lIndex < lPolygonVertexCount; ++lIndex)
{
// Save the vertex position.
lCurrentVertex = lControlPoints[lIndex];
lVertices[lIndex * 3] = static_cast<float>(lCurrentVertex[0]);
lVertices[lIndex * 3 + 1] = static_cast<float>(lCurrentVertex[1]);
lVertices[lIndex * 3 + 2] = static_cast<float>(lCurrentVertex[2]);
vertexControlIndices.push_back(lIndex);
}
}
int lVertexCount = 0;
for (int lPolygonIndex = 0; lPolygonIndex < lPolygonCount; ++lPolygonIndex)
{
for (int lVerticeIndex = 0; lVerticeIndex < 3; ++lVerticeIndex)
{
const int lControlPointIndex = lMesh->GetPolygonVertex(lPolygonIndex, lVerticeIndex);
if (lAllByControlPoint)
{
lIndices[lPolygonIndex * 3 + lVerticeIndex] = static_cast<unsigned int>(lControlPointIndex);
}
// Populate the array with vertex attribute, if by polygon vertex.
else
{
lIndices[lPolygonIndex * 3 + lVerticeIndex] = static_cast<unsigned int>(lVertexCount);
lCurrentVertex = lControlPoints[lControlPointIndex];
lVertices[lVertexCount * 3] = static_cast<float>(lCurrentVertex[0]);
lVertices[lVertexCount * 3 + 1] = static_cast<float>(lCurrentVertex[1]);
lVertices[lVertexCount * 3 + 2] = static_cast<float>(lCurrentVertex[2]);
vertexControlIndices.push_back(lControlPointIndex);
}
++lVertexCount;
}
}
shape_t shape;
shape.mesh.positions = lVertices;
gShapeAnim.push_back(shape);
if ((FbxSkin *)lMesh->GetDeformer(0, FbxDeformer::eSkin) != 0)
{
delete [] lControlPoints;
}
}
}
}
const int lChildCount = pNode->GetChildCount();
for (int lChildIndex = 0; lChildIndex < lChildCount; ++lChildIndex)
{
LoadAnimationRecursive(pScene, pNode->GetChild(lChildIndex), lGlobalPosition, pTime);
}
}
void LoadMaterials(FbxNode *pNode)
{
// Bake material and hook as user data.
int lMaterialIndexBase = gMaterials.size();
const int lMaterialCount = pNode->GetMaterialCount();
for (int lMaterialIndex = 0; lMaterialIndex < lMaterialCount; ++lMaterialIndex)
{
FbxSurfaceMaterial * lMaterial = pNode->GetMaterial(lMaterialIndex);
material_t material;
if (lMaterial)
{
string lTextureNameTemp;
const FbxDouble3 lAmbient = GetMaterialProperty(lMaterial,
FbxSurfaceMaterial::sAmbient, FbxSurfaceMaterial::sAmbientFactor, lTextureNameTemp);
material.ambient[0] = static_cast<GLfloat>(lAmbient[0]);
material.ambient[1] = static_cast<GLfloat>(lAmbient[1]);
material.ambient[2] = static_cast<GLfloat>(lAmbient[2]);
material.ambient_texname = lTextureNameTemp;
const FbxDouble3 lDiffuse = GetMaterialProperty(lMaterial,
FbxSurfaceMaterial::sDiffuse, FbxSurfaceMaterial::sDiffuseFactor, lTextureNameTemp);
material.diffuse[0] = static_cast<GLfloat>(lDiffuse[0]);
material.diffuse[1] = static_cast<GLfloat>(lDiffuse[1]);
material.diffuse[2] = static_cast<GLfloat>(lDiffuse[2]);
material.diffuse_texname = lTextureNameTemp;
const FbxDouble3 lSpecular = GetMaterialProperty(lMaterial,
FbxSurfaceMaterial::sSpecular, FbxSurfaceMaterial::sSpecularFactor, lTextureNameTemp);
material.specular[0] = static_cast<GLfloat>(lSpecular[0]);
material.specular[1] = static_cast<GLfloat>(lSpecular[1]);
material.specular[2] = static_cast<GLfloat>(lSpecular[2]);
material.specular_texname = lTextureNameTemp;
FbxProperty lShininessProperty = lMaterial->FindProperty(FbxSurfaceMaterial::sShininess);
if (lShininessProperty.IsValid())
{
double lShininess = lShininessProperty.Get<FbxDouble>();
material.shininess = static_cast<GLfloat>(lShininess);
}
}
gMaterials.push_back(material);
}
}
void LoadCacheRecursive(FbxScene* pScene, FbxNode * pNode, FbxAMatrix& pParentGlobalPosition, FbxTime& pTime)
{
FbxAMatrix lGlobalPosition = GetGlobalPosition(pNode, pTime, 0, &pParentGlobalPosition);
// Bake material and hook as user data.
int lMaterialIndexBase = gMaterials.size();
LoadMaterials(pNode);
FbxNodeAttribute* lNodeAttribute = pNode->GetNodeAttribute();
if (lNodeAttribute)
{
// Bake mesh as VBO(vertex buffer object) into GPU.
if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eMesh)
{
FbxMesh * lMesh = pNode->GetMesh();
if (lMesh)
{
const int lPolygonCount = lMesh->GetPolygonCount();
bool lAllByControlPoint = true; // => true: glDrawElements / false: glDrawArrays
// Count the polygon count of each material
FbxLayerElementArrayTemplate<int>* lMaterialIndice = NULL;
FbxGeometryElement::EMappingMode lMaterialMappingMode = FbxGeometryElement::eNone;
if (lMesh->GetElementMaterial())
{
lMaterialIndice = &lMesh->GetElementMaterial()->GetIndexArray();
lMaterialMappingMode = lMesh->GetElementMaterial()->GetMappingMode();
}
// Congregate all the data of a mesh to be cached in VBOs.
// If normal or UV is by polygon vertex, record all vertex attributes by polygon vertex.
bool lHasNormal = lMesh->GetElementNormalCount() > 0;
bool lHasUV = lMesh->GetElementUVCount() > 0;
FbxGeometryElement::EMappingMode lNormalMappingMode = FbxGeometryElement::eNone;
FbxGeometryElement::EMappingMode lUVMappingMode = FbxGeometryElement::eNone;
if (lHasNormal)
{
lNormalMappingMode = lMesh->GetElementNormal(0)->GetMappingMode();
if (lNormalMappingMode == FbxGeometryElement::eNone)
{
lHasNormal = false;
}
if (lHasNormal && lNormalMappingMode != FbxGeometryElement::eByControlPoint)
{
lAllByControlPoint = false;
}
}
if (lHasUV)
{
lUVMappingMode = lMesh->GetElementUV(0)->GetMappingMode();
if (lUVMappingMode == FbxGeometryElement::eNone)
{
lHasUV = false;
}
if (lHasUV && lUVMappingMode != FbxGeometryElement::eByControlPoint)
{
lAllByControlPoint = false;
}
}
// Allocate the array memory, by control point or by polygon vertex.
int lPolygonVertexCount = lMesh->GetControlPointsCount();
if (!lAllByControlPoint)
{
lPolygonVertexCount = lPolygonCount * 3;
}
printf("All By Control Point: %s\n", lAllByControlPoint ? "Yes" : "No");
vector<float> lVertices;
lVertices.resize(lPolygonVertexCount * 3);
vector<unsigned int> lIndices;
lIndices.resize(lPolygonCount * 3);
vector<float> lNormals;
if (lHasNormal)
{
lNormals.resize(lPolygonVertexCount * 3);
}
vector<float> lUVs;
FbxStringList lUVNames;
lMesh->GetUVSetNames(lUVNames);
const char * lUVName = NULL;
if (lHasUV && lUVNames.GetCount())
{
lUVs.resize(lPolygonVertexCount * 2);
lUVName = lUVNames[0];
}
// Populate the array with vertex attribute, if by control point.
FbxVector4 * lControlPoints = lMesh->GetControlPoints();
/////////////////////////
if ((FbxSkin *)lMesh->GetDeformer(0, FbxDeformer::eSkin) != 0)
{
lControlPoints = new FbxVector4[lMesh->GetControlPointsCount()];
memcpy(lControlPoints, lMesh->GetControlPoints(), lMesh->GetControlPointsCount() * sizeof(FbxVector4));
FbxTimeSpan lTimeLineTimeSpan;
pScene->GetGlobalSettings().GetTimelineDefaultTimeSpan(lTimeLineTimeSpan);
FbxTime pTime = lTimeLineTimeSpan.GetStart();
// select the base layer from the animation stack
FbxAnimStack * lCurrentAnimationStack = pScene->GetSrcObject<FbxAnimStack>(0);
// we assume that the first animation layer connected to the animation stack is the base layer
// (this is the assumption made in the FBXSDK)
FbxAnimLayer *mCurrentAnimLayer = lCurrentAnimationStack->GetMember<FbxAnimLayer>();
// ComputeShapeDeformation(lMesh, pTime, mCurrentAnimLayer, lControlPoints);
FbxAMatrix lGeometryOffset = GetGeometry(pNode);
FbxAMatrix lGlobalOffPosition = lGlobalPosition * lGeometryOffset;
ComputeSkinDeformation(lGlobalOffPosition, lMesh, pTime, lControlPoints, NULL);
}
/////////////////////////
vector<int> lMaterialIndices;
lMaterialIndices.resize(lPolygonVertexCount);
vector<int> vertexControlIndices;
FbxVector4 lCurrentVertex;
FbxVector4 lCurrentNormal;
FbxVector2 lCurrentUV;
if (lAllByControlPoint)
{
const FbxGeometryElementNormal * lNormalElement = NULL;
const FbxGeometryElementUV * lUVElement = NULL;
if (lHasNormal)
{
lNormalElement = lMesh->GetElementNormal(0);
}
if (lHasUV)
{
lUVElement = lMesh->GetElementUV(0);
}
for (int lIndex = 0; lIndex < lPolygonVertexCount; ++lIndex)
{
// The material for current face.
int lMaterialIndex = 0;
if (lMaterialIndice && lMaterialMappingMode == FbxGeometryElement::eByPolygon)
{
lMaterialIndex = lMaterialIndice->GetAt(lIndex);
}
// Save the vertex position.
lCurrentVertex = lControlPoints[lIndex];
lVertices[lIndex * 3] = static_cast<float>(lCurrentVertex[0]);
lVertices[lIndex * 3 + 1] = static_cast<float>(lCurrentVertex[1]);
lVertices[lIndex * 3 + 2] = static_cast<float>(lCurrentVertex[2]);
lMaterialIndices[lIndex] = lMaterialIndex + lMaterialIndexBase;
vertexControlIndices.push_back(lIndex);
// Save the normal.
if (lHasNormal)
{
int lNormalIndex = lIndex;
if (lNormalElement->GetReferenceMode() == FbxLayerElement::eIndexToDirect)
{
lNormalIndex = lNormalElement->GetIndexArray().GetAt(lIndex);
}
lCurrentNormal = lNormalElement->GetDirectArray().GetAt(lNormalIndex);
lNormals[lIndex * 3] = static_cast<float>(lCurrentNormal[0]);
lNormals[lIndex * 3 + 1] = static_cast<float>(lCurrentNormal[1]);
lNormals[lIndex * 3 + 2] = static_cast<float>(lCurrentNormal[2]);
}
// Save the UV.
if (lHasUV)
{
int lUVIndex = lIndex;
if (lUVElement->GetReferenceMode() == FbxLayerElement::eIndexToDirect)
{
lUVIndex = lUVElement->GetIndexArray().GetAt(lIndex);
}
lCurrentUV = lUVElement->GetDirectArray().GetAt(lUVIndex);
lUVs[lIndex * 2] = static_cast<float>(lCurrentUV[0]);
lUVs[lIndex * 2 + 1] = static_cast<float>(lCurrentUV[1]);
}
}
}
int lVertexCount = 0;
for (int lPolygonIndex = 0; lPolygonIndex < lPolygonCount; ++lPolygonIndex)
{
// The material for current face.
int lMaterialIndex = 0;
if (lMaterialIndice && lMaterialMappingMode == FbxGeometryElement::eByPolygon)
{
lMaterialIndex = lMaterialIndice->GetAt(lPolygonIndex);
}
if (lMaterialIndex != 0)
{
int i = 0;
}
for (int lVerticeIndex = 0; lVerticeIndex < 3; ++lVerticeIndex)
{
const int lControlPointIndex = lMesh->GetPolygonVertex(lPolygonIndex, lVerticeIndex);
if (lAllByControlPoint)
{
lIndices[lPolygonIndex * 3 + lVerticeIndex] = static_cast<unsigned int>(lControlPointIndex);
}
// Populate the array with vertex attribute, if by polygon vertex.
else
{
lIndices[lPolygonIndex * 3 + lVerticeIndex] = static_cast<unsigned int>(lVertexCount);
lCurrentVertex = lControlPoints[lControlPointIndex];
lVertices[lVertexCount * 3] = static_cast<float>(lCurrentVertex[0]);
lVertices[lVertexCount * 3 + 1] = static_cast<float>(lCurrentVertex[1]);
lVertices[lVertexCount * 3 + 2] = static_cast<float>(lCurrentVertex[2]);
lMaterialIndices[lVertexCount] = lMaterialIndex + lMaterialIndexBase;
vertexControlIndices.push_back(lControlPointIndex);
if (lHasNormal)
{
lMesh->GetPolygonVertexNormal(lPolygonIndex, lVerticeIndex, lCurrentNormal);
lNormals[lVertexCount * 3] = static_cast<float>(lCurrentNormal[0]);
lNormals[lVertexCount * 3 + 1] = static_cast<float>(lCurrentNormal[1]);
lNormals[lVertexCount * 3 + 2] = static_cast<float>(lCurrentNormal[2]);
}
if (lHasUV)
{
bool lUnmappedUV;
lMesh->GetPolygonVertexUV(lPolygonIndex, lVerticeIndex, lUVName, lCurrentUV, lUnmappedUV);
lUVs[lVertexCount * 2] = static_cast<float>(lCurrentUV[0]);
lUVs[lVertexCount * 2 + 1] = static_cast<float>(lCurrentUV[1]);
}
}
++lVertexCount;
}
}
shape_t shape;
shape.mesh.indices = lIndices;
shape.mesh.material_ids = lMaterialIndices;
shape.mesh.positions = lVertices;
shape.mesh.normals = lNormals;
shape.mesh.texcoords = lUVs;
gShapes.push_back(shape);
if ((FbxSkin *)lMesh->GetDeformer(0, FbxDeformer::eSkin) != 0)
{
delete [] lControlPoints;
}
/*
// For all skins and all clusters, accumulate their deformation and weight
// on each vertices and store them in lClusterDeformation and lClusterWeight.
vector<int> vertexJointIndices;
vertexJointIndices.resize(lMesh->GetControlPointsCount() * 4, -1);
vector<float> vertexJointWeights;
vertexJointWeights.resize(lMesh->GetControlPointsCount() * 4, -1);
vector<vector<float> > jointTransformMatrices;
int num_frames;
FbxTimeSpan lTimeLineTimeSpan;
pScene->GetGlobalSettings().GetTimelineDefaultTimeSpan(lTimeLineTimeSpan);
FbxTime lStartTime = lTimeLineTimeSpan.GetStart();
FbxTime lEndTime = lTimeLineTimeSpan.GetStop();
FbxTime lStepTime = (lEndTime - lStartTime) / 100;
// select the base layer from the animation stack
FbxAnimStack * lCurrentAnimationStack = pScene->GetSrcObject<FbxAnimStack>(0);
// we assume that the first animation layer connected to the animation stack is the base layer
// (this is the assumption made in the FBXSDK)
FbxAnimLayer *lCurrentAnimLayer = lCurrentAnimationStack->GetMember<FbxAnimLayer>();
int lSkinCount = lMesh->GetDeformerCount(FbxDeformer::eSkin);
for (int lSkinIndex = 0; lSkinIndex < lSkinCount && lSkinIndex < 1; ++lSkinIndex)
{
FbxSkin * lSkinDeformer = (FbxSkin *)lMesh->GetDeformer(lSkinIndex, FbxDeformer::eSkin);
int lClusterCount = lSkinDeformer->GetClusterCount();
for (int lClusterIndex = 0; lClusterIndex < lClusterCount; ++lClusterIndex)
{
FbxCluster* lCluster = lSkinDeformer->GetCluster(lClusterIndex);
if (!lCluster->GetLink())
continue;
FbxAMatrix globalPosition = FbxAMatrix(FbxVector4(0, 0, 0, 1), FbxVector4(0, 0, 0, 0), FbxVector4(1, 1, 1, 1));
num_frames = 0;
vector<float> OneJointTransformMatrices;
for (FbxTime lTime = lStartTime; lTime < lEndTime; lTime += lStepTime)
{
FbxAMatrix lVertexTransformMatrix;
ComputeClusterDeformation(globalPosition, lMesh, lCluster, lVertexTransformMatrix, lTime, 0);
for (int n = 0; n < 16; n++)
{
OneJointTransformMatrices.push_back(*((double*)(lVertexTransformMatrix) + n));
}
num_frames++;
}
jointTransformMatrices.push_back(OneJointTransformMatrices);
int lVertexIndexCount = lCluster->GetControlPointIndicesCount();
for (int k = 0; k < lVertexIndexCount; ++k)
{
int lIndex = lCluster->GetControlPointIndices()[k];
// Sometimes, the mesh can have less points than at the time of the skinning
// because a smooth operator was active when skinning but has been deactivated during export.
if (lIndex >= lVertexCount)
continue;
double lWeight = lCluster->GetControlPointWeights()[k];
if (lWeight == 0.0)
{
continue;
}
int m = 0;
while (m < 4 && vertexJointIndices[lIndex * 4 + m] != -1)
{
m++;
}
if (m != 4)
{
vertexJointIndices[lIndex * 4 + m] = lClusterIndex;
vertexJointWeights[lIndex * 4 + m] = (float) lWeight;
}
} //For each vertex
} //lClusterCount
}
animation_t animation;
animation.vertexJointIndices = vertexJointIndices;
animation.vertexJointWeights = vertexJointWeights;
animation.jointTransformMatrices = jointTransformMatrices;
animation.num_frames = num_frames;
animation.vertexControlIndices = vertexControlIndices;
gAnimations.push_back(animation);
*/
}
}
}
const int lChildCount = pNode->GetChildCount();
for (int lChildIndex = 0; lChildIndex < lChildCount; ++lChildIndex)
{
LoadCacheRecursive(pScene, pNode->GetChild(lChildIndex), lGlobalPosition, pTime);
}
}
// Deform the vertex array with the shapes contained in the mesh.
void ComputeShapeDeformation(FbxMesh* pMesh, FbxTime& pTime, FbxAnimLayer * pAnimLayer, FbxVector4* pVertexArray)
{
int lVertexCount = pMesh->GetControlPointsCount();
FbxVector4* lSrcVertexArray = pVertexArray;
FbxVector4* lDstVertexArray = new FbxVector4[lVertexCount];
memcpy(lDstVertexArray, pVertexArray, lVertexCount * sizeof(FbxVector4));
int lBlendShapeDeformerCount = pMesh->GetDeformerCount(FbxDeformer::eBlendShape);
for (int lBlendShapeIndex = 0; lBlendShapeIndex<lBlendShapeDeformerCount; ++lBlendShapeIndex)
{
FbxBlendShape* lBlendShape = (FbxBlendShape*)pMesh->GetDeformer(lBlendShapeIndex, FbxDeformer::eBlendShape);
int lBlendShapeChannelCount = lBlendShape->GetBlendShapeChannelCount();
for (int lChannelIndex = 0; lChannelIndex<lBlendShapeChannelCount; ++lChannelIndex)
{
FbxBlendShapeChannel* lChannel = lBlendShape->GetBlendShapeChannel(lChannelIndex);
if (lChannel)
{
// Get the percentage of influence on this channel.
FbxAnimCurve* lFCurve = pMesh->GetShapeChannel(lBlendShapeIndex, lChannelIndex, pAnimLayer);
if (!lFCurve) continue;
double lWeight = lFCurve->Evaluate(pTime);
/*
If there is only one targetShape on this channel, the influence is easy to calculate:
influence = (targetShape - baseGeometry) * weight * 0.01
dstGeometry = baseGeometry + influence
But if there are more than one targetShapes on this channel, this is an in-between
blendshape, also called progressive morph. The calculation of influence is different.
For example, given two in-between targets, the full weight percentage of first target
is 50, and the full weight percentage of the second target is 100.
When the weight percentage reach 50, the base geometry is already be fully morphed
to the first target shape. When the weight go over 50, it begin to morph from the
first target shape to the second target shape.
To calculate influence when the weight percentage is 25:
1. 25 falls in the scope of 0 and 50, the morphing is from base geometry to the first target.
2. And since 25 is already half way between 0 and 50, so the real weight percentage change to
the first target is 50.
influence = (firstTargetShape - baseGeometry) * (25-0)/(50-0) * 100
dstGeometry = baseGeometry + influence
To calculate influence when the weight percentage is 75:
1. 75 falls in the scope of 50 and 100, the morphing is from the first target to the second.
2. And since 75 is already half way between 50 and 100, so the real weight percentage change
to the second target is 50.
influence = (secondTargetShape - firstTargetShape) * (75-50)/(100-50) * 100
dstGeometry = firstTargetShape + influence
*/
// Find the two shape indices for influence calculation according to the weight.
// Consider index of base geometry as -1.
int lShapeCount = lChannel->GetTargetShapeCount();
double* lFullWeights = lChannel->GetTargetShapeFullWeights();
// Find out which scope the lWeight falls in.
int lStartIndex = -1;
int lEndIndex = -1;
for (int lShapeIndex = 0; lShapeIndex<lShapeCount; ++lShapeIndex)
{
if (lWeight > 0 && lWeight <= lFullWeights[0])
{
lEndIndex = 0;
break;
}
if (lWeight > lFullWeights[lShapeIndex] && lWeight < lFullWeights[lShapeIndex + 1])
{
lStartIndex = lShapeIndex;
lEndIndex = lShapeIndex + 1;
break;
}
}
FbxShape* lStartShape = NULL;
FbxShape* lEndShape = NULL;
if (lStartIndex > -1)
{
lStartShape = lChannel->GetTargetShape(lStartIndex);
}
if (lEndIndex > -1)
{
lEndShape = lChannel->GetTargetShape(lEndIndex);
}