-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSceneContext.cxx
1258 lines (1080 loc) · 40.8 KB
/
SceneContext.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************************
Copyright (C) 2013 Autodesk, Inc.
Edited 2013 by Emre Tanirgan
All rights reserved.
Use of this software is subject to the terms of the Autodesk license agreement
provided at the time of installation or download, or which otherwise accompanies
this software in either electronic or hard copy form.
****************************************************************************************/
#include "SceneContext.h"
#include "SceneCache.h"
#include "SetCamera.h"
#include "DrawScene.h"
#include "DrawText.h"
#include "targa.h"
#include "../Common/Common.h"
#include <string.h>
#include "Skeleton.h"
#include "Transformation.h"
#include <fstream>
#include <iostream>
namespace
{
// Default file of ViewScene example
const char * SAMPLE_FILENAME = "bearbvhdancelights.fbx";
// Button and action definition
const int LEFT_BUTTON = 0;
const int MIDDLE_BUTTON = 1;
const int RIGHT_BUTTON = 2;
const int BUTTON_DOWN = 0;
const int BUTTON_UP = 1;
// Find all the cameras under this node recursively.
void FillCameraArrayRecursive(FbxNode* pNode, FbxArray<FbxNode*>& pCameraArray)
{
if (pNode)
{
if (pNode->GetNodeAttribute())
{
if (pNode->GetNodeAttribute()->GetAttributeType() == FbxNodeAttribute::eCamera)
{
pCameraArray.Add(pNode);
}
}
const int lCount = pNode->GetChildCount();
for (int i = 0; i < lCount; i++)
{
FillCameraArrayRecursive(pNode->GetChild(i), pCameraArray);
}
}
}
// Find all the cameras in this scene.
void FillCameraArray(FbxScene* pScene, FbxArray<FbxNode*>& pCameraArray)
{
pCameraArray.Clear();
FillCameraArrayRecursive(pScene->GetRootNode(), pCameraArray);
}
// Find all poses in this scene.
void FillPoseArray(FbxScene* pScene, FbxArray<FbxPose*>& pPoseArray)
{
const int lPoseCount = pScene->GetPoseCount();
for (int i=0; i < lPoseCount; ++i)
{
pPoseArray.Add(pScene->GetPose(i));
}
}
void PreparePointCacheData(FbxScene* pScene, FbxTime &pCache_Start, FbxTime &pCache_Stop)
{
// This function show how to cycle through scene elements in a linear way.
const int lNodeCount = pScene->GetSrcObjectCount<FbxNode>();
FbxStatus lStatus;
for (int lIndex=0; lIndex<lNodeCount; lIndex++)
{
FbxNode* lNode = pScene->GetSrcObject<FbxNode>(lIndex);
if (lNode->GetGeometry())
{
int i, lVertexCacheDeformerCount = lNode->GetGeometry()->GetDeformerCount(FbxDeformer::eVertexCache);
// There should be a maximum of 1 Vertex Cache Deformer for the moment
lVertexCacheDeformerCount = lVertexCacheDeformerCount > 0 ? 1 : 0;
for (i=0; i<lVertexCacheDeformerCount; ++i )
{
// Get the Point Cache object
FbxVertexCacheDeformer* lDeformer = static_cast<FbxVertexCacheDeformer*>(lNode->GetGeometry()->GetDeformer(i, FbxDeformer::eVertexCache));
if( !lDeformer ) continue;
FbxCache* lCache = lDeformer->GetCache();
if( !lCache ) continue;
// Process the point cache data only if the constraint is active
if (lDeformer->IsActive())
{
if (lCache->GetCacheFileFormat() == FbxCache::eMaxPointCacheV2)
{
// This code show how to convert from PC2 to MC point cache format
// turn it on if you need it.
#if 0
if (!lCache->ConvertFromPC2ToMC(FbxCache::eMCOneFile,
FbxTime::GetFrameRate(pScene->GetGlobalTimeSettings().GetTimeMode())))
{
// Conversion failed, retrieve the error here
FbxString lTheErrorIs = lCache->GetStaus().GetErrorString();
}
#endif
}
else if (lCache->GetCacheFileFormat() == FbxCache::eMayaCache)
{
// This code show how to convert from MC to PC2 point cache format
// turn it on if you need it.
//#if 0
if (!lCache->ConvertFromMCToPC2(FbxTime::GetFrameRate(pScene->GetGlobalSettings().GetTimeMode()), 0, &lStatus))
{
// Conversion failed, retrieve the error here
FbxString lTheErrorIs = lStatus.GetErrorString();
}
//#endif
}
// Now open the cache file to read from it
if (!lCache->OpenFileForRead(&lStatus))
{
// Cannot open file
FbxString lTheErrorIs = lStatus.GetErrorString();
// Set the deformer inactive so we don't play it back
lDeformer->SetActive(false);
}
else
{
// get the start and stop time of the cache
int lChannelCount = lCache->GetChannelCount();
for (int iChannelNo=0; iChannelNo < lChannelCount; iChannelNo++)
{
FbxTime lChannel_Start;
FbxTime lChannel_Stop;
if(lCache->GetAnimationRange(iChannelNo, lChannel_Start, lChannel_Stop))
{
// get the smallest start time
if(lChannel_Start < pCache_Start) pCache_Start = lChannel_Start;
// get the biggest stop time
if(lChannel_Stop > pCache_Stop) pCache_Stop = lChannel_Stop;
}
}
}
}
}
}
}
}
// Load a texture file (TGA only now) into GPU and return the texture object name
bool LoadTextureFromFile(const FbxString & pFilePath, unsigned int & pTextureObject)
{
if (pFilePath.Right(3).Upper() == "TGA")
{
tga_image lTGAImage;
if (tga_read(&lTGAImage, pFilePath.Buffer()) == TGA_NOERR)
{
// Make sure the image is left to right
if (tga_is_right_to_left(&lTGAImage))
tga_flip_horiz(&lTGAImage);
// Make sure the image is bottom to top
if (tga_is_top_to_bottom(&lTGAImage))
tga_flip_vert(&lTGAImage);
// Make the image BGR 24
tga_convert_depth(&lTGAImage, 24);
// Transfer the texture date into GPU
glGenTextures(1, &pTextureObject);
glBindTexture(GL_TEXTURE_2D, pTextureObject);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexImage2D(GL_TEXTURE_2D, 0, 3, lTGAImage.width, lTGAImage.height, 0, GL_BGR,
GL_UNSIGNED_BYTE, lTGAImage.image_data);
glBindTexture(GL_TEXTURE_2D, 0);
tga_free_buffers(&lTGAImage);
return true;
}
}
return false;
}
// Bake node attributes and materials under this node recursively.
// Currently only mesh, light and material.
void LoadCacheRecursive(FbxNode * pNode, FbxAnimLayer * pAnimLayer, bool pSupportVBO)
{
// Bake material and hook as user data.
const int lMaterialCount = pNode->GetMaterialCount();
for (int lMaterialIndex = 0; lMaterialIndex < lMaterialCount; ++lMaterialIndex)
{
FbxSurfaceMaterial * lMaterial = pNode->GetMaterial(lMaterialIndex);
if (lMaterial && !lMaterial->GetUserDataPtr())
{
FbxAutoPtr<MaterialCache> lMaterialCache(new MaterialCache);
if (lMaterialCache->Initialize(lMaterial))
{
lMaterial->SetUserDataPtr(lMaterialCache.Release());
}
}
}
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 (pSupportVBO && lMesh && !lMesh->GetUserDataPtr())
{
FbxAutoPtr<VBOMesh> lMeshCache(new VBOMesh);
if (lMeshCache->Initialize(lMesh))
{
lMesh->SetUserDataPtr(lMeshCache.Release());
}
}
}
// Bake light properties.
else if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eLight)
{
FbxLight * lLight = pNode->GetLight();
if (lLight && !lLight->GetUserDataPtr())
{
FbxAutoPtr<LightCache> lLightCache(new LightCache);
if (lLightCache->Initialize(lLight, pAnimLayer))
{
lLight->SetUserDataPtr(lLightCache.Release());
}
}
}
}
const int lChildCount = pNode->GetChildCount();
for (int lChildIndex = 0; lChildIndex < lChildCount; ++lChildIndex)
{
LoadCacheRecursive(pNode->GetChild(lChildIndex), pAnimLayer, pSupportVBO);
}
}
// Unload the cache and release the memory under this node recursively.
void UnloadCacheRecursive(FbxNode * pNode)
{
// Unload the material cache
const int lMaterialCount = pNode->GetMaterialCount();
for (int lMaterialIndex = 0; lMaterialIndex < lMaterialCount; ++lMaterialIndex)
{
FbxSurfaceMaterial * lMaterial = pNode->GetMaterial(lMaterialIndex);
if (lMaterial && lMaterial->GetUserDataPtr())
{
MaterialCache * lMaterialCache = static_cast<MaterialCache *>(lMaterial->GetUserDataPtr());
lMaterial->SetUserDataPtr(NULL);
delete lMaterialCache;
}
}
FbxNodeAttribute* lNodeAttribute = pNode->GetNodeAttribute();
if (lNodeAttribute)
{
// Unload the mesh cache
if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eMesh)
{
FbxMesh * lMesh = pNode->GetMesh();
if (lMesh && lMesh->GetUserDataPtr())
{
VBOMesh * lMeshCache = static_cast<VBOMesh *>(lMesh->GetUserDataPtr());
lMesh->SetUserDataPtr(NULL);
delete lMeshCache;
}
}
// Unload the light cache
else if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eLight)
{
FbxLight * lLight = pNode->GetLight();
if (lLight && lLight->GetUserDataPtr())
{
LightCache * lLightCache = static_cast<LightCache *>(lLight->GetUserDataPtr());
lLight->SetUserDataPtr(NULL);
delete lLightCache;
}
}
}
const int lChildCount = pNode->GetChildCount();
for (int lChildIndex = 0; lChildIndex < lChildCount; ++lChildIndex)
{
UnloadCacheRecursive(pNode->GetChild(lChildIndex));
}
}
// Bake node attributes and materials for this scene and load the textures.
void LoadCacheRecursive(FbxScene * pScene, FbxAnimLayer * pAnimLayer, const char * pFbxFileName, bool pSupportVBO)
{
// Load the textures into GPU, only for file texture now
const int lTextureCount = pScene->GetTextureCount();
for (int lTextureIndex = 0; lTextureIndex < lTextureCount; ++lTextureIndex)
{
FbxTexture * lTexture = pScene->GetTexture(lTextureIndex);
FbxFileTexture * lFileTexture = FbxCast<FbxFileTexture>(lTexture);
if (lFileTexture && !lFileTexture->GetUserDataPtr())
{
// Try to load the texture from absolute path
const FbxString lFileName = lFileTexture->GetFileName();
// Only TGA textures are supported now.
if (lFileName.Right(3).Upper() != "TGA")
{
FBXSDK_printf("Only TGA textures are supported now: %s\n", lFileName.Buffer());
continue;
}
GLuint lTextureObject = 0;
bool lStatus = LoadTextureFromFile(lFileName, lTextureObject);
const FbxString lAbsFbxFileName = FbxPathUtils::Resolve(pFbxFileName);
const FbxString lAbsFolderName = FbxPathUtils::GetFolderName(lAbsFbxFileName);
if (!lStatus)
{
// Load texture from relative file name (relative to FBX file)
const FbxString lResolvedFileName = FbxPathUtils::Bind(lAbsFolderName, lFileTexture->GetRelativeFileName());
lStatus = LoadTextureFromFile(lResolvedFileName, lTextureObject);
}
if (!lStatus)
{
// Load texture from file name only (relative to FBX file)
const FbxString lTextureFileName = FbxPathUtils::GetFileName(lFileName);
const FbxString lResolvedFileName = FbxPathUtils::Bind(lAbsFolderName, lTextureFileName);
lStatus = LoadTextureFromFile(lResolvedFileName, lTextureObject);
}
if (!lStatus)
{
FBXSDK_printf("Failed to load texture file: %s\n", lFileName.Buffer());
continue;
}
if (lStatus)
{
GLuint * lTextureName = new GLuint(lTextureObject);
lFileTexture->SetUserDataPtr(lTextureName);
}
}
}
LoadCacheRecursive(pScene->GetRootNode(), pAnimLayer, pSupportVBO);
}
// Unload the cache and release the memory fro this scene and release the textures in GPU
void UnloadCacheRecursive(FbxScene * pScene)
{
const int lTextureCount = pScene->GetTextureCount();
for (int lTextureIndex = 0; lTextureIndex < lTextureCount; ++lTextureIndex)
{
FbxTexture * lTexture = pScene->GetTexture(lTextureIndex);
FbxFileTexture * lFileTexture = FbxCast<FbxFileTexture>(lTexture);
if (lFileTexture && lFileTexture->GetUserDataPtr())
{
GLuint * lTextureName = static_cast<GLuint *>(lFileTexture->GetUserDataPtr());
lFileTexture->SetUserDataPtr(NULL);
glDeleteTextures(1, lTextureName);
delete lTextureName;
}
}
UnloadCacheRecursive(pScene->GetRootNode());
}
}
bool InitializeOpenGL()
{
// Initialize GLEW.
GLenum lError = glewInit();
if (lError != GLEW_OK)
{
FBXSDK_printf("GLEW Error: %s\n", glewGetErrorString(lError));
return false;
}
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glClearColor(0.0, 0.0, 0.0, 0.0);
// OpenGL 1.5 at least.
if (!GLEW_VERSION_1_5)
{
FBXSDK_printf("The OpenGL version should be at least 1.5 to display shaded scene!\n");
return false;
}
return true;
}
SceneContext::SceneContext(const char * pFileName, int pWindowWidth, int pWindowHeight, bool pSupportVBO)
: mFileName(pFileName), mStatus(UNLOADED),
mSdkManager(NULL), mScene(NULL), mImporter(NULL), mCurrentAnimLayer(NULL), mSelectedNode(NULL),
mPoseIndex(-1), mCameraStatus(CAMERA_NOTHING), mPause(false), mShadingMode(SHADING_MODE_SHADED),
mSupportVBO(pSupportVBO), mCameraZoomMode(ZOOM_FOCAL_LENGTH),
mWindowWidth(pWindowWidth), mWindowHeight(pWindowHeight), mDrawText(new DrawText), setAnim(false)
{
if (mFileName == NULL)
mFileName = SAMPLE_FILENAME;
// initialize cache start and stop time
mCache_Start = FBXSDK_TIME_INFINITE;
mCache_Stop = FBXSDK_TIME_MINUS_INFINITE;
skeleton = new Skeleton();
// Create the FBX SDK manager which is the object allocator for almost
// all the classes in the SDK and create the scene.
InitializeSdkObjects(mSdkManager, mScene);
if (mSdkManager)
{
// Create the importer.
int lFileFormat = -1;
mImporter = FbxImporter::Create(mSdkManager,"");
if (!mSdkManager->GetIOPluginRegistry()->DetectReaderFileFormat(mFileName, lFileFormat) )
{
// Unrecognizable file format. Try to fall back to FbxImporter::eFBX_BINARY
lFileFormat = mSdkManager->GetIOPluginRegistry()->FindReaderIDByDescription( "FBX binary (*.fbx)" );;
}
// Initialize the importer by providing a filename.
if(mImporter->Initialize(mFileName, lFileFormat) == true)
{
// The file is going to be imported at
// the end of the first display callback.
mWindowMessage = "Importing file ";
mWindowMessage += mFileName;
mWindowMessage += "\nPlease wait!";
// Set scene status flag to ready to load.
mStatus = MUST_BE_LOADED;
}
else
{
mWindowMessage = "Unable to open file ";
mWindowMessage += mFileName;
mWindowMessage += "\nError reported: ";
mWindowMessage += mImporter->GetStatus().GetErrorString();
mWindowMessage += "\nEsc to exit";
}
}
else
{
mWindowMessage = "Unable to create the FBX SDK manager";
mWindowMessage += "\nEsc to exit";
}
}
SceneContext::~SceneContext()
{
FbxArrayDelete(mAnimStackNameArray);
delete mDrawText;
// Unload the cache and free the memory
if (mScene)
{
UnloadCacheRecursive(mScene);
}
// Delete the FBX SDK manager. All the objects that have been allocated
// using the FBX SDK manager and that haven't been explicitly destroyed
// are automatically destroyed at the same time.
DestroySdkObjects(mSdkManager, true);
}
bool SceneContext::LoadFile()
{
bool lResult = false;
// Make sure that the scene is ready to load.
if (mStatus == MUST_BE_LOADED)
{
if (mImporter->Import(mScene) == true)
{
// Set the scene status flag to refresh
// the scene in the first timer callback.
mStatus = MUST_BE_REFRESHED;
// mCurrentAnimLayer->
// Convert Axis System to what is used in this example, if needed
FbxAxisSystem SceneAxisSystem = mScene->GetGlobalSettings().GetAxisSystem();
FbxAxisSystem OurAxisSystem(FbxAxisSystem::eYAxis, FbxAxisSystem::eParityOdd, FbxAxisSystem::eRightHanded);
if( SceneAxisSystem != OurAxisSystem )
{
OurAxisSystem.ConvertScene(mScene);
}
// Convert Unit System to what is used in this example, if needed
FbxSystemUnit SceneSystemUnit = mScene->GetGlobalSettings().GetSystemUnit();
if( SceneSystemUnit.GetScaleFactor() != 1.0 )
{
//The unit in this example is centimeter.
FbxSystemUnit::cm.ConvertScene( mScene);
}
// Get the list of all the animation stack.
mScene->FillAnimStackNameArray(mAnimStackNameArray);
// Get the list of all the cameras in the scene.
FillCameraArray(mScene, mCameraArray);
// Convert mesh, NURBS and patch into triangle mesh
FbxGeometryConverter lGeomConverter(mSdkManager);
lGeomConverter.Triangulate(mScene, /*replace*/true);
// Split meshes per material, so that we only have one material per mesh (for VBO support)
lGeomConverter.SplitMeshesPerMaterial(mScene, /*replace*/true);
// Bake the scene for one frame
LoadCacheRecursive(mScene, mCurrentAnimLayer, mFileName, mSupportVBO);
// Convert any .PC2 point cache data into the .MC format for
// vertex cache deformer playback.
PreparePointCacheData(mScene, mCache_Start, mCache_Stop);
// Get the list of pose in the scene
FillPoseArray(mScene, mPoseArray);
// Initialize the window message.
mWindowMessage = "File ";
mWindowMessage += mFileName;
mWindowMessage += "\nClick on the right mouse button to enter menu.";
mWindowMessage += "\nEsc to exit.";
// Initialize the frame period.
mFrameTime.SetTime(0, 0, 0, 1, 0, mScene->GetGlobalSettings().GetTimeMode());
// Print the keyboard shortcuts.
FBXSDK_printf("Play/Pause Animation: Space Bar.\n");
FBXSDK_printf("Camera Rotate: Left Mouse Button.\n");
FBXSDK_printf("Camera Pan: Left Mouse Button + Middle Mouse Button.\n");
FBXSDK_printf("Camera Zoom: Middle Mouse Button.\n");
lResult = true;
}
else
{
// Import failed, set the scene status flag accordingly.
mStatus = UNLOADED;
mWindowMessage = "Unable to import file ";
mWindowMessage += mFileName;
mWindowMessage += "\nError reported: ";
mWindowMessage += mImporter->GetStatus().GetErrorString();
}
// Destroy the importer to release the file.
mImporter->Destroy();
mImporter = NULL;
}
return lResult;
}
void SceneContext::convertToSkeleton(){
double fps = 30.0f;
int framecount;
int nodecount = mScene->GetNodeCount();
FbxNode* rootNode = mScene->GetRootNode();
printf("Nodes: %i \n", nodecount);
FbxTime zeroTime;
zeroTime.SetSecondDouble(0.0);
//We first set the skeleton, this part seems to be working fine except rotations
for(int i = 2; i < nodecount; i++){
FbxNode* node = mScene->GetNode(i);
EFbxRotationOrder lRotationOrder;
node->GetRotationOrder(FbxNode::eSourcePivot, lRotationOrder);
printf("Node #%i: %s \n", i, node->GetName());
//If the node isn't a camera or light, it's a joint
if(!node->GetCamera() && !node->GetLight()){
Joint* joint = new Joint(node->GetName());
//joint->SetID(i);
switch (lRotationOrder){
case eEulerXYZ: joint->SetRotationOrder("XYZ");
break;
case eEulerXZY: joint->SetRotationOrder("XZY");
break;
case eEulerYZX: joint->SetRotationOrder("YXZ");
break;
case eEulerYXZ: joint->SetRotationOrder("YXZ");
break;
case eEulerZXY: joint->SetRotationOrder("ZXY");
break;
case eEulerZYX: joint->SetRotationOrder("ZYX");
break;
case eSphericXYZ: joint->SetRotationOrder("XYZ");
break;
}
joint->SetNumChannels(3);
if(i==2){
//This is the root
joint->SetNumChannels(6);
skeleton->AddJoint(joint, true);
}
else{
joint->SetNumChannels(3);
skeleton->AddJoint(joint, false);
}
//Local translation and rotation
FbxVector4& lcltranslate = node->EvaluateLocalTranslation(FBXSDK_TIME_INFINITE, FbxNode::eSourcePivot, false, false);
joint->SetLocalTranslation(vec3(lcltranslate[0], lcltranslate[1], lcltranslate[2]));
FbxVector4& lclrotate = node->EvaluateLocalRotation(zeroTime, FbxNode::eSourcePivot, false, false);
//printf("Local Rotation for Joint %s: %f, %f, %f \n", node->GetName(), lclrotate[0], lclrotate[1], lclrotate[2]);
mat3 rotmat = mat3();
joint->SetLocalRotation(rotmat.FromEulerAnglesZXY(vec3(lclrotate[0], lclrotate[1], lclrotate[2])));
}
}
//Set parenting relationships - seems to work fine
int keyCount = 0;
for(int i = 2; i < nodecount; i++){
FbxNode* node = mScene->GetNode(i);
if(!node->GetCamera() && !node->GetLight()){
FbxNode* parent = node->GetParent();
if(parent){
Joint* jChild = skeleton->GetJointByName(node->GetName());
Joint* jParent = skeleton->GetJointByName(parent->GetName());
Joint::AttachJoints(jParent, jChild);
}
FbxAnimCurve* transAnimCurve = node->LclTranslation.GetCurve(mCurrentAnimLayer, FBXSDK_CURVENODE_COMPONENT_X);
if(transAnimCurve){
keyCount = transAnimCurve->KeyGetCount();
}
/*
FbxAnimCurve* rotAnimCurve = node->LclRotation.GetCurve(mCurrentAnimLayer, FBXSDK_CURVENODE_COMPONENT_X);
if(rotAnimCurve){
keyCount = rotAnimCurve->KeyGetCount();
//FbxAnimCurveKey lKey = rotAnimCurve->KeyGet(i);
// float lKeyValue = lKey.GetValue();
}
*/
}
}
//Create keyframes and set up animation - not working
fps = FbxTime::GetFrameRate(mScene->GetGlobalSettings().GetTimeMode());
framecount = mScene->GetGlobalSettings().GetTimeMarkerCount();
motion = new Motion();
motion->SetFps(fps);
//Starting time
FbxTime myTime;
myTime.SetSecondDouble(0.0);
for(int i=0; i<keyCount; i++){
myTime.SetSecondDouble(i/fps);
Frame* frame = new Frame();
frame->SetRootTranslation(skeleton->GetRootJoint()->GetLocalTranslation());
frame->SetNumJoints(skeleton->m_joints.size());
int index = 0;
for(int j=2; j<nodecount; j++){
FbxNode* node = mScene->GetNode(j);
if(!node->GetCamera() && !node->GetLight()){
FbxVector4& lclrotate = node->EvaluateLocalRotation(myTime, FbxNode::eSourcePivot, false, false);
vec3 rotvec = vec3(lclrotate[0], lclrotate[1], lclrotate[2]);
mat3 rotmat = mat3();
frame->SetJointRotation(index, rotmat.FromEulerAnglesZXY(rotvec*Deg2Rad));
index++;
}
}
motion->AppendFrame(*frame);
}
std::ofstream newfile("testbvh.bvh");
skeleton->SaveToBVHFile(newfile);
motion->SaveToBVHFile(newfile, *skeleton);
std::map<std::string, unsigned int> skinWeightJoints;
std::vector<std::vector<float>> skinWeights;
for (int i = 0; i < nodecount; i++){
FbxNode* node = mScene->GetNode(i);
FbxMesh* mesh = node->GetMesh();
if(!mesh){
continue;
}
int vertCount = mesh->GetControlPointsCount();
if(vertCount == 0){
continue;
}
bool hasSkin = mesh->GetDeformerCount(FbxDeformer::eSkin) > 0;
int skinCount = mesh->GetDeformerCount(FbxDeformer::eSkin);
int vertexCount = mesh->GetPolygonVertexCount();
printf("Vertex Count: %i\n", vertexCount);
int clusterCount = 0;
for(int skinIndex = 0; skinIndex < skinCount; skinIndex++){
clusterCount += ((FbxSkin*)(mesh->GetDeformer(skinIndex, FbxDeformer::eSkin)))->GetClusterCount();
FbxSkin* skin = (FbxSkin*)mesh->GetDeformer(skinIndex, FbxDeformer::eSkin);
printf("Skin #%i: Cluster count %i\n", skinIndex, skin->GetClusterCount());
for (int j=0; j<skin->GetClusterCount(); j++){
FbxCluster* cluster = skin->GetCluster(j);
int* vertIndices = cluster->GetControlPointIndices();
int vertCount = cluster->GetControlPointIndicesCount();
printf("Number of ctrl points: %i\n", vertCount);
double* vertWeights = cluster->GetControlPointWeights();
skinWeights.resize(nodecount);
/*(Emre) NOT DONE - UNCOMMENT IF YOU WANT TO CONTINUE
for(int k = 0; k < vertCount; k++){
skinWeights.at(k).resize(vertexCount);
vertIndices[k];
if(j==0){
printf("Index %i: %i\n", k, vertIndices[k]);
}
skinWeights.at(0).at(vertIndices[k]) = vertWeights[k];
}*/
}
}
//if (clusterCount){
//}
}
/*bxMesh* lMesh = pNode->GetMesh();
const int lVertexCount = lMesh->GetControlPointsCount();
const int lSkinCount = lMesh->GetDeformerCount(FbxDeformer::eSkin);
int lClusterCount = 0;
for (int lSkinIndex = 0; lSkinIndex < lSkinCount; ++lSkinIndex)
{
lClusterCount += ((FbxSkin *)(lMesh->GetDeformer(lSkinIndex, FbxDeformer::eSkin)))->GetClusterCount();
}
if (lClusterCount)
{
// Deform the vertex array with the skin deformer.
ComputeSkinDeformation(pGlobalPosition, lMesh, pTime, lVertexArray, pPose);
}
// No vertex to draw.
if (lVertexCount == 0)
{
return;
}
const VBOMesh * lMeshCache = static_cast<const VBOMesh *>(lMesh->GetUserDataPtr());
// If it has some defomer connection, update the vertices position
const bool lHasVertexCache = lMesh->GetDeformerCount(FbxDeformer::eVertexCache) &&
(static_cast<FbxVertexCacheDeformer*>(lMesh->GetDeformer(0, FbxDeformer::eVertexCache)))->IsActive();
const bool lHasShape = lMesh->GetShapeCount() > 0;
const bool lHasSkin = lMesh->GetDeformerCount(FbxDeformer::eSkin) > 0;
const bool lHasDeformation = lHasVertexCache || lHasShape || lHasSkin;
FbxVector4* lVertexArray = NULL;
if (!lMeshCache || lHasDeformation)
{
lVertexArray = new FbxVector4[lVertexCount];
memcpy(lVertexArray, lMesh->GetControlPoints(), lVertexCount * sizeof(FbxVector4));
}
if (lHasDeformation)
{
// Active vertex cache deformer will overwrite any other deformer
if (lHasVertexCache)
{
ReadVertexCacheData(lMesh, pTime, lVertexArray);
}
else
{
if (lHasShape)
{
// Deform the vertex array with the shapes.
ComputeShapeDeformation(lMesh, pTime, pAnimLayer, lVertexArray);
}
//we need to get the number of clusters
const int lSkinCount = lMesh->GetDeformerCount(FbxDeformer::eSkin);
int lClusterCount = 0;
for (int lSkinIndex = 0; lSkinIndex < lSkinCount; ++lSkinIndex)
{
lClusterCount += ((FbxSkin *)(lMesh->GetDeformer(lSkinIndex, FbxDeformer::eSkin)))->GetClusterCount();
}
if (lClusterCount)
{
// Deform the vertex array with the skin deformer.
ComputeSkinDeformation(pGlobalPosition, lMesh, pTime, lVertexArray, pPose);
}
}
if (lMeshCache)
lMeshCache->UpdateVertexPosition(lMesh, lVertexArray);
}*/
}
bool SceneContext::SetCurrentAnimStack(int pIndex)
{
setAnim = true;
const int lAnimStackCount = mAnimStackNameArray.GetCount();
if (!lAnimStackCount || pIndex >= lAnimStackCount)
{
return false;
}
// select the base layer from the animation stack
FbxAnimStack * lCurrentAnimationStack = mScene->FindMember<FbxAnimStack>(mAnimStackNameArray[pIndex]->Buffer());
if (lCurrentAnimationStack == NULL)
{
// this is a problem. The anim stack should be found in the scene!
return false;
}
// we assume that the first animation layer connected to the animation stack is the base layer
// (this is the assumption made in the FBXSDK)
mCurrentAnimLayer = lCurrentAnimationStack->GetMember<FbxAnimLayer>();
mScene->GetEvaluator()->SetContext(lCurrentAnimationStack);
FbxTakeInfo* lCurrentTakeInfo = mScene->GetTakeInfo(*(mAnimStackNameArray[pIndex]));
if (lCurrentTakeInfo)
{
mStart = lCurrentTakeInfo->mLocalTimeSpan.GetStart();
mStop = lCurrentTakeInfo->mLocalTimeSpan.GetStop();
}
else
{
// Take the time line value
FbxTimeSpan lTimeLineTimeSpan;
mScene->GetGlobalSettings().GetTimelineDefaultTimeSpan(lTimeLineTimeSpan);
mStart = lTimeLineTimeSpan.GetStart();
mStop = lTimeLineTimeSpan.GetStop();
}
// check for smallest start with cache start
if(mCache_Start < mStart)
mStart = mCache_Start;
// check for biggest stop with cache stop
if(mCache_Stop > mStop)
mStop = mCache_Stop;
// move to beginning
mCurrentTime = mStart;
// Set the scene status flag to refresh
// the scene in the next timer callback.
mStatus = MUST_BE_REFRESHED;
convertToSkeleton();
return true;
}
bool SceneContext::SetCurrentCamera(const char * pCameraName)
{
if (!pCameraName)
{
return false;
}
FbxGlobalSettings& lGlobalCameraSettings = mScene->GetGlobalSettings();
lGlobalCameraSettings.SetDefaultCamera(pCameraName);
mStatus = MUST_BE_REFRESHED;
return true;
}
bool SceneContext::SetCurrentPoseIndex(int pPoseIndex)
{
mPoseIndex = pPoseIndex;
mStatus = MUST_BE_REFRESHED;
return true;
}
void SceneContext::OnTimerClick() const
{
// Loop in the animation stack if not paused.
if (mStop > mStart && !mPause)
{
// Set the scene status flag to refresh
// the scene in the next timer callback.
mStatus = MUST_BE_REFRESHED;
mCurrentTime += mFrameTime;
if (mCurrentTime > mStop)
{
mCurrentTime = mStart;
}
}
// Avoid displaying the same frame on
// and on if the animation stack has no length.
else
{
// Set the scene status flag to avoid refreshing
// the scene in the next timer callback.
mStatus = REFRESHED;
}
}
// Redraw the scene
bool SceneContext::OnDisplay()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Test if the scene has been loaded yet.
if (mStatus != UNLOADED && mStatus != MUST_BE_LOADED)
{
glPushAttrib(GL_ENABLE_BIT);
glPushAttrib(GL_LIGHTING_BIT);
glEnable(GL_DEPTH_TEST);
// Draw the front face only, except for the texts and lights.
glEnable(GL_CULL_FACE);
// Set the view to the current camera settings.
SetCamera(mScene, mCurrentTime, mCurrentAnimLayer, mCameraArray,
mWindowWidth, mWindowHeight);
FbxPose * lPose = NULL;
if (mPoseIndex != -1)
{
lPose = mScene->GetPose(mPoseIndex);
}
// If one node is selected, draw it and its children.
FbxAMatrix lDummyGlobalPosition;
if (mSelectedNode)
{
// Set the lighting before other things.
InitializeLights(mScene, mCurrentTime, lPose);
DrawNodeRecursive(mSelectedNode, mCurrentTime, mCurrentAnimLayer, lDummyGlobalPosition, lPose, mShadingMode);
DisplayGrid(lDummyGlobalPosition);
}
// Otherwise, draw the whole scene.
else
{
InitializeLights(mScene, mCurrentTime, lPose);
DrawNodeRecursive(mScene->GetRootNode(), mCurrentTime, mCurrentAnimLayer, lDummyGlobalPosition, lPose, mShadingMode);
DisplayGrid(lDummyGlobalPosition);
}
glPopAttrib();
glPopAttrib();
}
DisplayWindowMessage();
return true;
}
void SceneContext::OnReshape(int pWidth, int pHeight)
{
glViewport(0, 0, (GLsizei)pWidth, (GLsizei)pHeight);
mWindowWidth = pWidth;
mWindowHeight = pHeight;
}
void SceneContext::OnKeyboard(unsigned char pKey)
{
// Zoom In on '+' or '=' keypad keys
if (pKey == 43 || pKey == 61)
{
FbxCamera* lCamera = GetCurrentCamera(mScene);
if(lCamera)
{
//double lOriginalAperture = sqrt(lCamera->GetApertureWidth());
CameraZoom(mScene, 10, mCameraZoomMode);
mStatus = MUST_BE_REFRESHED;
}
}