CC_FILE_ERROR FBXFilter::saveToFile(ccHObject* entity, QString filename, SaveParameters& parameters) { if (!entity) return CC_FERR_BAD_ARGUMENT; std::vector<ccGenericMesh*> meshes; if (entity->isKindOf(CC_TYPES::MESH)) { meshes.push_back(static_cast<ccGenericMesh*>(entity)); } else if (entity->isA(CC_TYPES::HIERARCHY_OBJECT)) { for (unsigned i=0; i<entity->getChildrenNumber(); ++i) { ccHObject* child = entity->getChild(i); if (child->isKindOf(CC_TYPES::MESH)) meshes.push_back(static_cast<ccGenericMesh*>(child)); } } if (meshes.empty()) { return CC_FERR_NO_SAVE; } //The first thing to do is to create the FBX Manager which is the object allocator for almost all the classes in the SDK FbxManager* lSdkManager = FbxManager::Create(); if( !lSdkManager ) { ccLog::Warning("[FBX] Error: Unable to create FBX Manager!"); return CC_FERR_CONSOLE_ERROR; } else { ccLog::Print("[FBX] Autodesk FBX SDK version %s", lSdkManager->GetVersion()); } try { //Create an IOSettings object. This object holds all import/export settings. FbxIOSettings* ios = FbxIOSettings::Create(lSdkManager, IOSROOT); lSdkManager->SetIOSettings(ios); //Load plugins from the executable directory (optional) //FbxString lPath = FbxGetApplicationDirectory(); //lSdkManager->LoadPluginsDirectory(lPath.Buffer()); //Create an FBX scene. This object holds most objects imported/exported from/to files. FbxScene* lScene = FbxScene::Create(lSdkManager, "My Scene"); if( !lScene ) { ccLog::Warning("[FBX] Error: Unable to create FBX scene!"); return CC_FERR_CONSOLE_ERROR; } // create scene info { FbxDocumentInfo* sceneInfo = FbxDocumentInfo::Create(lSdkManager,"SceneInfo"); sceneInfo->mTitle = qPrintable(QString("Mesh: ") + (meshes.size() == 1 ? meshes[0]->getName() : QString("Multiple meshes"))); sceneInfo->mAuthor = "CloudCompare"; sceneInfo->mRevision = "rev. 1.0"; sceneInfo->mKeywords = "cloudcompare mesh"; // we need to add the sceneInfo before calling AddThumbNailToScene because // that function is asking the scene for the sceneInfo. lScene->SetSceneInfo(sceneInfo); } //create thumbnail //{ // FbxThumbnail* lThumbnail = FbxThumbnail::Create(lScene,""); // lThumbnail->SetDataFormat(FbxThumbnail::eRGB_24); // lThumbnail->SetSize(FbxThumbnail::e64x64); // lThumbnail->SetThumbnailImage(cSceneThumbnail); // if (lScene->GetSceneInfo()) // { // lScene->GetSceneInfo()->SetSceneThumbnail(lThumbnail); // } //} // Build the node tree. FbxNode* lRootNode = lScene->GetRootNode(); { for (size_t i=0; i<meshes.size(); ++i) { FbxNode* meshNode = ToFbxMesh(meshes[i],lScene,filename,i); if (meshNode) lRootNode->AddChild(meshNode); else ccLog::Warning(QString("[FBX] Failed to convert mesh '%1' to FBX mesh/node!").arg(meshes[i]->getName())); } } int fileFormat = -1; //Display a combox box to let the user choose the export file format { FbxManager* pSdkManager = FbxManager::GetDefaultManager(); int lFormatCount = pSdkManager ? pSdkManager->GetIOPluginRegistry()->GetWriterFormatCount() : 0; if (lFormatCount > 0) { if (s_defaultOutputFormat.isEmpty()) { try { QMessageBox msgBox(QMessageBox::Question,"FBX format","Choose output format:"); QMap<QAbstractButton*,int> buttons; for (int lFormatIndex=0; lFormatIndex<lFormatCount; lFormatIndex++) { if (pSdkManager->GetIOPluginRegistry()->WriterIsFBX(lFormatIndex)) { FbxString lDesc = pSdkManager->GetIOPluginRegistry()->GetWriterFormatDescription(lFormatIndex); QPushButton *button = msgBox.addButton(lDesc.Buffer(), QMessageBox::AcceptRole); buttons[button] = lFormatIndex; } } msgBox.exec(); //get the right format fileFormat = buttons[msgBox.clickedButton()]; } catch(...) { } } else { //try to find the default output format as set by the user for (int lFormatIndex=0; lFormatIndex<lFormatCount; lFormatIndex++) { if (pSdkManager->GetIOPluginRegistry()->WriterIsFBX(lFormatIndex)) { FbxString lDesc = pSdkManager->GetIOPluginRegistry()->GetWriterFormatDescription(lFormatIndex); QString sanitizedDesc = SanitizeFBXFormatString(lDesc.Buffer()); if (s_defaultOutputFormat == sanitizedDesc) { ccLog::Print(QString("[FBX] Default output file format: %1").arg(sanitizedDesc)); fileFormat = lFormatIndex; break; } } } //if we failed to find the specified file format, warn the user and display the list of supported formats if (fileFormat < 0) { ccLog::Warning(QString("[FBX] File format '%1' not supported").arg(s_defaultOutputFormat)); ccLog::Print("[FBX] Supported output formats:"); for (int lFormatIndex=0; lFormatIndex<lFormatCount; lFormatIndex++) { if (pSdkManager->GetIOPluginRegistry()->WriterIsFBX(lFormatIndex)) { FbxString lDesc = pSdkManager->GetIOPluginRegistry()->GetWriterFormatDescription(lFormatIndex); ccLog::Print(QString("\t- %1").arg(SanitizeFBXFormatString(lDesc.Buffer()))); } } } } } } // Save the scene. bool lResult = SaveScene(lSdkManager, lScene, qPrintable(filename),fileFormat); // Destroy all objects created by the FBX SDK. if( lSdkManager ) lSdkManager->Destroy(); return lResult ? CC_FERR_NO_ERROR : CC_FERR_CONSOLE_ERROR; } catch(...) { ccLog::Warning("[FBX] FBX SDK has thrown an unknown exception!"); return CC_FERR_THIRD_PARTY_LIB_EXCEPTION; } }
/** * Print an attribute. */ void PrintAttribute(FbxNodeAttribute* pAttribute) { if(!pAttribute) return; FbxString typeName = GetAttributeTypeName(pAttribute->GetAttributeType()); FbxString attrName = pAttribute->GetName(); PrintTabs(); // Note: to retrieve the character array of a FbxString, use its Buffer() method. printf("<attribute type='%s' name='%s'/>\n", typeName.Buffer(), attrName.Buffer()); }
void FBXSceneImporter::PrintAttribute(FbxNodeAttribute* pAttribute) { if (!pAttribute) { return; } FbxString typeName = GetAttributeTypeName(pAttribute->GetAttributeType()); FbxString attrName = pAttribute->GetName(); PrintTabs(); // Note: to retrieve the character array of a FbxString, use its Buffer() method. myfile << "<attribute type= " << typeName.Buffer() << " name= " << attrName.Buffer() << " />\n"; }
fbxSdkMgr::fbxSdkMgr () : _sdkManager(FbxManager::Create ()) { assert( _sdkManager ) ; FbxIOSettings *pIOSettings =FbxIOSettings::Create (_sdkManager, IOSROOT) ; //pIOSettings->SetBoolProp (IMP_FBX_CONSTRAINT, true) ; //pIOSettings->SetBoolProp (IMP_FBX_CONSTRAINT_COUNT, true) ; //pIOSettings->SetBoolProp (IMP_FBX_MATERIAL, true) ; //pIOSettings->SetBoolProp (IMP_FBX_TEXTURE, true) ; //pIOSettings->SetBoolProp (IMP_FBX_LINK, true) ; //pIOSettings->SetBoolProp (IMP_FBX_SHAPE, true) ; //pIOSettings->SetBoolProp (IMP_FBX_GOBO, false) ; //pIOSettings->SetBoolProp (IMP_FBX_ANIMATION, true) ; //pIOSettings->SetBoolProp (IMP_FBX_GLOBAL_SETTINGS, true) ; pIOSettings->SetBoolProp (EXP_FBX_EMBEDDED, false) ; _sdkManager->SetIOSettings (pIOSettings) ; // Load plug-ins from the executable directory FbxString path =FbxGetApplicationDirectory () ; #if defined(_WIN64) || defined(_WIN32) FbxString extension ("dll") ; #elif defined(__APPLE__) FbxString extension ("dylib") ; #else // __linux FbxString extension ("so") ; #endif _sdkManager->LoadPluginsDirectory (path.Buffer ()/*, extension.Buffer ()*/) ; _sdkManager->FillIOSettingsForReadersRegistered (*pIOSettings) ; _sdkManager->FillIOSettingsForWritersRegistered (*pIOSettings) ; }
String^ FBXIOFileHeaderInfo::Creator::get() { FbxString creatorInformation = this->instance->mCreator; const char* creatorBuffer = creatorInformation.Buffer(); return StringHelper::ToManaged(creatorBuffer); }
bool FbxSerializer::initFBXObjects() { // 创建FBX SDK Manager destroyFBXObjects(); mFbxManager = FbxManager::Create(); if (mFbxManager == nullptr) { T3D_LOG_ERROR("Unable to create FBX Manager !"); return false; } // 创建IOSettings object FbxIOSettings *pIOSettings = FbxIOSettings::Create(mFbxManager, IOSROOT); mFbxManager->SetIOSettings(pIOSettings); // Load plugins from the executable directory (optional) FbxString path = FbxGetApplicationDirectory(); mFbxManager->LoadPluginsDirectory(path.Buffer()); // Create an FBX scene. This object holds most objects imported/exported from/to files. mFbxScene = FbxScene::Create(mFbxManager, "My Scene"); if (mFbxScene == nullptr) { T3D_LOG_ERROR("Unable to create FBX scene !"); return false; } return true; }
// PRIVATE FUNCTION-------------------------------------------------------------------------------------------------------------------------- void FBXReader::initializeSdkObjects(FbxManager*& fbxManager, FbxScene*& scene) { //The first thing to do is to create the FBX Manager which is the object allocator for almost all the classes in the SDK fbxManager = FbxManager::Create(); if (!fbxManager) { FBXSDK_printf("Error: Unable to create FBX Manager!\n"); exit(1); } else FBXSDK_printf("Autodesk FBX SDK version %s\n", fbxManager->GetVersion()); //Create an IOSettings object. This object holds all import/export settings. FbxIOSettings* ios = FbxIOSettings::Create(fbxManager, IOSROOT); fbxManager->SetIOSettings(ios); //Load plugins from the executable directory (optional) FbxString lPath = FbxGetApplicationDirectory(); fbxManager->LoadPluginsDirectory(lPath.Buffer()); //Create an FBX scene. This object holds most objects imported/exported from/to files. scene = FbxScene::Create(fbxManager, "My Scene"); if (!scene) { FBXSDK_printf("Error: Unable to create FBX scene!\n"); exit(1); } }
bool FbxParser::Initialize() { if(mpFbxManager) return true; mpFbxManager = FbxManager::Create(); if( !mpFbxManager ) { return false ; } //Create an IOSettings object. This object holds all import/export settings. FbxIOSettings* ios = FbxIOSettings::Create(mpFbxManager, IOSROOT); mpFbxManager->SetIOSettings(ios); //Load plugins from the executable directory (optional) FbxString lPath = FbxGetApplicationDirectory(); mpFbxManager->LoadPluginsDirectory(lPath.Buffer()); //Create an FBX scene. This object holds most objects imported/exported from/to files. mpFbxScene = FbxScene::Create(mpFbxManager, "My Scene"); if( !mpFbxScene ) { mpFbxManager->Destroy(); mpFbxManager = NULL; return false ; } return true; }
void Node::WriteString( FILE* _pFile, const FbxString& _String ) { int TextSize = (int) _String.GetLen(); WriteInt( _pFile, TextSize ); const char* pText = _String.Buffer(); fwrite( pText, sizeof(char), TextSize, _pFile ); }
web::json::value gltfWriter::WriteTexture (FbxTexture *pTexture) { utility::string_t name =utility::conversions::to_string_t (pTexture->GetNameWithoutNameSpacePrefix ().Buffer ()) ; utility::string_t uri =utility::conversions::to_string_t (FbxCast<FbxFileTexture> (pTexture)->GetRelativeFileName ()) ; web::json::value image =web::json::value::object ({{ name, web::json::value::object ({ { U("name"), web::json::value::string (name) }, { U("uri"), web::json::value::string (uri) } }) } }) ; if ( GetIOSettings ()->GetBoolProp (IOSN_FBX_GLTF_EMBEDMEDIA, false) ) { // data:[<mime type>][;charset=<charset>][;base64],<encoded data> FbxString imageFile =FbxCast<FbxFileTexture> (pTexture)->GetFileName () ; image [name] [U("uri")] =web::json::value::string (IOglTF::dataURI (utility::conversions::to_string_t (imageFile.Buffer ()))) ; } /*else*/ if ( GetIOSettings ()->GetBoolProp (IOSN_FBX_GLTF_COPYMEDIA, false) ) { FbxString path =FbxPathUtils::GetFolderName (utility::conversions::to_utf8string (_fileName).c_str ()) ; #if defined(_WIN32) || defined(_WIN64) path +="\\" ; #else path +="/" ; #endif FbxString imageFile =FbxCast<FbxFileTexture> (pTexture)->GetFileName () ; std::ifstream src (imageFile.Buffer (), std::ios::binary) ; std::ofstream dst (path + FbxPathUtils::GetFileName (imageFile), std::ios::binary) ; dst << src.rdbuf () ; } utility::string_t texName =createTextureName (pTexture->GetNameWithoutNameSpacePrefix ()) ; utility::string_t samplerName =createSamplerName (pTexture->GetNameWithoutNameSpacePrefix ()) ; web::json::value textureDef =web::json::value::object ({ { U("name"), web::json::value::string (texName) }, { U("format"), web::json::value::number ((int)IOglTF::RGBA) }, // todo { U("internalFormat"), web::json::value::number ((int)IOglTF::RGBA) }, // todo { U("sampler"), web::json::value::string (samplerName) }, // todo do I need one everytime { U("source"), web::json::value::string (name) }, { U("target"), web::json::value::number ((int)IOglTF::TEXTURE_2D) }, { U("type"), web::json::value::number ((int)IOglTF::UNSIGNED_BYTE) } // todo }) ; web::json::value texture =web::json::value::object ({{ texName, textureDef }}) ; //TODO: Shall try to find a similar sampler defined already vs create one each time? web::json::value samplerDef =web::json::value::object ({ { U("name"), web::json::value::string (samplerName) }, { U("magFilter"), web::json::value::number ((int)IOglTF::LINEAR) }, { U("minFilter"), web::json::value::number ((int)IOglTF::LINEAR_MIPMAP_LINEAR) }, { U("wrapS"), web::json::value::number ((int)(pTexture->WrapModeU.Get () == FbxTexture::eRepeat ? IOglTF::REPEAT : IOglTF::CLAMP_TO_EDGE)) }, { U("wrapT"), web::json::value::number ((int)(pTexture->WrapModeV.Get () == FbxTexture::eRepeat ? IOglTF::REPEAT : IOglTF::CLAMP_TO_EDGE)) } }) ; return (web::json::value::object ({ { U("images"), image }, { U("textures"), web::json::value::object ({{ texName, textureDef }}) }, { U("samplers"), web::json::value::object ({{ samplerName, samplerDef }}) } })) ; }
//=============================================================================================================================== bool FBXLoader::LoadScene() { LARGE_INTEGER start; LARGE_INTEGER end; int fileMinor, fileRevision; int sdkMajor, sdkMinor, sdkRevision; int fileFormat; QueryPerformanceCounter(&start); { FbxString filePath = FbxGetApplicationDirectory(); m_pFBXManager->LoadPluginsDirectory(filePath.Buffer()); FbxManager::GetFileFormatVersion(sdkMajor, sdkMinor, sdkRevision); FbxImporter* pImporter = FbxImporter::Create(m_pFBXManager, ""); m_pFbxScene = FbxScene::Create(m_pFBXManager, ""); if(!m_pFBXManager->GetIOPluginRegistry()->DetectReaderFileFormat(mInputFilePath.c_str(), fileFormat)) { //Unrecognizable file format. Try to fall back on FbxImorter::eFBX_BINARY fileFormat = m_pFBXManager->GetIOPluginRegistry()->FindReaderIDByDescription("FBX binary (*.fbx)"); } bool bSuccess = pImporter->Initialize(mInputFilePath.c_str(), fileFormat, m_pFBXManager->GetIOSettings()); pImporter->GetFileVersion(fileMinor, fileMinor, fileRevision); if(!bSuccess) { printf( "ERROR %s : %d FbxImporter Initialize failed!\n", __FILE__, __LINE__ ); return false; } bSuccess = pImporter->Import(m_pFbxScene); if (!bSuccess) { return false; } pImporter->Destroy(); // Very Important!! Triangulate all meshes in the scene // DirectX must have this to render the mesh properly FbxGeometryConverter clsConv(m_pFBXManager); bool triangulate = clsConv.Triangulate(m_pFbxScene, true); } QueryPerformanceCounter(&end); float finalTime = ((end.QuadPart - start.QuadPart) / static_cast<float>(mCPUFreq.QuadPart)); string finalTimeStr = ZShadeSandboxGlobal::Convert::ConvertToString<float>(finalTime); outFile << "Loading FBX File: " << finalTimeStr << "s\n"; }
void Model::processAttribute(FbxNodeAttribute *attribute, int level, Data &model) { if (!attribute) return; FbxString typeName = getAttributeTypeName(attribute->GetAttributeType()); FbxString attrName = attribute->GetName(); LOG(INFO) << "Attribute " << typeName.Buffer() << " Name " << attrName; switch (attribute->GetAttributeType()) { case FbxNodeAttribute::eSkeleton: return; case FbxNodeAttribute::eMesh: processMesh(attribute->GetNode()->GetMesh(), model); case FbxNodeAttribute::eCamera: return; case FbxNodeAttribute::eLight: return; } }
void Utilities::PrintMatrix(FbxMatrix& inMatrix) { FbxString lMatrixValue; for (int k = 0; k<4; ++k) { FbxVector4 lRow = inMatrix.GetRow(k); char lRowValue[1024]; FBXSDK_sprintf(lRowValue, 1024, "%9.4f %9.4f %9.4f %9.4f\n", lRow[0], lRow[1], lRow[2], lRow[3]); lMatrixValue += FbxString(" ") + FbxString(lRowValue); } std::cout << lMatrixValue.Buffer(); }
void processAttribute(FbxNodeAttribute * attribute, GameObject * go) { if (!attribute) return; FbxString typeName = GetAttributeTypeName(attribute->GetAttributeType()); FbxString attrName = attribute->GetName(); PrintTabs(); std::cout << "Attribute " << typeName.Buffer() << " Name " << attrName << std::endl; switch (attribute->GetAttributeType()) { case FbxNodeAttribute::eSkeleton: return; case FbxNodeAttribute::eMesh: processMesh(attribute->GetNode()->GetMesh(),go); case FbxNodeAttribute::eCamera: return; case FbxNodeAttribute::eLight: return; } }
void Tools::DisplayCamera::DisplayBackgroundProperties( FbxCamera *i_camera ) { DisplayCommon::DisplayString( " Background Properties" ); DisplayCommon::DisplayString( " Background File Name: \"", (char *) i_camera->GetBackgroundFileName(), "\"" ); const char* backgroundDisplayModes[] = { "Disabled", "Always", "When Media" }; DisplayCommon::DisplayString( " Background Display Mode: ", backgroundDisplayModes[i_camera->ViewFrustumBackPlaneMode.Get()] ); DisplayCommon::DisplayBool( " Foreground Matte Threshold Enable: ", i_camera->ShowFrontplate.Get() ); // This option is only relevant if background drawing mode is set to eFOREGROUND or eBACKGROUND_AND_FOREGROUND. if( i_camera->ForegroundOpacity.Get() ) { DisplayCommon::DisplayDouble( " Foreground Matte Threshold: ", i_camera->BackgroundAlphaTreshold.Get() ); } FbxString backgroundPlacementOptions; if( i_camera->GetBackPlateFitImage() ) { backgroundPlacementOptions += " Fit,"; } if( i_camera->GetBackPlateCenter() ) { backgroundPlacementOptions += " Center,"; } if( i_camera->GetBackPlateKeepRatio() ) { backgroundPlacementOptions += " Keep Ratio,"; } if( i_camera->GetBackPlateCrop() ) { backgroundPlacementOptions += " Crop,"; } if( !backgroundPlacementOptions.IsEmpty() ) { FbxString lString = backgroundPlacementOptions.Left( backgroundPlacementOptions.GetLen() - 1 ); DisplayCommon::DisplayString( " Background Placement Options: ",lString.Buffer() ); } DisplayCommon::DisplayDouble( " Background Distance: ", i_camera->BackPlaneDistance.Get() ); const char* cameraBackgroundDistanceModes[] = { "Relative to Interest", "Absolute from Camera" }; DisplayCommon::DisplayString( " Background Distance Mode: ", cameraBackgroundDistanceModes[i_camera->BackPlaneDistanceMode.Get()] ); }
static void GetCustomVisionData(FbxNode* fbxNode, hkStringPtr& userPropertiesStr) { userPropertiesStr = ""; for(FbxProperty prop = fbxNode->GetFirstProperty(); prop.IsValid(); prop = fbxNode->GetNextProperty(prop)) { EFbxType type = prop.GetPropertyDataType().GetType(); if (type == eFbxString) { FbxString propertyData = prop.Get<FbxString>(); const char* text = propertyData.Buffer(); if (!hkString::strNcasecmp(text, "vision", 6)) { userPropertiesStr = text; break; } } } }
bool LoaderFbx::createFbxManager() { bool success = true; fbxManager_ = FbxManager::Create(); if(!fbxManager_) { success = false; ERROR_MESSAGEBOX("LoaderFbx::createFbxManager | fbxManager_ could not be created!"); } else { FbxIOSettings* fbxIOSettings = FbxIOSettings::Create(fbxManager_, IOSROOT); fbxManager_->SetIOSettings(fbxIOSettings); FbxString path = FbxGetApplicationDirectory(); fbxManager_->LoadPluginsDirectory(path.Buffer()); } return success; }
void Tools::DisplayCommon::DisplayDouble( const char* pHeader, double pValue, const char* pSuffix ) { std::ofstream out; out.open( dumpInfoFilename->c_str(), std::ios::app ); if( out.fail() ) return; FbxString string; FbxString floatValue = (float) pValue; floatValue = pValue <= -HUGE_VAL ? "-INFINITY" : floatValue.Buffer(); floatValue = pValue >= HUGE_VAL ? "INFINITY" : floatValue.Buffer(); string = pHeader; string += floatValue; string += pSuffix; string += "\n"; //FBXSDK_printf( string ); out << string; out.close(); }
//------------------------------------------------------------------------- // //------------------------------------------------------------------------- bool UnFbx::FFbxImporter::CreateAndLinkExpressionForMaterialProperty( FbxSurfaceMaterial& FbxMaterial, UMaterial* UnrealMaterial, const char* MaterialProperty , FExpressionInput& MaterialInput, bool bSetupAsNormalMap, TArray<FString>& UVSet ) { bool bCreated = false; FbxProperty FbxProperty = FbxMaterial.FindProperty( MaterialProperty ); if( FbxProperty.IsValid() ) { int32 LayeredTextureCount = FbxProperty.GetSrcObjectCount(FbxLayeredTexture::ClassId); if (LayeredTextureCount>0) { UE_LOG(LogFbxMaterialImport, Warning,TEXT("Layered TEXTures are not supported (material %s)"),ANSI_TO_TCHAR(FbxMaterial.GetName())); } else { int32 TextureCount = FbxProperty.GetSrcObjectCount(FbxTexture::ClassId); if (TextureCount>0) { for(int32 TextureIndex =0; TextureIndex<TextureCount; ++TextureIndex) { FbxFileTexture* FbxTexture = FbxProperty.GetSrcObject(FBX_TYPE(FbxFileTexture), TextureIndex); // create an unreal texture asset UTexture* UnrealTexture = ImportTexture(FbxTexture, bSetupAsNormalMap); if (UnrealTexture) { // and link it to the material UMaterialExpressionTextureSample* UnrealTextureExpression = ConstructObject<UMaterialExpressionTextureSample>( UMaterialExpressionTextureSample::StaticClass(), UnrealMaterial ); UnrealMaterial->Expressions.Add( UnrealTextureExpression ); MaterialInput.Expression = UnrealTextureExpression; UnrealTextureExpression->Texture = UnrealTexture; UnrealTextureExpression->SamplerType = bSetupAsNormalMap ? SAMPLERTYPE_Normal : SAMPLERTYPE_Color; // add/find UVSet and set it to the texture FbxString UVSetName = FbxTexture->UVSet.Get(); FString LocalUVSetName = ANSI_TO_TCHAR(UVSetName.Buffer()); int32 SetIndex = UVSet.Find(LocalUVSetName); UMaterialExpressionTextureCoordinate* MyCoordExpression = ConstructObject<UMaterialExpressionTextureCoordinate>( UMaterialExpressionTextureCoordinate::StaticClass(), UnrealMaterial ); UnrealMaterial->Expressions.Add( MyCoordExpression ); MyCoordExpression->CoordinateIndex = (SetIndex >= 0)? SetIndex: 0; UnrealTextureExpression->Coordinates.Expression = MyCoordExpression; if ( !bSetupAsNormalMap ) { UnrealMaterial->BaseColor.Expression = UnrealTextureExpression; } else { UnrealMaterial->Normal.Expression = UnrealTextureExpression; } bCreated = true; } } } if (MaterialInput.Expression) { TArray<FExpressionOutput> Outputs = MaterialInput.Expression->GetOutputs(); FExpressionOutput* Output = Outputs.GetTypedData(); MaterialInput.Mask = Output->Mask; MaterialInput.MaskR = Output->MaskR; MaterialInput.MaskG = Output->MaskG; MaterialInput.MaskB = Output->MaskB; MaterialInput.MaskA = Output->MaskA; } } } return bCreated; }
//=============================================================================================================================== void FBXLoader::LoadJointsAndAnimation(FbxNode* inNode) { // This is how each subset gets its bone/joint for animation FBXSubsets* subset = mSubsets[iCurrentSubset]; FbxMesh* mesh = inNode->GetMesh(); uint32 numOfDeformers = mesh->GetDeformerCount(); FbxAMatrix geomTrans = ZShadeSandboxMesh::FBXHelper::GetGeometryTransformation(inNode); // A deformer contains clusters. // A cluster contains a link, which is a joint. // Normally, There is only one deformer in a mesh but Maya has many types. for (uint32 deformerIndex = 0; deformerIndex < numOfDeformers; ++deformerIndex) { // Lets see if this deformer is a skin FbxSkin* skin = reinterpret_cast<FbxSkin*>(mesh->GetDeformer(deformerIndex, FbxDeformer::eSkin)); if (!skin) continue; uint32 numOfClusters = skin->GetClusterCount(); for (uint32 clusterIndex = 0; clusterIndex < numOfClusters; ++clusterIndex) { FbxCluster* cluster = skin->GetCluster(clusterIndex); string jointName = cluster->GetLink()->GetName(); uint32 jointIndex = FindJointIndexUsingName(jointName); subset->mJoints.push_back(jointIndex); FbxAMatrix transform; FbxAMatrix transformLink; FbxAMatrix globalBindposeInverse; // The transformation of the mesh at binding time cluster->GetTransformMatrix(transform); // The transformation of the cluster (joint) at binding time from joint space to world space cluster->GetTransformLinkMatrix(transformLink); globalBindposeInverse = transformLink.Inverse() * transform * geomTrans; // Update skeletal information mSkeleton.joints[jointIndex].globalBindposeInverse = globalBindposeInverse; mSkeleton.joints[jointIndex].node = cluster->GetLink(); // Associate each joint with the control points it affects uint32 numOfIndices = cluster->GetControlPointIndicesCount(); for (uint32 i = 0; i < numOfIndices; ++i) { ZShadeSandboxMesh::BlendingIndexWeightPair currBlendingIndexWeightPair; currBlendingIndexWeightPair.blendingIndex = jointIndex; currBlendingIndexWeightPair.blendingWeight = cluster->GetControlPointWeights()[i]; mControlPoints[cluster->GetControlPointIndices()[i]]->blendingInfo.push_back(currBlendingIndexWeightPair); } // Animation information FbxAnimStack* animStack = m_pFbxScene->GetSrcObject<FbxAnimStack>(0); FbxString animStackName = animStack->GetName(); mAnimationName = animStackName.Buffer(); FbxTakeInfo* takeInfo = m_pFbxScene->GetTakeInfo(animStackName); FbxTime start = takeInfo->mLocalTimeSpan.GetStart(); FbxTime end = takeInfo->mLocalTimeSpan.GetStop(); mAnimationLength = end.GetFrameCount(FbxTime::eFrames24) - start.GetFrameCount(FbxTime::eFrames24) + 1; FBXKeyframe** anim = &mSkeleton.joints[jointIndex].animation; for (FbxLongLong i = start.GetFrameCount(FbxTime::eFrames24); i <= end.GetFrameCount(FbxTime::eFrames24); ++i) { FbxTime time; time.SetFrame(i, FbxTime::eFrames24); *anim = new FBXKeyframe(); (*anim)->frameNum = i; FbxAMatrix currentTransformOffset = inNode->EvaluateGlobalTransform(time) * geomTrans; (*anim)->globalTransform = currentTransformOffset.Inverse() * cluster->GetLink()->EvaluateGlobalTransform(time); anim = &((*anim)->next); } } } // Some control points have less than 4 joints // For a normal renderer, there are usually 4 joints ZShadeSandboxMesh::BlendingIndexWeightPair currBlendingIndexWeightPair; currBlendingIndexWeightPair.blendingIndex = 0; currBlendingIndexWeightPair.blendingWeight = 0; for (auto itr = mControlPoints.begin(); itr != mControlPoints.end(); ++itr) { for (unsigned int i = itr->second->blendingInfo.size(); i <= 4; ++i) { itr->second->blendingInfo.push_back(currBlendingIndexWeightPair); } } }
void FBXScene::ProcessAnimations(FbxScene* pScene) { m_pAnimationController = new AnimationController(); FbxNode* pRootNode = pScene->GetRootNode(); if(!pRootNode) return; float fFrameRate = (float)FbxTime::GetFrameRate(pScene->GetGlobalSettings().GetTimeMode()); FbxArray<FbxString*> takeArray; FbxDocument* pDocument = FbxCast<FbxDocument>(pScene); // dynamic_cast<FbxDocument*>(pScene); if( pDocument ) pDocument->FillAnimStackNameArray(takeArray); for( int i = 0; i < takeArray.GetCount(); ++i ) { FbxString* takeName = takeArray.GetAt(i); if( std::string(takeName->Buffer()) != "Default" ) { /// ARRRGHHH SÄTTER ALLTID FÖRSTA HÄR!!!!!!!!!!!!!!!!!! FbxTakeInfo* lCurrentTakeInfo = pScene->GetTakeInfo(takeName->Buffer()); FbxAnimStack* lAnimStack = FbxCast<FbxAnimStack>(pScene->GetSrcObject<FbxAnimStack>(i)); pScene->GetEvaluator()->SetContext(lAnimStack); FbxTime KStart; FbxTime KStop; if(lCurrentTakeInfo) { KStart = lCurrentTakeInfo->mLocalTimeSpan.GetStart(); KStop = lCurrentTakeInfo->mLocalTimeSpan.GetStop(); } else { // Take the time line value FbxTimeSpan lTimeLineTimeSpan; pScene->GetGlobalSettings().GetTimelineDefaultTimeSpan(lTimeLineTimeSpan); KStart = lTimeLineTimeSpan.GetStart(); KStop = lTimeLineTimeSpan.GetStop(); } float fStart = (float)KStart.GetSecondDouble(); float fStop = (float)KStop.GetSecondDouble(); if( fStart < fStop ) { int nKeyFrames = int((fStop-fStart)*fFrameRate); Animation* pAnimation = new Animation(takeName->Buffer(), nKeyFrames, fFrameRate); m_pAnimationController->AddAnimation(pAnimation); ProcessAnimation(pRootNode, takeName->Buffer(), fFrameRate, fStart, fStop); } } delete takeName; } takeArray.Clear(); }
bool SceneConverter::convert() { // // Construt the scene // FbxNode *node = m_scene->GetRootNode(); std::list<FbxNode *> nodes; std::map<FbxNode *, SceneNode *> fbxNode2SceneNodes; Scene scene; nodes.push_back(node); SceneNode *sceneNode = makeSceneNode(node); scene.addNode(sceneNode); fbxNode2SceneNodes.insert(std::make_pair(node, sceneNode)); while (!nodes.empty()) { FbxNode *ret = nodes.front(); nodes.pop_front(); for (int i = 0; i < ret->GetChildCount(); i++) { FbxNode *child = ret->GetChild(i); // Only output visible nodes. if (child->GetVisibility() && child->Show.Get()) { SceneNode *sceneNode = makeSceneNode(child); if (sceneNode != NULL) { if (sceneNode->type == "camera") { // The first camera will be the main camera of the scene scene.setCamera(sceneNode); } scene.addNode(sceneNode, fbxNode2SceneNodes[ret]); fbxNode2SceneNodes.insert(std::make_pair(child, sceneNode)); } nodes.push_back(child); } } } // Create a camera if it is not included in FBX. The camera is evaluated // using the bounding box of all visible nodes. if (m_numCameras == 0) { FbxVector4 rootBboxMin; FbxVector4 rootBboxMax; FbxVector4 rootBboxCenter; rootBboxMin = FbxVector4(FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX); rootBboxMax = FbxVector4(-FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX); FbxNode *node = m_scene->GetRootNode(); nodes.push_back(node); while (!nodes.empty()) { FbxNode *ret = nodes.front(); nodes.pop_front(); for (int i = 0; i < ret->GetChildCount(); i++) { FbxNode *child = ret->GetChild(i); nodes.push_back(child); } if (ret->GetChildCount() == 0 && ret->GetVisibility() && ret->Show.Get() && ret->GetMesh() != NULL) { FbxVector4 bboxMin; FbxVector4 bboxMax; FbxVector4 bboxCenter; ret->EvaluateGlobalBoundingBoxMinMaxCenter(bboxMin, bboxMax, bboxCenter); rootBboxMin[0] = std::min(rootBboxMin[0], bboxMin[0]); rootBboxMin[1] = std::min(rootBboxMin[1], bboxMin[1]); rootBboxMin[2] = std::min(rootBboxMin[2], bboxMin[2]); rootBboxMax[0] = std::max(rootBboxMax[0], bboxMax[0]); rootBboxMax[1] = std::max(rootBboxMax[1], bboxMax[1]); rootBboxMax[2] = std::max(rootBboxMax[2], bboxMax[2]); } } rootBboxCenter = (rootBboxMin + rootBboxMax) / 2; FbxVector4 rootBboxSize = rootBboxMax - rootBboxMin; SceneNode *sceneNode = new SceneNode(); sceneNode->type = FbxString("camera"); sceneNode->attributes.push_back(std::make_pair(FbxString("name"), FbxString("camera"))); sceneNode->attributes.push_back(std::make_pair(FbxString("fixed"), FbxString("true"))); double diag = sqrt(rootBboxSize[0] * rootBboxSize[0] + rootBboxSize[1] * rootBboxSize[1] + rootBboxSize[2] * rootBboxSize[2]) * 0.5; double eye = diag / tan(15.0 * FBXSDK_PI_DIV_180); double position[3]; double up[3]; double znear; double zfar; znear = eye - diag - 1.0f; zfar = eye + diag + 1.0f; if (rootBboxSize[0] <= rootBboxSize[1] && rootBboxSize[0] <= rootBboxSize[2]) { position[0] = eye + rootBboxCenter[0]; position[1] = rootBboxCenter[1]; position[2] = rootBboxCenter[2]; up[0] = 0; up[1] = 1; up[2] = 0; } else if (rootBboxSize[1] <= rootBboxSize[0] && rootBboxSize[1] <= rootBboxSize[2]) { position[0] = rootBboxCenter[0]; position[1] = eye + rootBboxCenter[1]; position[2] = rootBboxCenter[2]; up[0] = 0; up[1] = 0; up[2] = 1; } else { position[0] = rootBboxCenter[0]; position[1] = rootBboxCenter[1]; position[2] = eye + rootBboxCenter[2]; up[0] = 0; up[1] = 1; up[2] = 0; } char lookat[1024]; char perspective[1024]; FBXSDK_sprintf(lookat, 1024, "eye:%8.5f,%8.5f,%8.5f,center:%8.5f,%8.5f,%8.5f,up:%8.5f,%8.5f,%8.5f", (float)position[0], (float)position[1], (float)position[2], (float)rootBboxCenter[0], (float)rootBboxCenter[1], (float)rootBboxCenter[2], (float)up[0], (float)up[1], (float)up[2]); sceneNode->attributes.push_back(std::make_pair(FbxString("lookat"), FbxString(lookat))); FBXSDK_sprintf(perspective, 1024, "perspective,fov:%8.5f,aspect:-1,znear:%8.5f,zfar:%8.5f", 30.0f, (float)znear, (float)zfar); sceneNode->attributes.push_back(std::make_pair(FbxString("projection"), FbxString(perspective))); scene.setCamera(sceneNode); scene.addNode(sceneNode, scene.root()); } // // Output the file. // //FbxString outputFilename = FbxPathUtils::GetFileName(m_arguments->FBXFileName.Buffer()).Lower(); //outputFilename.FindAndReplace(".fbx", ".psc"); FbxString outputFilename("scene.psc"); FbxString path = FbxPathUtils::Bind(m_arguments->outputFolder, outputFilename.Buffer()); bool ret = scene.output(path.Buffer()); if (!ret) { FBXSDK_printf("Exporting failed!\n\n"); } return ret; }
bool FBXReader::loadScene(FbxManager* fbxManager, FbxDocument* scene, string fileName) { int lFileMajor, lFileMinor, lFileRevision; int lSDKMajor, lSDKMinor, lSDKRevision; //int lFileFormat = -1; 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(fbxManager, ""); // Initialize the importer by providing a filename. const bool lImportStatus = lImporter->Initialize(fileName.c_str(), -1, fbxManager->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", fileName, 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", fileName, 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"); } // Set the import states. By default, the import states are always set to // true. The code below shows how to change these states. IOS_REF.SetBoolProp(IMP_FBX_MATERIAL, true); IOS_REF.SetBoolProp(IMP_FBX_TEXTURE, true); IOS_REF.SetBoolProp(IMP_FBX_LINK, true); IOS_REF.SetBoolProp(IMP_FBX_SHAPE, true); IOS_REF.SetBoolProp(IMP_FBX_GOBO, true); IOS_REF.SetBoolProp(IMP_FBX_ANIMATION, true); IOS_REF.SetBoolProp(IMP_FBX_GLOBAL_SETTINGS, true); } // Import the scene. lStatus = lImporter->Import(scene); if (lStatus == false && lImporter->GetStatus().GetCode() == FbxStatus::ePasswordError) { FBXSDK_printf("Please enter password: "******"%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(scene); if (lStatus == false && lImporter->GetStatus().GetCode() == FbxStatus::ePasswordError) { FBXSDK_printf("\nPassword is wrong, import aborted.\n"); } } // Destroy the importer. lImporter->Destroy(); return lStatus; }
void Material::ExportMaterials(FbxScene* scene, FbxMesh* mesh, const ImporterMesh& importedMesh, const ImporterMaterial* importedMaterials) { for (int i = 0; i < importedMesh.material_count; i++) { FbxNode* node = mesh->GetNode(); FbxString materialName = importedMaterials[importedMesh.material_Id[i]].name; FbxString shadingName; FbxDouble3 diffuseColor(importedMaterials[importedMesh.material_Id[i]].diffuse[0], importedMaterials[importedMesh.material_Id[i]].diffuse[1], importedMaterials[importedMesh.material_Id[i]].diffuse[2]); FbxDouble3 ambientColor(importedMaterials[importedMesh.material_Id[i]].ambient[0], importedMaterials[importedMesh.material_Id[i]].ambient[1], importedMaterials[importedMesh.material_Id[i]].ambient[2]); FbxDouble3 emissiveColor(importedMaterials[importedMesh.material_Id[i]].incandescence[0], importedMaterials[importedMesh.material_Id[i]].incandescence[1], importedMaterials[importedMesh.material_Id[i]].incandescence[2]); FbxDouble3 transparencyColor(importedMaterials[importedMesh.material_Id[i]].transparency_color[0], importedMaterials[importedMesh.material_Id[i]].transparency_color[1], importedMaterials[importedMesh.material_Id[i]].transparency_color[2]); FbxDouble3 specularColor(importedMaterials[importedMesh.material_Id[i]].specular[0], importedMaterials[importedMesh.material_Id[i]].specular[1] , importedMaterials[importedMesh.material_Id[i]].specular[2]); const char* pathName = "C://Users/Litet/Documents/GitHub/SmallGameProject/FBX Export/FBX Export/"; // Lambert if (importedMaterials[importedMesh.material_Id[i]].mtrl_type == 0) { shadingName = "Lambert"; FbxSurfaceLambert* material = NULL; material= node->GetSrcObject<FbxSurfaceLambert>(0); material = FbxSurfaceLambert::Create(scene, materialName.Buffer()); materialName += i; material->Emissive.Set(emissiveColor); material->Ambient.Set(ambientColor); material->Diffuse.Set(diffuseColor); material->DiffuseFactor.Set(importedMaterials[importedMesh.material_Id[i]].diffuse_factor); material->TransparentColor.Set(transparencyColor); FbxNode* node = mesh->GetNode(); if (node) { node->AddMaterial(material); } // Diffuse Texture FbxFileTexture* texture = FbxFileTexture::Create(scene, "Diffuse Texture"); std::cout << "DAFUSE MAP LENGTH: " << importedMaterials[importedMesh.material_Id[i]].duffuse_map_length << std::endl; if (importedMaterials[importedMesh.material_Id[i]].duffuse_map_length > 0) { std::string tmp(pathName); tmp += importedMaterials[importedMesh.material_Id[i]].diffuse_map; texture->SetFileName(tmp.c_str()); texture->SetTextureUse(FbxTexture::eStandard); texture->SetMappingType(FbxTexture::eUV); texture->SetMaterialUse(FbxFileTexture::eModelMaterial); texture->SetSwapUV(false); texture->SetTranslation(0.0, 0.0); texture->SetScale(1.0, 1.0); texture->SetRotation(0.0, 0.0); if (material) material->Diffuse.ConnectSrcObject(texture); } // Normal Texture texture = FbxFileTexture::Create(scene, "Normal Texture"); if (importedMaterials[importedMesh.material_Id[i]].normal_map_length > 0) { texture->SetFileName(importedMaterials[importedMesh.material_Id[i]].normal_map); texture->SetTextureUse(FbxTexture::eStandard); texture->SetMappingType(FbxTexture::eUV); texture->SetMaterialUse(FbxFileTexture::eModelMaterial); texture->SetSwapUV(false); texture->SetTranslation(0.0, 0.0); texture->SetScale(1.0, 1.0); texture->SetRotation(0.0, 0.0); if (material) material->NormalMap.ConnectSrcObject(texture); } } // Phong else { shadingName = "Phong"; FbxSurfacePhong* material = NULL; material = node->GetSrcObject<FbxSurfacePhong>(0); material = FbxSurfacePhong::Create(scene, materialName.Buffer()); materialName += i; material->Emissive.Set(emissiveColor); material->Ambient.Set(ambientColor); material->Diffuse.Set(diffuseColor); material->DiffuseFactor.Set(importedMaterials[importedMesh.material_Id[i]].diffuse_factor); material->TransparentColor.Set(transparencyColor); material->Specular.Set(specularColor); // No need... super boost? //material->SpecularFactor.Set(importedMaterials[importedMesh.material_Id[i]].specular_factor * 100); material->Shininess.Set(importedMaterials[importedMesh.material_Id[i]].specular_factor); material->Reflection.Set(FbxDouble3(importedMaterials[importedMesh.material_Id[i]].reflection[0], importedMaterials[importedMesh.material_Id[i]].reflection[1], importedMaterials[importedMesh.material_Id[i]].reflection[2])); // Bugged...? material->ReflectionFactor.Set(FbxDouble(importedMaterials[importedMesh.material_Id[i]].reflection_factor)); cout << importedMaterials[importedMesh.material_Id[i]].shininess << endl; FbxNode* node = mesh->GetNode(); if (node) { node->AddMaterial(material); } // Diffuse Texture FbxFileTexture* texture = FbxFileTexture::Create(scene, "Diffuse Texture"); if (importedMaterials[importedMesh.material_Id[i]].duffuse_map_length > 0) { texture->SetFileName(importedMaterials[importedMesh.material_Id[i]].diffuse_map); texture->SetTextureUse(FbxTexture::eStandard); texture->SetMappingType(FbxTexture::eUV); texture->SetMaterialUse(FbxFileTexture::eModelMaterial); texture->SetSwapUV(false); texture->SetTranslation(0.0, 0.0); texture->SetScale(1.0, 1.0); texture->SetRotation(0.0, 0.0); if (material) material->Diffuse.ConnectSrcObject(texture); } // Specular Texture texture = FbxFileTexture::Create(scene, "Specular Texture"); if (importedMaterials[importedMesh.material_Id[i]].specular_map_length > 0) { texture->SetFileName(importedMaterials[importedMesh.material_Id[i]].specular_map); texture->SetTextureUse(FbxTexture::eStandard); texture->SetMappingType(FbxTexture::eUV); texture->SetMaterialUse(FbxFileTexture::eModelMaterial); texture->SetSwapUV(false); texture->SetTranslation(0.0, 0.0); texture->SetScale(1.0, 1.0); texture->SetRotation(0.0, 0.0); if (material) material->Specular.ConnectSrcObject(texture); } // Normal Texture texture = FbxFileTexture::Create(scene, "Normal Texture"); if (importedMaterials[importedMesh.material_Id[i]].normal_map_length > 0) { texture->SetFileName(importedMaterials[importedMesh.material_Id[i]].normal_map); texture->SetTextureUse(FbxTexture::eStandard); texture->SetMappingType(FbxTexture::eUV); texture->SetMaterialUse(FbxFileTexture::eModelMaterial); texture->SetSwapUV(false); texture->SetTranslation(0.0, 0.0); texture->SetScale(1.0, 1.0); texture->SetRotation(0.0, 0.0); if (material) material->NormalMap.ConnectSrcObject(texture); } } } }
void FbxToHkxConverter::extractKeyFramesAndAnnotations(hkxScene *scene, FbxNode* fbxChildNode, hkxNode* newChildNode, int animStackIndex) { FbxAMatrix bindPoseMatrix; FbxAnimStack* lAnimStack = NULL; int numAnimLayers = 0; FbxTimeSpan animTimeSpan; if (animStackIndex >= 0) { lAnimStack = m_curFbxScene->GetSrcObject<FbxAnimStack>(animStackIndex); numAnimLayers = lAnimStack->GetMemberCount<FbxAnimLayer>(); animTimeSpan = lAnimStack->GetLocalTimeSpan(); } // Find the time offset (in the "time space" of the FBX file) of the first animation frame FbxTime timePerFrame; timePerFrame.SetTime(0, 0, 0, 1, 0, m_curFbxScene->GetGlobalSettings().GetTimeMode()); const FbxTime startTime = animTimeSpan.GetStart(); const FbxTime endTime = animTimeSpan.GetStop(); const hkReal startTimeSeconds = static_cast<hkReal>(startTime.GetSecondDouble()); const hkReal endTimeSeconds = static_cast<hkReal>(endTime.GetSecondDouble()); int numFrames = 0; bool staticNode = true; if (scene->m_sceneLength == 0) { bindPoseMatrix = fbxChildNode->EvaluateLocalTransform(startTime); } else { hkArray<hkStringOld> annotationStrings; hkArray<hkReal> annotationTimes; HK_ASSERT(0x0, newChildNode->m_keyFrames.getSize() == 0); // Sample each animation frame for (FbxTime time = startTime, priorSampleTime = endTime; time < endTime; priorSampleTime = time, time += timePerFrame, ++numFrames) { FbxAMatrix frameMatrix = fbxChildNode->EvaluateLocalTransform(time); staticNode = staticNode && (frameMatrix == bindPoseMatrix); hkMatrix4 mat; // Extract this frame's transform convertFbxXMatrixToMatrix4(frameMatrix, mat); newChildNode->m_keyFrames.pushBack(mat); // Extract all annotation strings for this frame using the deprecated // pipeline (new annotations are extracted when sampling attributes) if (m_options.m_exportAnnotations && numAnimLayers > 0) { FbxProperty prop = fbxChildNode->GetFirstProperty(); while(prop.IsValid()) { FbxString propName = prop.GetName(); FbxDataType lDataType = prop.GetPropertyDataType(); hkStringOld name(propName.Buffer(), (int) propName.GetLen()); if (name.asUpperCase().beginsWith("HK") && lDataType.GetType() == eFbxEnum) { FbxAnimLayer* lAnimLayer = lAnimStack->GetMember<FbxAnimLayer>(0); FbxAnimCurve* lAnimCurve = prop.GetCurve(lAnimLayer); int currentKeyIndex; const int keyIndex = (int) lAnimCurve->KeyFind(time, ¤tKeyIndex); const int priorKeyIndex = (int) lAnimCurve->KeyFind(priorSampleTime); // Only store annotations on frames where they're explicitly keyframed, or if this is the first keyframe if (priorKeyIndex != keyIndex) { const int currentEnumValueIndex = keyIndex < 0 ? (int) lAnimCurve->Evaluate(priorSampleTime) : (int) lAnimCurve->Evaluate(time); HK_ASSERT(0x0, currentEnumValueIndex < prop.GetEnumCount()); const char* enumValue = prop.GetEnumValue(currentEnumValueIndex); hkxNode::AnnotationData& annotation = newChildNode->m_annotations.expandOne(); annotation.m_time = (hkReal) (time - startTime).GetSecondDouble(); annotation.m_description = (name + hkStringOld(enumValue, hkString::strLen(enumValue))).cString(); } } prop = fbxChildNode->GetNextProperty(prop); } } } } // Replace animation key data for static nodes with just 1 or 2 frames of bind pose data if (staticNode) { // Static nodes in animated scene data are exported with two keys const bool exportTwoFramesForStaticNodes = (numFrames > 1); // replace transform newChildNode->m_keyFrames.setSize(exportTwoFramesForStaticNodes ? 2: 1); newChildNode->m_keyFrames.optimizeCapacity(0, true); // convert the bind pose transform to Havok format convertFbxXMatrixToMatrix4(bindPoseMatrix, newChildNode->m_keyFrames[0]); if (exportTwoFramesForStaticNodes) { newChildNode->m_keyFrames[1] = newChildNode->m_keyFrames[0]; } } // Extract all times of actual keyframes for the current node... this can be used by Vision if ( m_options.m_storeKeyframeSamplePoints && newChildNode->m_keyFrames.getSize() > 2 && numAnimLayers > 0 ) { FbxAnimLayer* lAnimLayer = lAnimStack->GetMember<FbxAnimLayer>(0); extractKeyTimes(fbxChildNode, lAnimLayer, FBXSDK_CURVENODE_TRANSLATION, newChildNode, startTimeSeconds, endTimeSeconds); extractKeyTimes(fbxChildNode, lAnimLayer, FBXSDK_CURVENODE_ROTATION, newChildNode, startTimeSeconds, endTimeSeconds); extractKeyTimes(fbxChildNode, lAnimLayer, FBXSDK_CURVENODE_SCALING, newChildNode, startTimeSeconds, endTimeSeconds); extractKeyTimes(fbxChildNode, lAnimLayer, FBXSDK_CURVENODE_COMPONENT_X, newChildNode, startTimeSeconds, endTimeSeconds); extractKeyTimes(fbxChildNode, lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Y, newChildNode, startTimeSeconds, endTimeSeconds); extractKeyTimes(fbxChildNode, lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Z, newChildNode, startTimeSeconds, endTimeSeconds); if (newChildNode->m_linearKeyFrameHints.getSize() > 1) { hkSort(newChildNode->m_linearKeyFrameHints.begin(), newChildNode->m_linearKeyFrameHints.getSize()); } } }
FbxDouble3 CFBXLoader::GetMaterialProperty( const FbxSurfaceMaterial * pMaterial, const char * pPropertyName, const char * pFactorPropertyName, FBX_MATRIAL_ELEMENT* pElement) { pElement->type = FBX_MATRIAL_ELEMENT::ELEMENT_NONE; 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; } pElement->type = FBX_MATRIAL_ELEMENT::ELEMENT_COLOR; } if (lProperty.IsValid()) { int existTextureCount = 0; const int lTextureCount = lProperty.GetSrcObjectCount<FbxFileTexture>(); for(int i=0;i<lTextureCount;i++) { FbxFileTexture* lFileTexture = lProperty.GetSrcObject<FbxFileTexture>(i); if(!lFileTexture) continue; FbxString uvsetName = lFileTexture->UVSet.Get(); std::string uvSetString = uvsetName.Buffer(); std::string filepath = lFileTexture->GetFileName(); pElement->textureSetArray[uvSetString].push_back(filepath); existTextureCount++; } const int lLayeredTextureCount = lProperty.GetSrcObjectCount<FbxLayeredTexture>(); for(int i=0;i<lLayeredTextureCount;i++) { FbxLayeredTexture* lLayeredTexture = lProperty.GetSrcObject<FbxLayeredTexture>(i); const int lTextureFileCount = lLayeredTexture->GetSrcObjectCount<FbxFileTexture>(); for(int j=0;j<lTextureFileCount;j++) { FbxFileTexture* lFileTexture = lLayeredTexture->GetSrcObject<FbxFileTexture>(j); if(!lFileTexture) continue; FbxString uvsetName = lFileTexture->UVSet.Get(); std::string uvSetString = uvsetName.Buffer(); std::string filepath = lFileTexture->GetFileName(); pElement->textureSetArray[uvSetString].push_back(filepath); existTextureCount++; } } if(existTextureCount > 0) { if(pElement->type == FBX_MATRIAL_ELEMENT::ELEMENT_COLOR) pElement->type = FBX_MATRIAL_ELEMENT::ELEMENT_BOTH; else pElement->type = FBX_MATRIAL_ELEMENT::ELEMENT_TEXTURE; } } return lResult; }
void Tools::DisplayMaterial::DisplayMaterial( FbxGeometry *i_geometry ) { DisplayCommon::DisplayString( "\n\n--------------------\nMaterial\n--------------------" ); int materialCount = 0; FbxNode *node = NULL; if( i_geometry ) { node = i_geometry->GetNode(); if( node ) materialCount = node->GetMaterialCount(); } if( materialCount > 0 ) { FbxPropertyT<FbxDouble3> double3; FbxPropertyT<FbxDouble> double1; FbxColor theColor; for( int ctr = 0; ctr < materialCount; ctr++ ) { DisplayCommon::DisplayInt( " Material ", ctr ); FbxSurfaceMaterial *material = node->GetMaterial( ctr ); DisplayCommon::DisplayString( " Name: \"", (char *) material->GetName(), "\"" ); #ifdef DISPLAY_HARDWARE_SHADER_INFORMATION //Get the implementation to see if it's a hardware shader. // Note:: this cause memory leak const FbxImplementation* implementation = GetImplementation( material, FBXSDK_IMPLEMENTATION_HLSL ); FbxString implementationType = "HLSL"; if( !implementation ) { implementation = GetImplementation( material, FBXSDK_IMPLEMENTATION_CGFX ); implementationType = "CGFX"; } if( implementation ) { //Now we have a hardware shader, let's read it FBXSDK_printf( " Hardware Shader Type: %s\n", implemenationType.Buffer() ); DisplayCommon::DisplayString( " Hardware Shader Type: ", implemenationType ); const FbxBindingTable* rootTable = implementation->GetRootTable(); FbxString fileName = rootTable->DescAbsoluteURL.Get(); FbxString techniqueName = rootTable->DescTAG.Get(); const FbxBindingTable* table = implementation->GetRootTable(); size_t entryNum = table->GetEntryCount(); for( int i = 0; i < (int)entryNum; i++ ) { const FbxBindingTableEntry& entry = table->GetEntry( i ); const char *entrySrcType = entry.GetEntryType( true ); FbxProperty fbxProp; FbxString test = entry.GetSource(); FBXSDK_printf( " Entry: %s\n", test.Buffer() ); DisplayCommon::DisplayString( " Entry: %s\n", test ); if ( strcmp( FbxPropertyEntryView::sEntryType, entrySrcType ) == 0 ) { fbxProp = material->FindPropertyHierarchical(entry.GetSource()); if( !fbxProp.IsValid() ) { fbxProp = material->RootProperty.FindHierarchical( entry.GetSource() ); } } else if( strcmp( FbxConstantEntryView::sEntryType, entrySrcType ) == 0 ) { fbxProp = implementation->GetConstants().FindHierarchical( entry.GetSource() ); } if( fbxProp.IsValid() ) { if( fbxProp.GetSrcObjectCount<FbxTexture>() > 0 ) { //do what you want with the textures for( int j = 0; j < fbxProp.GetSrcObjectCount<FbxFileTexture>(); j++ ) { FbxFileTexture *tex = fbxProp.GetSrcObject<FbxFileTexture>( j ); FBXSDK_printf( " File Texture: %s\n", tex->GetFileName() ); DisplayCommon::DisplayString( " File Texture: %s\n", tex->GetFileName() ); } for( int j = 0; j < fbxProp.GetSrcObjectCount<FbxLayeredTexture>(); j++ ) { FbxLayeredTexture *tex = fbxProp.GetSrcObject<FbxLayeredTexture>( j ); FBXSDK_printf( " Layered Texture: %s\n", tex->GetName() ); DisplayCommon::DisplayString( " Layered Texture: %s\n", tex->GetName() ); } for( int j = 0; j < fbxProp.GetSrcObjectCount<FbxProceduralTexture>(); j++ ) { FbxProceduralTexture *tex = fbxProp.GetSrcObject<FbxProceduralTexture>( j ); FBXSDK_printf( " Procedural Texture: %s\n", tex->GetName() ); DisplayCommon::DisplayString( " Procedural Texture: %s\n", tex->GetName() ); } } else { FbxDataType fbxType = fbxProp.GetPropertyDataType(); FbxString fbxName = fbxType.GetName(); if( FbxBoolDT == fbxType ) { DisplayCommon::DisplayBool( " Bool: ", fbxProp.Get<FbxBool>() ); } else if( FbxIntDT == fbxType || FbxEnumDT == fbxType ) { DisplayCommon::DisplayInt( " Int: ", fbxProp.Get<FbxInt>() ); } else if( FbxFloatDT == fbxType ) { DisplayCommon::DisplayDouble( " Float: ", fbxProp.Get<FbxFloat>() ); } else if( FbxDoubleDT == fbxType ) { DisplayCommon::DisplayDouble( " Double: ", fbxProp.Get<FbxDouble>() ); } else if( FbxStringDT == fbxType || FbxUrlDT == fbxType || FbxXRefUrlDT == fbxType ) { DisplayCommon::DisplayString( " String: ", fbxProp.Get<FbxString>().Buffer() ); } else if( FbxDouble2DT == fbxType ) { FbxDouble2 double2 = fbxProp.Get<FbxDouble2>(); FbxVector2 vector; vector[0] = double2[0]; vector[1] = double2[1]; DisplayCommon::Display2DVector( " 2D vector: ", vector ); } else if( (FbxDouble3DT == fbxType) || (FbxColor3DT == fbxType) ) { FbxDouble3 double3 = fbxProp.Get<FbxDouble3>(); FbxVector4 vector; vector[0] = double3[0]; vector[1] = double3[1]; vector[2] = double3[2]; DisplayCommon::Display3DVector( " 3D vector: ", vector ); } else if( (FbxDouble4DT == fbxType) || (FbxColor4DT == fbxType) ) { FbxDouble4 double4 = fbxProp.Get<FbxDouble4>(); FbxVector4 vector; vector[0] = double4[0]; vector[1] = double4[1]; vector[2] = double4[2]; vector[3] = double4[3]; DisplayCommon::Display4DVector( " 4D vector: ", vector ); } else if( FbxDouble4x4DT == fbxType ) { FbxDouble4x4 double44 = fbxProp.Get<FbxDouble4x4>(); for( int j = 0; j < 4; j++ ) { FbxVector4 vector; vector[0] = double44[j][0]; vector[1] = double44[j][1]; vector[2] = double44[j][2]; vector[3] = double44[j][3]; DisplayCommon::Display4DVector( " 4x4D vector: ", vector ); } } } } } } else #endif // #ifdef DISPLAY_HARDWARE_SHADER_INFORMATION if( material->GetClassId().Is(FbxSurfacePhong::ClassId) ) { // We found a Phong material. Display its properties. // Display the Ambient Color double3 = ((FbxSurfacePhong *) material)->Ambient; theColor.Set( double3.Get()[0], double3.Get()[1], double3.Get()[2] ); DisplayCommon::DisplayColor( " Ambient: ", theColor ); // Display the Diffuse Color double3 = ((FbxSurfacePhong *) material)->Diffuse; theColor.Set( double3.Get()[0], double3.Get()[1], double3.Get()[2] ); DisplayCommon::DisplayColor( " Diffuse: ", theColor ); // Display the Specular Color (unique to Phong materials) double3 = ((FbxSurfacePhong *) material)->Specular; theColor.Set( double3.Get()[0], double3.Get()[1], double3.Get()[2] ); DisplayCommon::DisplayColor( " Specular: ", theColor ); // Display the Emissive Color double3 = ((FbxSurfacePhong *) material)->Emissive; theColor.Set( double3.Get()[0], double3.Get()[1], double3.Get()[2] ); DisplayCommon::DisplayColor( " Emissive: ", theColor ); //Opacity is Transparency factor now double1 = ((FbxSurfacePhong *) material)->TransparencyFactor; DisplayCommon::DisplayDouble( " Opacity: ", 1.0-double1.Get() ); // Display the Shininess double1 = ((FbxSurfacePhong *) material)->Shininess; DisplayCommon::DisplayDouble( " Shininess: ", double1.Get() ); // Display the Reflectivity double1 = ((FbxSurfacePhong *) material)->ReflectionFactor; DisplayCommon::DisplayDouble( " Reflectivity: ", double1.Get() ); } else if( material->GetClassId().Is(FbxSurfaceLambert::ClassId) ) { // We found a Lambert material. Display its properties. // Display the Ambient Color double3 = ((FbxSurfaceLambert *)material)->Ambient; theColor.Set( double3.Get()[0], double3.Get()[1], double3.Get()[2] ); DisplayCommon::DisplayColor( " Ambient: ", theColor ); // Display the Diffuse Color double3 = ((FbxSurfaceLambert *)material)->Diffuse; theColor.Set( double3.Get()[0], double3.Get()[1], double3.Get()[2] ); DisplayCommon::DisplayColor( " Diffuse: ", theColor ); // Display the Emissive double3 = ((FbxSurfaceLambert *)material)->Emissive; theColor.Set( double3.Get()[0], double3.Get()[1], double3.Get()[2] ); DisplayCommon::DisplayColor( " Emissive: ", theColor ); // Display the Opacity double1 = ((FbxSurfaceLambert *)material)->TransparencyFactor; DisplayCommon::DisplayDouble( " Opacity: ", 1.0-double1.Get() ); } else DisplayCommon::DisplayString( "Unknown type of Material" ); FbxPropertyT<FbxString> string; string = material->ShadingModel; DisplayCommon::DisplayString( " Shading Model: ", string.Get() ); } } }
void Resource::FBX::FBXMaterial::InitMaterial(const FbxSurfaceMaterial *pFbxMaterial, Resource::ResourceManager& rm) { // Logger::Debug(pFbxMaterial->GetName()); Render::MaterialElement& material = AddElement(); const FbxImplementation *lImplementation = pFbxMaterial->GetDefaultImplementation(); FbxPropertyT<FbxDouble3> lKFbxDouble3; FbxPropertyT<FbxDouble> lKFbxDouble1; FbxColor theColor; if(lImplementation){ const FbxBindingTable *lTable = lImplementation->GetRootTable(); size_t lEntryNum = lTable->GetEntryCount(); for (int i = 0; i < (int) lEntryNum; ++i) { const FbxBindingTableEntry &lEntry = lTable->GetEntry(i); const char *lEntrySrcType = lEntry.GetEntryType(true); FbxProperty lFbxProp; FbxString lTest = lEntry.GetSource(); FBXSDK_printf(" Entry: %s\n", lTest.Buffer()); if (strcmp(FbxPropertyEntryView::sEntryType, lEntrySrcType) == 0) { lFbxProp = pFbxMaterial->FindPropertyHierarchical(lEntry.GetSource()); if (!lFbxProp.IsValid()) { lFbxProp = pFbxMaterial->RootProperty.FindHierarchical(lEntry.GetSource()); } } else if (strcmp(FbxConstantEntryView::sEntryType, lEntrySrcType) == 0) { lFbxProp = lImplementation->GetConstants().FindHierarchical(lEntry.GetSource()); } } } else if (pFbxMaterial->GetClassId().Is(FbxSurfacePhong::ClassId)) { // We found a Phong material. Display its properties. // Display the Ambient Color lKFbxDouble3 =((FbxSurfacePhong *) pFbxMaterial)->Ambient; theColor.Set(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]); // Display the Diffuse Color lKFbxDouble3 =((FbxSurfacePhong *) pFbxMaterial)->Diffuse; theColor.Set(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]); // Display the Specular Color (unique to Phong materials) lKFbxDouble3 =((FbxSurfacePhong *) pFbxMaterial)->Specular; theColor.Set(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]); // Display the Emissive Color lKFbxDouble3 =((FbxSurfacePhong *) pFbxMaterial)->Emissive; theColor.Set(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]); //Opacity is Transparency factor now lKFbxDouble1 =((FbxSurfacePhong *) pFbxMaterial)->TransparencyFactor; // Display the Shininess lKFbxDouble1 =((FbxSurfacePhong *) pFbxMaterial)->Shininess; double dShininess = lKFbxDouble1.Get(); lKFbxDouble1 =((FbxSurfacePhong *) pFbxMaterial)->Specular; double dSpecular = lKFbxDouble1.Get(); lKFbxDouble1 =((FbxSurfacePhong *) pFbxMaterial)->SpecularFactor; double dSpecularFactor = lKFbxDouble1.Get(); material.m_fShininess = dShininess; material.m_fSpecular = dSpecular * dSpecularFactor; // Display the Reflectivity lKFbxDouble1 =((FbxSurfacePhong *) pFbxMaterial)->ReflectionFactor; material.m_fReflectionFactor = lKFbxDouble1.Get(); } else if(pFbxMaterial->GetClassId().Is(FbxSurfaceLambert::ClassId) ) { // We found a Lambert material. Display its properties. // Display the Ambient Color lKFbxDouble3=((FbxSurfaceLambert *)pFbxMaterial)->Ambient; theColor.Set(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]); // Display the Diffuse Color lKFbxDouble3 =((FbxSurfaceLambert *)pFbxMaterial)->Diffuse; theColor.Set(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]); // Display the Emissive lKFbxDouble3 =((FbxSurfaceLambert *)pFbxMaterial)->Emissive; theColor.Set(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]); // Display the Opacity lKFbxDouble1 =((FbxSurfaceLambert *)pFbxMaterial)->TransparencyFactor; } else Logger::Debug("Unknown type of Material"); FbxProperty prop = pFbxMaterial->FindProperty(FbxSurfaceMaterial::sDiffuse); // Check if it's layeredtextures int layeredTextureCount = prop.GetSrcObjectCount<FbxLayeredTexture>(); for (int j = 0; j < layeredTextureCount; j++) { FbxLayeredTexture* layered_texture = FbxCast<FbxLayeredTexture>(prop.GetSrcObject<FbxLayeredTexture>(j)); int lcount = layered_texture->GetSrcObjectCount<FbxFileTexture>(); for (int k = 0; k < lcount; k++) { FbxFileTexture* texture = FbxCast<FbxFileTexture>(layered_texture->GetSrcObject<FbxFileTexture>(k)); // Then, you can get all the properties of the texture, include its name const char* textureName = texture->GetFileName(); material.AddTexture(rm.LoadImageFromFile(textureName)); } } int textureCount = prop.GetSrcObjectCount<FbxFileTexture>(); for(int i=0; i<textureCount; ++i){ FbxFileTexture* texture = FbxCast<FbxFileTexture>(prop.GetSrcObject<FbxFileTexture>(i)); const char* textureName = texture->GetFileName(); material.AddTexture(rm.LoadImageFromFile(textureName)); } FbxPropertyT<FbxString> lString; lString = pFbxMaterial->ShadingModel; }
/** * Adds FBX skeleton nodes to the FbxScene based on the skeleton in the given USkeletalMesh, and fills * the given array with the nodes created */ FbxNode* FFbxExporter::CreateSkeleton(const USkeletalMesh* SkelMesh, TArray<FbxNode*>& BoneNodes) { const FReferenceSkeleton& RefSkeleton= SkelMesh->RefSkeleton; if(RefSkeleton.GetNum() == 0) { return NULL; } // Create a list of the nodes we create for each bone, so that children can // later look up their parent BoneNodes.Reserve(RefSkeleton.GetNum()); for(int32 BoneIndex = 0; BoneIndex < RefSkeleton.GetNum(); ++BoneIndex) { const FMeshBoneInfo& CurrentBone = RefSkeleton.GetRefBoneInfo()[BoneIndex]; const FTransform& BoneTransform = RefSkeleton.GetRefBonePose()[BoneIndex]; FbxString BoneName = Converter.ConvertToFbxString(CurrentBone.ExportName); // Create the node's attributes FbxSkeleton* SkeletonAttribute = FbxSkeleton::Create(Scene, BoneName.Buffer()); if(BoneIndex) { SkeletonAttribute->SetSkeletonType(FbxSkeleton::eLimbNode); //SkeletonAttribute->Size.Set(1.0); } else { SkeletonAttribute->SetSkeletonType(FbxSkeleton::eRoot); //SkeletonAttribute->Size.Set(1.0); } // Create the node FbxNode* BoneNode = FbxNode::Create(Scene, BoneName.Buffer()); BoneNode->SetNodeAttribute(SkeletonAttribute); // Set the bone node's local orientation FVector UnrealRotation = BoneTransform.GetRotation().Euler(); FbxVector4 LocalPos = Converter.ConvertToFbxPos(BoneTransform.GetTranslation()); FbxVector4 LocalRot = Converter.ConvertToFbxRot(UnrealRotation); BoneNode->LclTranslation.Set(LocalPos); BoneNode->LclRotation.Set(LocalRot); // If this is not the root bone, attach it to its parent if(BoneIndex) { BoneNodes[CurrentBone.ParentIndex]->AddChild(BoneNode); } // Add the node to the list of nodes, in bone order BoneNodes.Push(BoneNode); } return BoneNodes[0]; }
// マテリアルプロパティ獲得 FbxDouble3 GetMaterialProperty( const FbxSurfaceMaterial * pMaterial, const char * pPropertyName, const char * pFactorPropertyName) { 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()) { printf("テクスチャ\n"); const int lTextureCount = lProperty.GetSrcObjectCount<FbxFileTexture>(); for(int i = 0; i<lTextureCount; i++) { FbxFileTexture* lFileTexture = lProperty.GetSrcObject<FbxFileTexture>(i); if(lFileTexture) { FbxString uvsetName = lFileTexture->UVSet.Get(); std::string uvSetString = uvsetName.Buffer(); std::string filepath = lFileTexture->GetFileName(); printf("UVSet名=%s\n", uvSetString.c_str()); printf("テクスチャ名=%s\n", filepath.c_str()); } } puts(""); printf("レイヤードテクスチャ\n"); const int lLayeredTextureCount = lProperty.GetSrcObjectCount<FbxLayeredTexture>(); for(int i = 0; i<lLayeredTextureCount; i++) { FbxLayeredTexture* lLayeredTexture = lProperty.GetSrcObject<FbxLayeredTexture>(i); const int lTextureFileCount = lLayeredTexture->GetSrcObjectCount<FbxFileTexture>(); for(int j = 0; j<lTextureFileCount; j++) { FbxFileTexture* lFileTexture = lLayeredTexture->GetSrcObject<FbxFileTexture>(j); if(lFileTexture) { FbxString uvsetName = lFileTexture->UVSet.Get(); std::string uvSetString = uvsetName.Buffer(); std::string filepath = lFileTexture->GetFileName(); printf("UVSet名=%s\n", uvSetString.c_str()); printf("テクスチャ名=%s\n", filepath.c_str()); } } } puts(""); } return lResult; }