Пример #1
1
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;
	}
}
Пример #2
0
    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;
    }
Пример #3
0
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) ;
}
Пример #4
0
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;
}
Пример #5
0
bool SaveScene(FbxManager* pManager, FbxDocument* pScene, const char* pFilename, int pFileFormat = -1, bool pEmbedMedia = false)
{
	int lMajor, lMinor, lRevision;
	bool lStatus = true;

	// Create an exporter.
	FbxExporter* lExporter = FbxExporter::Create(pManager, "");

	if (pFileFormat < 0 || pFileFormat >= pManager->GetIOPluginRegistry()->GetWriterFormatCount())
	{
		// Write in fall back format in less no ASCII format found
		pFileFormat = pManager->GetIOPluginRegistry()->GetNativeWriterFormat();

		//Try to export in ASCII if possible
		int lFormatIndex, lFormatCount = pManager->GetIOPluginRegistry()->GetWriterFormatCount();

		for (lFormatIndex = 0; lFormatIndex < lFormatCount; lFormatIndex++)
		{
			if (pManager->GetIOPluginRegistry()->WriterIsFBX(lFormatIndex))
			{
				FbxString lDesc = pManager->GetIOPluginRegistry()->GetWriterFormatDescription(lFormatIndex);
				const char *lASCII = "ascii";
				if (lDesc.Find(lASCII) >= 0)
				{
					pFileFormat = lFormatIndex;
					break;
				}
			}
		}
	}

	// Set the export states. By default, the export states are always set to 
	// true except for the option eEXPORT_TEXTURE_AS_EMBEDDED. The code below 
	// shows how to change these states.
	IOSETTING_REF.SetBoolProp(EXP_FBX_MATERIAL, true);
	IOSETTING_REF.SetBoolProp(EXP_FBX_TEXTURE, true);
	IOSETTING_REF.SetBoolProp(EXP_FBX_EMBEDDED, pEmbedMedia);
	IOSETTING_REF.SetBoolProp(EXP_FBX_SHAPE, true);
	IOSETTING_REF.SetBoolProp(EXP_FBX_GOBO, true);
	IOSETTING_REF.SetBoolProp(EXP_FBX_ANIMATION, true);
	IOSETTING_REF.SetBoolProp(EXP_FBX_GLOBAL_SETTINGS, true);

	// Initialize the exporter by providing a filename.
	if (lExporter->Initialize(pFilename, pFileFormat, pManager->GetIOSettings()) == false)
	{
		printf("Call to FbxExporter::Initialize() failed.\n");
		printf("Error returned: %s\n\n", lExporter->GetStatus().GetErrorString());
		return false;
	}

	FbxManager::GetFileFormatVersion(lMajor, lMinor, lRevision);
	printf("FBX file format version %d.%d.%d\n\n", lMajor, lMinor, lRevision);

	// Export the scene.
	lStatus = lExporter->Export(pScene);

	// Destroy the exporter.
	lExporter->Destroy();
	return lStatus;
}
Пример #6
0
String^ FBXIOFileHeaderInfo::Creator::get()
{
	FbxString creatorInformation = this->instance->mCreator;
	const char* creatorBuffer = creatorInformation.Buffer();

	return StringHelper::ToManaged(creatorBuffer);
}
Пример #7
0
// 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);
    }
}
Пример #8
0
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 );
}
Пример #9
0
/**
 * 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());
}
Пример #10
0
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 }}) }
	})) ;
}
Пример #11
0
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;
  }
}
Пример #12
0
//===============================================================================================================================
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";
}
Пример #13
0
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";
}
Пример #14
0
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;
	}
}
Пример #15
0
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();
}
Пример #16
0
int ILDLMesh::SaveScene(FbxManager* pManager, FbxDocument* pScene, const char* pFilename, int pFileFormat, bool pEmbedMedia)
{
    int lMajor, lMinor, lRevision;
    int lStatus = -1;

    // Create an exporter.
    FbxExporter* lExporter = FbxExporter::Create(pManager, "");

    if( pFileFormat < 0 || pFileFormat >= pManager->GetIOPluginRegistry()->GetWriterFormatCount() )
    {
        // Write in fall back format in less no ASCII format found
        pFileFormat = pManager->GetIOPluginRegistry()->GetNativeWriterFormat();

        //Try to export in ASCII if possible
        int lFormatIndex, lFormatCount = pManager->GetIOPluginRegistry()->GetWriterFormatCount();

        for (lFormatIndex=0; lFormatIndex<lFormatCount; lFormatIndex++)
        {
            if (pManager->GetIOPluginRegistry()->WriterIsFBX(lFormatIndex))
            {
                FbxString lDesc =pManager->GetIOPluginRegistry()->GetWriterFormatDescription(lFormatIndex);
                const char *lASCII = "ascii";
                if (lDesc.Find(lASCII)>=0)
                {
                    pFileFormat = lFormatIndex;
                    break;
                }
            }
        }
    }
    // Initialize the exporter by providing a filename.
    if(lExporter->Initialize(pFilename, pFileFormat, pManager->GetIOSettings()) == false)
    {
        //FBXSDK_printf("Call to FbxExporter::Initialize() failed.\n");
        //FBXSDK_printf("Error returned: %s\n\n", lExporter->GetStatus().GetErrorString());
        return 431;
    }

    FbxManager::GetFileFormatVersion(lMajor, lMinor, lRevision);
    //FBXSDK_printf("FBX file format version %d.%d.%d\n\n", lMajor, lMinor, lRevision);

    // Export the scene.
    if ( !lExporter->Export(pScene) )
        lStatus = 432;

    // Destroy the exporter.
    lExporter->Destroy();
    return lStatus;
}
Пример #17
0
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;
			}
		}
	}
}
Пример #18
0
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;
}
Пример #19
0
void Scene::outputNode(FileStream &stream, SceneNode *node, int depth)
{
    // The indent
    for (int i = 0; i < depth; ++i)
    {
        stream.printf("  ");
    }

    // Output the type and attributes;
    stream.printf("<%s ", node->type.Buffer());
    for (size_t i = 0; i < node->attributes.size(); i++)
    {
        stream.printf("%s=\"%s\" ", node->attributes[i].first.Buffer(),
                node->attributes[i].second.Buffer());
    }
    stream.printf(">\n");
    
    // Only output the geometry and material of root.
    if (depth > 1 && node->type == "drawable")
    {
        // Geometry
        for (int i = 0; i <= depth; ++i)
        {
            stream.printf("  ");
        }
        stream.printf("<geometry id=\"mesh/%s\" />\n", node->geometry.Lower().Buffer());
        
        // Texture
        // FIXME: more complex material
        for (int i = 0; i <= depth; ++i)
        {
            stream.printf("  ");
        }
        FbxString texName = node->texture;
        FbxString pngTexName = FbxPathUtils::ChangeExtension(texName, ".png");
        stream.printf("<material id=\"material/texture.pmt\" texture=\"texture/%s\" />\n", pngTexName.Buffer());
    }

    // Output children
    for (size_t i = 0; i < node->children.size(); i++)
    {
        SceneNode *child = node->children[i];
        outputNode(stream, child, depth + 1);
    }

    // The indent
    for (int i = 0; i < depth; ++i)
    {
        stream.printf("  ");
    }
    stream.printf("</%s>\n", node->type.Buffer());
}
Пример #20
0
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();
}
Пример #21
0
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()] );
}
Пример #22
0
//-------------------------------------------------------------------------
//
//-------------------------------------------------------------------------
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;
}
Пример #23
0
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();
}
Пример #24
0
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;
}
Пример #25
0
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, &currentKeyIndex);
						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());
		}
	}
}
Пример #26
0
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;
}
Пример #27
0
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;
}
Пример #28
0
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() );
		}
	}
}
// マテリアルプロパティ獲得
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;
}
/**
 * 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];
}