Exemple #1
0
/**
 * FBX ファイルをシーンに読み込む
 *
 * @param file_path FBX ファイルパス
 */
bool FbxFileLoader::load_fbx( const char_t* file_path )
{
	bool result = false;

	if ( fbx_scene_ )
	{
		fbx_scene_->Destroy( true );
	}

	fbx_scene_ = FbxScene::Create( fbx_manager_, "scene" );

	FbxImporter* importer = FbxImporter::Create( fbx_manager_, "" );
    
	if ( importer->Initialize( file_path, -1, fbx_manager_->GetIOSettings() ) )
	{
		result = importer->Import( fbx_scene_ );
	}
	
	importer->Destroy();

	FbxGeometryConverter converter( fbx_manager_ );
	converter.Triangulate( fbx_scene_, true );

	return result;
}
FbxScene* getScene(std::string filePath, FbxManager* manager) {

	// Create an importer using the SDK manager.
	FbxImporter* importer = FbxImporter::Create(manager,"");

	// Use the first argument as the filename for the importer.
	if(!importer->Initialize(filePath.c_str(), -1, manager->GetIOSettings())) { 
		printf("Call to FbxImporter::Initialize() failed.\n"); 
		printf("Error returned: %s\n\n", importer->GetStatus().GetErrorString()); 
		return nullptr;
	}

	// Create a new scene so that it can be populated by the imported file.
	FbxScene* scene = FbxScene::Create(manager,"myScene");

	// Import the contents of the file into the scene.
	if (importer->Import(scene)) {
		std::cout << "Scene is succefully loaded." << std::endl;
	} else {
		std::cout << "Scene is NOT loaded." << std::endl;
	}

	// The file is imported; so get rid of the importer.
	importer->Destroy();

	return scene;
}
	//FbxManager* lSdkManager = FbxManager::Create();
	sb7fbxmodel::sb7fbxmodel(char *fileName)
	{
		FbxManager* lSdkManager = FbxManager::Create();

		// Create the IO settings object.
		FbxIOSettings *ios = FbxIOSettings::Create(lSdkManager, IOSROOT);
		lSdkManager->SetIOSettings(ios);

		// Create an importer using the SDK manager.
		FbxImporter* lImporter = FbxImporter::Create(lSdkManager,"");

		// Use the first argument as the filename for the importer.
		if(!lImporter->Initialize(fileName, -1, lSdkManager->GetIOSettings())) { 
			printf("Call to FbxImporter::Initialize() failed.\n"); 
			printf("Error returned: %s\n\n", lImporter->GetStatus().GetErrorString()); 
			exit(-1); 
		}

		// Create a new scene so that it can be populated by the imported file.
		FbxScene* lScene = FbxScene::Create(lSdkManager,"myScene");

		// Import the contents of the file into the scene.
		lImporter->Import(lScene);
		ProcessNode(lScene->GetRootNode());

		// The file is imported; so get rid of the importer.
		lImporter->Destroy();
	}
Exemple #4
0
	int FbxLoader::LoadFbx(const char* fbxName)
	{
		m_fbxManager = FbxManager::Create();
		FbxIOSettings *ios = FbxIOSettings::Create(m_fbxManager, IOSROOT);
		m_fbxManager->SetIOSettings(ios);
		FbxImporter* lImporter = FbxImporter::Create(m_fbxManager, "");

		if (!lImporter->Initialize(fbxName, -1, m_fbxManager->GetIOSettings())) {
			printf("Call to FbxImporter::Initialize() failed.\n");
			printf("Error returned: %s\n\n", lImporter->GetStatus().GetErrorString());
			return -1;
		}

		FbxScene* lScene = FbxScene::Create(m_fbxManager, "myScene");
		lImporter->Import(lScene);
		lImporter->Destroy();

		m_rootNode = lScene->GetRootNode();
		if (m_rootNode) {
			m_firstNode = m_rootNode->GetChild(0);
			for (int i = 0; i < m_rootNode->GetChildCount(); i++)
				LoadNode(m_rootNode->GetChild(i));
		}
		m_animEvaluator = lScene->GetAnimationEvaluator();
		return 0;
	}
Exemple #5
0
void LoadScene(FbxManager* pManager,FbxScene*& pScene, const char* fileName)
{
	FbxImporter* sceneImporter = FbxImporter::Create(pManager,"");
	sceneImporter->Initialize(fileName,-1,pManager->GetIOSettings());
	sceneImporter->Import(pScene);
	sceneImporter->Destroy();
}
HRESULT CStaticMesh::Initalize(const char * szFilePath, const char * szFileName)
{

	m_eDrawType = DRAW_VERTEX;
	FbxManager* pFBXManager = FbxManager::Create();
	FbxIOSettings* pIOsettings = FbxIOSettings::Create(pFBXManager, IOSROOT);
	pFBXManager->SetIOSettings(pIOsettings);
	FbxScene* pFBXScene = FbxScene::Create(pFBXManager, "");

	FbxImporter* pImporter = FbxImporter::Create(pFBXManager, "");


	if (FAILED(Load_StaticMesh(szFilePath, szFileName, pFBXManager, pIOsettings, pFBXScene, pImporter)))
		return E_FAIL;


	CMesh::CreateRasterizerState();
	//Init_Shader();

	pFBXScene->Destroy();
	pImporter->Destroy();
	pIOsettings->Destroy();
	pFBXManager->Destroy();


	return S_OK;
}
Exemple #7
0
	void FbxUtil::LoadScene(const std::string &filePath, const std::shared_ptr<SceneNode> &rootNode, float scaleFactor, unsigned int options)
	{
		FbxManager* sdkManager = FbxManager::Create();

		FbxIOSettings* ios = FbxIOSettings::Create(sdkManager, IOSROOT);
		sdkManager->SetIOSettings(ios);

		FbxImporter* importer = FbxImporter::Create(sdkManager, "");
		m_ScaleFactor = scaleFactor;
		m_Options = options;

		if (importer->Initialize(filePath.c_str(), -1, sdkManager->GetIOSettings()))
		{
			FbxScene* lScene = FbxScene::Create(sdkManager, "");

			importer->Import(lScene);

			importer->Destroy();

			FbxNode* lRootNode = lScene->GetRootNode();

			if (lRootNode)
			{
				for (int i = 0; i < lRootNode->GetChildCount(); i++)
					LoadNode(rootNode, lRootNode->GetChild(i));

				rootNode->Recompose();
			}
		}
		else
			ASSERT_MSG(false, "Error: " << importer->GetStatus().GetErrorString());

		// Destroy the SDK manager and all the other objects it was handling.
		sdkManager->Destroy();
	}
Exemple #8
0
bool Model::loadFBXFromFile(const string& fileName)
{
	//initialize the sdk manager
	FbxManager *manager = FbxManager::Create();

	//setting up the IO settings object
	FbxIOSettings *settings = FbxIOSettings::Create(manager, IOSROOT);
	manager->SetIOSettings(settings);

	//creating the importer
	FbxImporter *importer = FbxImporter::Create(manager, "");

	//initializing the importer with contents of file
	if (!importer->Initialize(fileName.c_str(), -1, settings))
		return false;

	//creating a scene to be filled with objects
	FbxScene *scene = FbxScene::Create(manager, "myScene");
	importer->Import(scene);

	FbxGeometryConverter geomConverter(manager);
	geomConverter.Triangulate(scene, true);

	FbxNode *root = scene->GetRootNode();
	if (root)
	{
		//printf("Root Node: %s\n", root->GetName());
		int childCount = root->GetChildCount();
		for (int i = 0; i < childCount; i++)
			processNode(root->GetChild(i), 1);
	}
	importer->Destroy();
	return true;
}
Exemple #9
0
	shared_ptr<Mesh> MeshImporter::createFromFBX(string filename) {
		FbxManager *manager = FbxManager::Create();

		FbxIOSettings *ioSettings = FbxIOSettings::Create(manager, IOSROOT);
		manager->SetIOSettings(ioSettings);

		FbxImporter *importer = FbxImporter::Create(manager, "");
		importer->Initialize(filename.c_str(), -1, manager->GetIOSettings());

		FbxScene *scene = FbxScene::Create(manager, "tempName");

		importer->Import(scene);
		importer->Destroy();

		FbxNode* rootNode = scene->GetRootNode();

		if(rootNode) {
			vector<Vector3> vertices;
			vector<Color> colors;
			vector<Vector2> uvs; 
			vector<Vector3> normals;
			vector<uint32> elements;
			importFBXNode(rootNode, vertices, colors, uvs, normals, elements);
			return shared_ptr<Mesh>(new Mesh(vertices, colors, uvs, elements));
		}

		return nullptr;
	}
Exemple #10
0
void FBXImporter::LoadScene(const char* fileName)
{
	FbxImporter* sceneImporter = FbxImporter::Create(mSDKManager, "importer");
	sceneImporter->Initialize(fileName, -1, mSDKManager->GetIOSettings());
	sceneImporter->Import(mScene);
	sceneImporter->Destroy();
}
// FBXデータから頂点データにコンバート
// ※パスは「/」でしか通らない
//const char* filename = "../datas/box.fbx";
bool LoadFBXConvertToVertexData(const char* filename, VertexDataArray& outVertexData)
{
	//==============================================================================
	// FBXオブジェクト初期化
	//==============================================================================
	// FBXマネージャー作成
	FbxManager* pFBXManager = FbxManager::Create();

	// シーン作成
	FbxScene* pScene = FbxScene::Create(pFBXManager, "");

	// FBXのIO設定オブジェクト作成
	FbxIOSettings *pIO = FbxIOSettings::Create(pFBXManager, IOSROOT);
	pFBXManager->SetIOSettings(pIO);

	// インポートオブジェクト作成
	FbxImporter* pImporter = FbxImporter::Create(pFBXManager, "");

	// ファイルインポート
	if(pImporter->Initialize(filename, -1, pFBXManager->GetIOSettings()) == false)
	{
		return false;
	}

	// シーンへインポート
	if(pImporter->Import(pScene) == false)
	{
		return false;
	}

	// ※この時点でインポートオブジェクトはいらない
	pImporter->Destroy();

	//==============================================================================
	// FBXオブジェクトの処理
	//==============================================================================
	// シーンのものすべてを三角化
	FbxGeometryConverter geometryConverte(pFBXManager);
	geometryConverte.Triangulate(pScene, true);

	// メッシュ情報処理
	GetMeshData(pScene->GetRootNode(), outVertexData);

	//==============================================================================
	// FBXオブジェクト色々破棄
	//==============================================================================
	pIO->Destroy();
	pScene->Destroy();
	pFBXManager->Destroy();

	getchar();

	return true;
}
Exemple #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";
}
Exemple #13
0
bool FbxParser::LoadScene(const char* pFilename)
{
	if(!mpFbxManager)
	if (mpFbxScene)
		mpFbxScene->Clear();
	int lSDKMajor,  lSDKMinor,  lSDKRevision;
    int lFileMajor, lFileMinor, lFileRevision;
	 // Get the file version number generate by the FBX SDK.
    FbxManager::GetFileFormatVersion(lSDKMajor, lSDKMinor, lSDKRevision);

    // Create an importer.
    FbxImporter* lImporter = FbxImporter::Create(mpFbxManager,"");
	    // Initialize the importer by providing a filename.
    const bool lImportStatus = lImporter->Initialize(pFilename, -1, mpFbxManager->GetIOSettings());
	  lImporter->GetFileVersion(lFileMajor, lFileMinor, lFileRevision);
	if (!lImportStatus)
	{
		lImporter->Destroy();
		return false ;
	}
	if (lImporter->IsFBX())
	{
		// Set the import states. By default, the import states are always set to 
        // true. The code below shows how to change these states.
		mpFbxManager->GetIOSettings()->SetBoolProp(IMP_FBX_MATERIAL,        true);
        mpFbxManager->GetIOSettings()->SetBoolProp(IMP_FBX_TEXTURE,         true);
        mpFbxManager->GetIOSettings()->SetBoolProp(IMP_FBX_LINK,            true);
        mpFbxManager->GetIOSettings()->SetBoolProp(IMP_FBX_SHAPE,           true);
        mpFbxManager->GetIOSettings()->SetBoolProp(IMP_FBX_GOBO,            true);
        mpFbxManager->GetIOSettings()->SetBoolProp(IMP_FBX_ANIMATION,       true);
        mpFbxManager->GetIOSettings()->SetBoolProp(IMP_FBX_GLOBAL_SETTINGS, true);
	}
	// Import the scene.
	bool lStatus = lImporter->Import(mpFbxScene);
	lImporter->Destroy();
	return lStatus;
}
void initializeFbxSdk() {
    const char* lFilename = "testCube.fbx";

    mySdkManager = FbxManager::Create();

    // Create the IO settings object.
    FbxIOSettings *ios = FbxIOSettings::Create(mySdkManager, IOSROOT);
    mySdkManager->SetIOSettings(ios);

    // Create an importer using the SDK manager.
    FbxImporter* lImporter = FbxImporter::Create(mySdkManager,"");
    
    // Use the first argument as the filename for the importer.
    if(!lImporter->Initialize(lFilename, -1, mySdkManager->GetIOSettings())) { 
        printf("Call to FbxImporter::Initialize() failed.\n"); 
        printf("Error returned: %s\n\n", lImporter->GetStatus().GetErrorString()); 
        exit(-1);
    }

    // Create a new scene so that it can be populated by the imported file.
    FbxScene* lScene = FbxScene::Create(mySdkManager,"myScene");

    // Import the contents of the file into the scene.
    lImporter->Import(lScene);

    // The file is imported, so get rid of the importer.
    lImporter->Destroy();

    // Print the nodes of the scene and their attributes recursively.
    // Note that we are not printing the root node because it should
    // not contain any attributes.
    FbxNode* lRootNode = lScene->GetRootNode();
    if(lRootNode) {
        for(int i = 0; i < lRootNode->GetChildCount(); i++)
            PrintNode(lRootNode->GetChild(i));
    }

    // Destroy the SDK manager and all the other objects it was handling.
    mySdkManager->Destroy();
}
    bool FbxSerializer::load(const String &path, void *&pData)
    {
        if (mFbxManager == nullptr)
        {
            T3D_LOG_ERROR("FBX Manager haven't been initialized !");
            return false;
        }

        // Create an importer
        FbxImporter *pFbxImporter = FbxImporter::Create(mFbxManager, "");

        // Initialize the importer by providing a filename.
        bool bImportStatus = pFbxImporter->Initialize(path.c_str(), -1, mFbxManager->GetIOSettings());

        if (!bImportStatus)
        {
            T3D_LOG_ERROR("Unable to initialize FBX importer !");
            return false;
        }

        // Import the scene
        bool bStatus = pFbxImporter->Import(mFbxScene);

        // Destroy the importer
        pFbxImporter->Destroy();

        // 统一切换成OpenGL的右手坐标系和以米为单位的坐标系
        FbxAxisSystem::OpenGL.ConvertScene(mFbxScene);
        // 统一以1米为单位
        FbxSystemUnit::m.ConvertScene(mFbxScene);

        // 不是三角形为面的mesh,统一转换成三角形为面的mesh
        FbxGeometryConverter converter(mFbxManager);
        converter.Triangulate(mFbxScene, true);

        pData = mFbxScene;

        return bStatus;
    }
Exemple #16
0
JNIEXPORT jboolean JNICALL Java_de_tesis_dynaware_javafx_graphics_importers_fbx_JFbxLib_open(JNIEnv *env, jobject obj, jstring filePath) {

	sdkManager = FbxManager::Create();

	FbxIOSettings *ios = FbxIOSettings::Create(sdkManager, IOSROOT);

	sdkManager->SetIOSettings(ios);

	FbxImporter *importer = FbxImporter::Create(sdkManager,"");

	if(!importer->Initialize(env->GetStringUTFChars(filePath, 0), -1, sdkManager->GetIOSettings())) {
		throwIOException(env);
	}

	FbxScene *scene = FbxScene::Create(sdkManager,"");

	importer->Import(scene);
	importer->Destroy();

	currentNode = scene->GetRootNode();

	return JNI_TRUE;
}
FbxFileReader::FbxFileReader(const string& filename) : m_pScene(nullptr), m_pSdkManager(nullptr)
{
    // Initialize the resources needed to import fbx files
    m_pSdkManager = FbxManager::Create();
    
	FbxIOSettings* pIOSettings = FbxIOSettings::Create(m_pSdkManager, IOSROOT);
    m_pSdkManager->SetIOSettings(pIOSettings);
	
	FbxImporter* pImporter = FbxImporter::Create(m_pSdkManager,"");
    if( !pImporter->Initialize(filename.c_str(), -1, pIOSettings) )
        throw exception("Failed to initialize FbxImporter.");
    
    // Prepare a scene to contain the fbx data
    m_pScene = FbxScene::Create(m_pSdkManager,"myScene");
    pImporter->Import(m_pScene);

    // Done importing
    pImporter->Destroy();

	//Check if the scene contains a root node
    if( !m_pScene->GetRootNode() )
        throw std::exception("No RootNode could be found.");
}
Exemple #18
0
FbxScene* FBXLoader::LoadScene(const char* aFile)
{
	// Create an importer using the SDK manager.
	FbxImporter* lImporter = FbxImporter::Create(myFbxManager,"");

	// Use the first argument as the filename for the importer.
	if(!lImporter->Initialize(aFile, -1, myFbxManager->GetIOSettings())) 
	{ 
		printf("Call to FbxImporter::Initialize() failed.\n"); 
		printf("Error returned: %s\n\n", lImporter->GetStatus().GetErrorString()); 
		std::string errorMessage = "Could not find fbx file: " + std::string(aFile);
		FBX_LOG(errorMessage.c_str());
		MessageBoxA(nullptr, errorMessage.c_str(), "ERROR", 0);
		//DL_ASSERT("Fbx file not found. Check the debug logger!");
	}

	// Create a new scene so that it can be populated by the imported file.
	FbxScene* lScene = FbxScene::Create(myFbxManager, "myScene");

	// Import the contents of the file into the scene.
	lImporter->Import(lScene);

	// The file is imported; so get rid of the importer.a
	lImporter->Destroy();

	FbxGeometryConverter lGeomConverter(myFbxManager);

	lGeomConverter.Triangulate(lScene, /*replace*/true);

	//FbxMesh mesh;
	//mesh.GenerateTangentsData(
	//lGeomConverter.Comp
	//lGeomConverter.tr
	// Split meshes per material, so that we only have one material per mesh (for VBO support)
	lGeomConverter.SplitMeshesPerMaterial(lScene, /*replace*/true);
	return lScene;
}
void reFBXAsset::import()
{
	FbxImporter* importer = FbxImporter::Create(sdk,"");
	meshes = new reFileAsset(this);
	meshes->setPath("meshes");
	children.push_back(meshes);
	if(!importer->Initialize(path().toUtf8().constData(), -1, sdk->GetIOSettings())) {
		printf("Call to FbxImporter::Initialize() failed.\n");
		printf("Error returned: %s\n\n", importer->GetLastErrorString());
		return;
	}
	FbxScene* lScene = FbxScene::Create(sdk, "myScene");
	FbxAxisSystem ga(FbxAxisSystem::OpenGL);
	ga.ConvertScene(lScene);
	importer->Import(lScene);
	FbxNode* lRootNode = lScene->GetRootNode();
	if(lRootNode) {
		reNode* node = importNode(lRootNode, NULL);
		node->name(info.baseName().toStdString());
		QString path = dataDir() + QDir::separator() + node->name().c_str() + ".json";
		node->save(path.toStdString());
	}
	importer->Destroy();
}
void FBXSceneEncoder::write(const string& filepath, const EncoderArguments& arguments)
{
    FbxManager* sdkManager = FbxManager::Create();
    FbxIOSettings *ios = FbxIOSettings::Create(sdkManager, IOSROOT);
    sdkManager->SetIOSettings(ios);
    FbxImporter* importer = FbxImporter::Create(sdkManager,"");
    
    if (!importer->Initialize(filepath.c_str(), -1, sdkManager->GetIOSettings()))
    {
        LOG(1, "Call to FbxImporter::Initialize() failed.\n");
        LOG(1, "Error returned: %s\n\n", importer->GetLastErrorString());
        exit(-1);
    }
    
    FbxScene* fbxScene = FbxScene::Create(sdkManager,"__FBX_SCENE__");

    print("Loading FBX file.");
    importer->Import(fbxScene);
    importer->Destroy();

    // Determine if animations should be grouped.
    if (arguments.getGroupAnimationAnimationId().empty() && isGroupAnimationPossible(fbxScene))
    {
        if ( arguments.getAnimationGrouping()==EncoderArguments::ANIMATIONGROUP_AUTO || 
            (arguments.getAnimationGrouping()==EncoderArguments::ANIMATIONGROUP_PROMPT && promptUserGroupAnimations()))
        {
            _autoGroupAnimations = true;
        }
    }

    if (arguments.tangentBinormalIdCount() > 0)
    {
        generateTangentsAndBinormals(fbxScene->GetRootNode(), arguments);
    }

    print("Loading Scene.");
    loadScene(fbxScene);
    print("Load materials");
    loadMaterials(fbxScene);
    print("Loading animations.");
    loadAnimations(fbxScene, arguments);
    sdkManager->Destroy();

    print("Optimizing GamePlay Binary.");
    _gamePlayFile.adjust();
    if (_autoGroupAnimations)
    {
        _gamePlayFile.groupMeshSkinAnimations();
    }
    
    string outputFilePath = arguments.getOutputFilePath();

    if (arguments.textOutputEnabled())
    {
        int pos = outputFilePath.find_last_of('.');
        if (pos > 2)
        {
            string path = outputFilePath.substr(0, pos);
            path.append(".xml");
            LOG(1, "Saving debug file: %s\n", path.c_str());
            if (!_gamePlayFile.saveText(path))
            {
                LOG(1, "Error writing text file: %s\n", path.c_str());
            }
        }
    }
    else
    {
        LOG(1, "Saving binary file: %s\n", outputFilePath.c_str());
        if (!_gamePlayFile.saveBinary(outputFilePath))
        {
            LOG(1, "Error writing binary file: %s\n", outputFilePath.c_str());
        }
    }

    // Write the material file
    if (arguments.outputMaterialEnabled())
    {
        int pos = outputFilePath.find_last_of('.');
        if (pos > 2)
        {
            string path = outputFilePath.substr(0, pos);
            path.append(".material");
            writeMaterial(path);
        }
    }
}
Exemple #21
0
FBXSceneImporter::FBXSceneImporter(std::string file_name)
{
	std::string log_file_name = file_name;
	log_file_name.append("log.txt");
	myfile.open(log_file_name.c_str());

	// Initialize the SDK manager. This object handles memory management.
	lSdkManager = FbxManager::Create();

	FbxIOSettings *ios = FbxIOSettings::Create(lSdkManager, IOSROOT);
	lSdkManager->SetIOSettings(ios);

	// Create an importer using the SDK manager.
	FbxImporter* lImporter = FbxImporter::Create(lSdkManager, "");

	// Use the first argument as the filename for the importer.
	if (!lImporter->Initialize(file_name.c_str(), -1, lSdkManager->GetIOSettings())) {
		myfile << "Call to FbxImporter::Initialize() failed.\n";
		myfile << "Error returned: " <<  lImporter->GetStatus().GetErrorString() << "";
		myfile.close();
		exit(-1);
	}

	// Create a new scene so that it can be populated by the imported file.
	lScene = FbxScene::Create(lSdkManager, "myScene");

	// Import the contents of the file into the scene.
	lImporter->Import(lScene);

	// The file is imported, so get rid of the importer.
	lImporter->Destroy();

	FbxGeometryConverter converter(lSdkManager);
	converter.Triangulate(lScene, true);

	scene_to_fill = new Scene(Utilities::get_file_name_from_path_wo_extension(file_name));
	resource_manager.add_scene(scene_to_fill);

	// Print the nodes of the scene and their attributes recursively.
	// Note that we are not printing the root node because it should
	// not contain any attributes.
	FbxNode* lRootNode = lScene->GetRootNode();
	if (lRootNode) 
	{
		for (int i = 0; i < lRootNode->GetChildCount(); i++)
		{
			read_node(lRootNode->GetChild(i));
		}
	}

	if (lRootNode)
	{
		for (int i = 0; i < lRootNode->GetChildCount(); i++)
		{
			PrintNode(lRootNode->GetChild(i));
		}
	}

	// Destroy the SDK manager and all the other objects it was handling.
	myfile.close();
	lSdkManager->Destroy();

}
Exemple #22
0
bool FBXScene::LoadScene(const char* filename, std::ostream& output, Vector3& minPos, Vector3& maxPos)
{
    int lFileMajor, lFileMinor, lFileRevision;

    int i, lAnimStackCount;
    bool lStatus;

	FbxIOSettings *ios = FbxIOSettings::Create(mSdkManager, IOSROOT);
	mSdkManager->SetIOSettings(ios);
	FbxGeometryConverter lGConverter(mSdkManager);
	
	// Create an importer using our sdk manager.
	FbxImporter* pFBXImporter = FbxImporter::Create(mSdkManager,"");

    // Initialize the importer by providing a filename.
    const bool lImportStatus = pFBXImporter->Initialize(filename, -1, mSdkManager->GetIOSettings());
	pFBXImporter->GetFileVersion(lFileMajor, lFileMinor, lFileRevision);

    if( !lImportStatus )
    {
		output << "FBX Importer Error: " << pFBXImporter->GetStatus().GetErrorString() << std::endl;

        if ( pFBXImporter->GetStatus() == FbxStatus::eInvalidFileVersion )
        {
			output << "FBX version number for file " << filename << " is " << lFileMajor << " " << lFileMinor << " " << lFileRevision << std::endl;
		}

        return false;
    }

    if (pFBXImporter->IsFBX())
    {
		output << "FBX version number for file " << filename << " is " << lFileMajor << " " << lFileMinor << " " << lFileRevision << std::endl;

        // From this point, it is possible to access animation stack information without
        // the expense of loading the entire file.

		output << "Animation Stack Information" << std::endl;

        lAnimStackCount = pFBXImporter->GetAnimStackCount();

		output << "    Number of Animation Stacks: " << lAnimStackCount << std::endl;
		output << "    Current Animation Stack: " << pFBXImporter->GetActiveAnimStackName().Buffer() << std::endl;
		
        for(i = 0; i < lAnimStackCount; i++)
        {
            FbxTakeInfo* lTakeInfo = pFBXImporter->GetTakeInfo(i);

			output << "    Animation Stack " << i << std::endl;
			output << "    Name: " << lTakeInfo->mName.Buffer() << std::endl;
			output << "    Description: " <<  lTakeInfo->mDescription.Buffer() << std::endl;
			output << "    Import Name: " << lTakeInfo->mImportName.Buffer() << std::endl;
			output << "    Import State: " << (lTakeInfo->mSelect ? "true" : "false") << std::endl;
        }
    }
	
    // Import the scene.
    lStatus = pFBXImporter->Import(mScene);

	if ( !lStatus )
	{
		output << "Failed Importing FBX!" << std::endl;
		output << "FBX is password protected!" << std::endl;

		if ( pFBXImporter->GetStatus() == FbxStatus::ePasswordError )
		{
			output << "FBX is password protected!" << std::endl;
		}
	}

	mFilename = pFBXImporter->GetFileName().Buffer();

    // Destroy the importer.
    pFBXImporter->Destroy();
	ios->Destroy();

	ProcessScene(mScene);

	return lStatus;
}
Exemple #23
0
/*****************************************************************
* LoadLevel()			Returns the only instance of the MessageManager
*
* Ins:					szFilePath
*
* Outs:					None
*
* Returns:				bool
*
* Mod. Date:		    09/02/2015
* Mod. Initials:	    NH
*****************************************************************/
bool CLevelLoader::LoadLevel(string file_name)
{

#pragma region FBX initialize

	// Get an FBX manager
	FbxManager* manager = FbxManager::Create();
	if (manager == 0)
	{
		return false;
	}

	// Create IO settings
	FbxIOSettings* io_settings = FbxIOSettings::Create(manager, IOSROOT);
	if (io_settings == 0)
	{
		manager->Destroy();
		return false;
	}

	manager->SetIOSettings(io_settings);

	// Create importer
	FbxImporter* importer = FbxImporter::Create(manager, "");
	if (importer == 0)
	{
		io_settings->Destroy();
		manager->Destroy();

		return false;
	}

	// Initialize importer
	if (importer->Initialize(file_name.c_str(), -1, io_settings) == false)
	{
		io_settings->Destroy();
		manager->Destroy();
		importer->Destroy();
		return false;
	}

	// Create a scene
	FbxScene* scene = FbxScene::Create(manager, "myScene");
	if (scene == 0)
	{
		io_settings->Destroy();
		manager->Destroy();
		importer->Destroy();
		return false;
	}

	// Load the scene with contents from the file
	if (importer->Import(scene) == false)
	{
		io_settings->Destroy();
		manager->Destroy();
		importer->Destroy();
		scene->Destroy();
		return false;
	}

	// No longer need the importer

	// Traverse the scene
	FbxNode* root_node = scene->GetRootNode();
	if (ProcessLevelNode(root_node, m_cvMeshes) == false)
	{
		importer->Destroy();
		io_settings->Destroy();
		root_node->Destroy();
		scene->Destroy();
		manager->Destroy();
		return false;
	}

	importer->Destroy();
	io_settings->Destroy();
	root_node->Destroy();
	scene->Destroy();
	manager->Destroy();
	


#pragma endregion

#pragma region Exit Door Objects
	srand((unsigned int)(CURRENT_TIME()));
	unsigned int ExitDoorIndex = rand() % 4;

	//for (unsigned int i = 0; i < m_cvExitDoorMeshes.size(); i++)
	//{
	//	m_cvExitDoorMeshes[i].ConvertVertices();
	//	m_cvExitTeleporterMeshes[i].ConvertVertices();

	//	if (i == ExitDoorIndex)
	//	{
	//		//this is the exit door
	//		m_cpTheExitDoor = new CExitDoorObject("ExitDoor");
	//		m_cpTheExitDoor->AddCollider(new CCollider(true, Bounds::AABB, m_cvExitDoorMeshes[i].GetVertices()));
	//		m_cpTheExitDoor->SetRenderMesh(new CRenderMesh(&m_cvExitDoorMeshes[i], GRAPHICS->GetVertexShader(), GRAPHICS->GetPixelShader(), nullptr, nullptr, nullptr, L"../Game/Assets/Art/2D/Textures/Door.dds"));

	//		m_cpEnvironmentObjects.push_back(m_cpTheExitDoor);
	//		m_cpObjectManager->AddObject(m_cpTheExitDoor, CObjectManager::eObjectType::Dynamic);

	//		//set up teleporter
	//		m_cpTheExitTeleporter = new CWaypointObject("ExitTeleporter");
	//		m_cpTheExitTeleporter->SetPosition(GetAABBCentroid(m_cvExitTeleporterMeshes[i].GetVertices()));

	//		continue;
	//	}

	//	//thse are not exit doors anymore. now they are standard walls
	//	CWallObject* newWall = new CWallObject("Wall");
	//	newWall->AddCollider(new CCollider(false, Bounds::AABB, m_cvExitDoorMeshes[i].GetVertices()));
	//	newWall->SetRenderMesh(new CRenderMesh(&m_cvExitDoorMeshes[i], GRAPHICS->GetVertexShader(), GRAPHICS->GetPixelShader(), nullptr, nullptr, nullptr, L"../Game/Assets/Art/2D/Textures/Maze_Wall.dds"));

	//	m_cpEnvironmentObjects.push_back(newWall);
	//	m_cpObjectManager->AddObject(newWall, CObjectManager::eObjectType::Static);
	//}

#pragma endregion

	CNavGraphManager::GetReference().AddNavGraph("MinotaurNavGraph", m_cpMinotaurNavGraph);

	return true;
}
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 FBXConverter::convert( const char* input , const char* output )
{
	if ( converting ) return;
	converting = true;
	FbxManager* fbxManger = FbxManager::Create();

	FbxIOSettings* ios = FbxIOSettings::Create( fbxManger , IOSROOT );
	fbxManger->SetIOSettings( ios );

	FbxImporter* importer = FbxImporter::Create( fbxManger , "" );

	bool status = importer->Initialize( input , -1 , fbxManger->GetIOSettings() );
	if ( !status )
	{
		std::cout << importer->GetStatus().GetErrorString() << std::endl;
	}

	FbxScene* scene = FbxScene::Create( fbxManger , "theScene" );
	importer->Import( scene );
	importer->Destroy();

	FbxMesh* theMesh = findMesh( scene->GetRootNode() );
	

	if ( theMesh )
	{
		std::vector<VertexData> vertices;
		std::vector<IndexData> indices;

		FbxStringList uvSets;
		theMesh->GetUVSetNames( uvSets );

		processPolygons( theMesh , vertices , indices , uvSets );

		std::vector<JointData> skeleton;
		processSkeletonHierarchy( scene->GetRootNode() , skeleton );
		if ( skeleton.size() ) processAnimations( theMesh->GetNode() , skeleton , vertices , indices );

		std::string modelData;
		for ( unsigned int i = 0; i < vertices.size(); ++i )
		{
			modelData += DATASTRING( vertices[i].position );
			modelData += DATASTRING( vertices[i].uv );
			modelData += DATASTRING( vertices[i].normal );
			modelData += DATASTRING( vertices[i].tangent );
			modelData += DATASTRING( vertices[i].bitangent );
			
			for ( unsigned int j = 0; j < 4 ; ++j )
			{
				if ( j < vertices[i].blendingInfo.size() )
				{
					int blendingIndex = vertices[i].blendingInfo[j].blendingIndex;
					modelData += DATASTRING( blendingIndex );
				}
				else
				{
					int blendingIndex = -1;
					modelData += DATASTRING( blendingIndex );
				}
			}
			for ( unsigned int j = 0; j < 4; ++j )
			{
				if ( j < vertices[i].blendingInfo.size() )
				{
					float blendingIndex = vertices[i].blendingInfo[j].blendingWeight;
					modelData += DATASTRING( blendingIndex );
				}
				else
				{
					float blendingIndex = -1;
					modelData += DATASTRING( blendingIndex );
				}
			}
		}

		for ( unsigned int i = 0; i < indices.size(); ++i)
		{
			modelData += DATASTRING( indices[i].index );
		}

		std::string boneData;
		std::vector<unsigned int> boneChildren;
		std::vector<AnimationData> boneAnimation;
		for ( unsigned int i = 0; i < skeleton.size(); ++i )
		{
			boneData += DATASTRING( skeleton[i].offsetMatrix );
			int childDataStart , childDataEnd , animationDataStart , animationDataEnd;
			if ( skeleton[i].children.size() )
			{
				childDataStart = boneChildren.size();
				for ( unsigned int j = 0; j < skeleton[i].children.size(); ++j )
				{
					boneChildren.push_back( skeleton[i].children[j] );
				}
				childDataEnd = boneChildren.size();
			}
			else
			{
				childDataStart = -1;
				childDataEnd = -1;
			}

			if ( skeleton[i].animation.size() )
			{
				animationDataStart = boneAnimation.size();
				for ( unsigned int j = 0; j < skeleton[i].animation.size(); ++j )
				{
					boneAnimation.push_back( skeleton[i].animation[j] );
				}
				animationDataEnd = boneAnimation.size();
			}
			else
			{
				animationDataStart = -1;
				animationDataEnd = -1;
			}
			boneData += DATASTRING( childDataStart );
			boneData += DATASTRING( childDataEnd );
			boneData += DATASTRING( animationDataStart );
			boneData += DATASTRING( animationDataEnd );
		}
		unsigned int sizeofAnimationRangeInfo;
		AnimationFrameRangeInfo frameRange;
		if ( boneAnimation.size() > 0 )
		{
			sizeofAnimationRangeInfo = 1;
			frameRange.nextAnimationFrameInfo = 0;
			frameRange.firstFrame = 1;
			frameRange.lastFrame = boneAnimation[boneAnimation.size() - 1].frame;
		}
		else
		{
			sizeofAnimationRangeInfo = 0;
		}

		std::fstream stream( output , std::ios_base::binary | std::ios_base::out | std::ios_base::trunc );

		unsigned int sizeofVertices = vertices.size();
		stream.write( reinterpret_cast< char* >( &sizeofVertices ) , sizeof( sizeofVertices ));
		unsigned int sizeofIndices = indices.size();
		stream.write( reinterpret_cast< char* >( &sizeofIndices ) , sizeof( sizeofIndices ) );

		unsigned int sizeofBoneData = skeleton.size();
		stream.write( reinterpret_cast<char*>( &sizeofBoneData ) , sizeof( sizeofBoneData ) );

		unsigned int sizeofBoneChildData = boneChildren.size();
		stream.write( reinterpret_cast< char* >( &sizeofBoneChildData ) , sizeof( sizeofBoneChildData ));

		unsigned int sizeofBoneAnimationData = boneAnimation.size();
		stream.write( reinterpret_cast< char* >( &sizeofBoneAnimationData ) , sizeof( sizeofBoneAnimationData ) );

		stream.write( reinterpret_cast< char* >( &sizeofAnimationRangeInfo ) , sizeof( sizeofAnimationRangeInfo ) );

		stream.write( modelData.c_str() , modelData.size() );

		stream.write( boneData.c_str() , boneData.size() );

		for ( unsigned int i = 0; i < boneChildren.size(); ++i )
		{
			stream.write( reinterpret_cast< char* >( &boneChildren[i] ) , sizeof( boneChildren[i] ) );
		}

		for ( unsigned int i = 0; i < boneAnimation.size(); ++i )
		{
			stream.write( reinterpret_cast< char* >( &boneAnimation[i] ) , sizeof( boneAnimation[i] ) );
		}

		
		if(sizeofAnimationRangeInfo) stream.write( reinterpret_cast< char* >( &frameRange ) , sizeof( frameRange ) );
		stream.close();
	}
	converting = false;
}
	HRESULT FBXLoader::loadFBXFile(char* filePath, VertexBuffer** vBuf, IndexBuffer** iBuf, Renderer* renderer, bool centerShift)
	{
		if (g_pFbxSdkManager == nullptr)
		{
			g_pFbxSdkManager = FbxManager::Create();

			FbxIOSettings* pIOsettings = FbxIOSettings::Create(g_pFbxSdkManager, IOSROOT);
			g_pFbxSdkManager->SetIOSettings(pIOsettings);
		}

		this->shiftCenter = centerShift;

		FbxImporter* pImporter = FbxImporter::Create(g_pFbxSdkManager, "");
		FbxScene* pFbxScene = FbxScene::Create(g_pFbxSdkManager, "");

		bool bSuccess = pImporter->Initialize(filePath, -1, g_pFbxSdkManager->GetIOSettings());
		if (!bSuccess) return E_FAIL;

		bSuccess = pImporter->Import(pFbxScene);
		if (!bSuccess) return E_FAIL;

		FbxAxisSystem sceneAxisSystem = pFbxScene->GetGlobalSettings().GetAxisSystem();
		FbxAxisSystem DirectXAxisSystem(FbxAxisSystem::eYAxis, FbxAxisSystem::eParityOdd, FbxAxisSystem::eLeftHanded);

		if (sceneAxisSystem != DirectXAxisSystem)
		{
			DirectXAxisSystem.ConvertScene(pFbxScene);
		}

		pImporter->Destroy();

		FbxNode* pFbxRootNode = pFbxScene->GetRootNode();

		if (pFbxRootNode)
		{
			// Check if the getChildCount is > 1  TODO
			int test = pFbxRootNode->GetChildCount();

			for (int i = 0; i < pFbxRootNode->GetChildCount(); i++)
			{
				FbxNode* pFbxChildNode = pFbxRootNode->GetChild(i);

				if (pFbxChildNode->GetNodeAttribute() == NULL)
					continue;

				FbxNodeAttribute::EType AttributeType = pFbxChildNode->GetNodeAttribute()->GetAttributeType();

				if (AttributeType != FbxNodeAttribute::eMesh)
					continue;

				FbxMesh* pMesh = (FbxMesh*)pFbxChildNode->GetNodeAttribute();

				int numControlPoints = pMesh->GetControlPointsCount();
				bool initial = true;
				float xMin, yMin, zMin;
				float xMax, yMax, zMax;
				float xIn, yIn, zIn;

				float xCenter, yCenter, zCenter;

				if (this->shiftCenter){

					for (int c = 0; c < numControlPoints; c++) {
						xIn = (float)pMesh->GetControlPointAt(c).mData[0];
						yIn = (float)pMesh->GetControlPointAt(c).mData[1];
						zIn = (float)pMesh->GetControlPointAt(c).mData[2];

						if (initial) {
							xMin = xIn;
							yMin = yIn;
							zMin = zIn;

							xMax = xIn;
							yMax = yIn;
							zMax = zIn;

							initial = false;
						}
						else {
							if (xIn < xMin) {
								xMin = xIn;
							}

							if (yIn < yMin) {
								yMin = yIn;
							}

							if (zIn < zMin) {
								zMin = zIn;
							}

							if (xIn > xMax) {
								xMax = xIn;
							}

							if (yIn > yMax) {
								yMax = yIn;
							}

							if (zIn > zMax) {
								zMax = zIn;
							}
						}
					}
					xCenter = (xMin + xMax) / 2.0f;
					yCenter = (yMin + yMax) / 2.0f;
					zCenter = (zMin + zMax) / 2.0f;
				}
				else {
					xCenter = 0;
					yCenter = 0;
					zCenter = 0;
				}

				FbxVector4* pVertices = pMesh->GetControlPoints();
				int vertexCount = pMesh->GetPolygonVertexCount();

				//Vertex vertex;
				Vertex* vertexArray = new Vertex[vertexCount];
				//Vertex vertexArray[2592];


				int numIndices = vertexCount;
				unsigned int* indexArray = new unsigned int[numIndices];


				FbxVector4 fbxNorm(0, 0, 0, 0);
				FbxVector2 fbxUV(0, 0);
				bool isMapped;

				int vertexIndex = 0;

				// Loop iterates through the polygons and fills the vertex and index arrays for the buffers
				for (int j = 0; j < pMesh->GetPolygonCount(); j++)
				{
					int iNumVertices = pMesh->GetPolygonSize(j);

					assert(iNumVertices == 3);

					//1st vertex
					int controlIndex = pMesh->GetPolygonVertex(j, 2);
					pMesh->GetPolygonVertexUV(j, 2, "map1", fbxUV, isMapped);
					pMesh->GetPolygonVertexNormal(j, 2, fbxNorm);

					vertexArray[vertexIndex].point[0] = (float)pVertices[controlIndex].mData[0] - xCenter;
					vertexArray[vertexIndex].point[1] = (float)pVertices[controlIndex].mData[1] - yCenter;
					vertexArray[vertexIndex].point[2] = -(float)pVertices[controlIndex].mData[2] - zCenter;

					vertexArray[vertexIndex].texCoord[0] = (float)fbxUV[0];
					vertexArray[vertexIndex].texCoord[1] = 1.0f - (float)fbxUV[1];

					vertexArray[vertexIndex].normal[0] = (float)fbxNorm[0];
					vertexArray[vertexIndex].normal[1] = (float)fbxNorm[1];
					vertexArray[vertexIndex].normal[2] = -(float)fbxNorm[2];

					indexArray[vertexIndex] = vertexIndex;
					vertexIndex++;

					//2nd vertex
					controlIndex = pMesh->GetPolygonVertex(j, 1);
					pMesh->GetPolygonVertexUV(j, 1, "map1", fbxUV, isMapped);
					pMesh->GetPolygonVertexNormal(j, 1, fbxNorm);

					vertexArray[vertexIndex].point[0] = (float)pVertices[controlIndex].mData[0] - xCenter;
					vertexArray[vertexIndex].point[1] = (float)pVertices[controlIndex].mData[1] - yCenter;
					vertexArray[vertexIndex].point[2] = -(float)pVertices[controlIndex].mData[2] - zCenter;

					vertexArray[vertexIndex].texCoord[0] = (float)fbxUV[0];
					vertexArray[vertexIndex].texCoord[1] = 1.0f - (float)fbxUV[1];

					vertexArray[vertexIndex].normal[0] = (float)fbxNorm[0];
					vertexArray[vertexIndex].normal[1] = (float)fbxNorm[1];
					vertexArray[vertexIndex].normal[2] = -(float)fbxNorm[2];

					indexArray[vertexIndex] = vertexIndex;
					vertexIndex++;

					//3rd vertex
					controlIndex = pMesh->GetPolygonVertex(j, 0);
					pMesh->GetPolygonVertexUV(j, 0, "map1", fbxUV, isMapped);
					pMesh->GetPolygonVertexNormal(j, 0, fbxNorm);

					vertexArray[vertexIndex].point[0] = (float)pVertices[controlIndex].mData[0] - xCenter;
					vertexArray[vertexIndex].point[1] = (float)pVertices[controlIndex].mData[1] - yCenter;
					vertexArray[vertexIndex].point[2] = -(float)pVertices[controlIndex].mData[2] - zCenter;

					vertexArray[vertexIndex].texCoord[0] = (float)fbxUV[0];
					vertexArray[vertexIndex].texCoord[1] = 1.0f - (float)fbxUV[1];

					vertexArray[vertexIndex].normal[0] = (float)fbxNorm[0];
					vertexArray[vertexIndex].normal[1] = (float)fbxNorm[1];
					vertexArray[vertexIndex].normal[2] = -(float)fbxNorm[2];

					indexArray[vertexIndex] = vertexIndex;
					vertexIndex++;
				}

				// Generate vertex and index buffers from the vertex and index arrays
				*vBuf = renderer->createVertexBuffer(vertexArray, vertexCount);
				*iBuf = renderer->createIndexBuffer(indexArray, numIndices);

				delete[] vertexArray;
				delete[] indexArray;
			}
		}
		return S_OK;
	}
int main ( int argc, char *argv[] )
{
	std::vector<std::string> args (argv, argv + argc);
	if ( args.size() == 1 )
	{
		PrintUsage (args[0]);
		return EXIT_FAILURE;
	}

	std::string animationFile;
	std::string outputPath ("model.glm");
	unsigned i;
	for ( i = 1; i < args.size(); i++ )
	{
		if ( args[i].compare ("-o") == 0 )
		{
			i++;
			if ( args.size() > i )
			{
				outputPath = args[i];

				continue;
			}
			else
			{
				PrintUsage (args[0]);

				return EXIT_FAILURE;
			}
		}
		else if ( args[i].compare ("-anim") == 0 )
		{
			i++;
			if ( args.size() > i )
			{
				animationFile = args[i];

				continue;
			}
			else
			{
				PrintUsage (args[0]);

				return EXIT_FAILURE;
			}
		}
	}

	std::unique_ptr<Skeleton> skeleton;
	std::string modelPath (args.back());

	std::cout << "Converting " << modelPath << " to GLM.\n";

	if ( !animationFile.empty() )
	{
		skeleton = LoadGLA (animationFile);
		if ( !skeleton )
		{
			return EXIT_FAILURE;
		}

		std::cout << "Using " << animationFile << " for skeleton.\n";
	}

	FbxManager *fbxManager = FbxManager::Create();
	FbxIOSettings *ios = FbxIOSettings::Create (fbxManager, IOSROOT);
	fbxManager->SetIOSettings (ios);

	FbxImporter *importer = FbxImporter::Create (fbxManager, "");

	if ( !importer->Initialize (modelPath.c_str(), -1, fbxManager->GetIOSettings()) )
	{
		std::cerr << "ERROR: Failed to import '" << modelPath << "': " << importer->GetStatus().GetErrorString() << ".\n";

		importer->Destroy();
		fbxManager->Destroy();

		return EXIT_FAILURE;
	}

	FbxScene *scene = FbxScene::Create (fbxManager, "model");
	importer->Import (scene);
	importer->Destroy();

	FbxNode *root = scene->GetRootNode();
	if ( root == nullptr )
	{
		std::cerr << "ERROR: The scene's root node could not be found.\n";

		fbxManager->Destroy();

		return EXIT_FAILURE;
	}

	std::vector<FbxNode *> modelRoots (GetLodRootModels (*root));

	if ( modelRoots.empty() )
	{
		std::cerr << "ERROR: No model LODs found.\n";

		fbxManager->Destroy();

		return EXIT_FAILURE;
	}

	std::sort (modelRoots.begin(), modelRoots.end(),
		[]( const FbxNode *a, const FbxNode *b ) { return std::strcmp (a->GetName(), b->GetName()) < 0; });

	if ( !MakeGLMFile (*scene, modelRoots, skeleton.get(), outputPath) )
	{
		std::cerr << "ERROR: Failed to create GLM file " << outputPath << ".\n";

		fbxManager->Destroy();

		return EXIT_FAILURE;
	}

	std::cout << "GLM file has been written to '" << outputPath << "'.\n";

	fbxManager->Destroy();

	return 0;
}
Exemple #28
0
CC_FILE_ERROR FBXFilter::loadFile(const char* filename, ccHObject& container, bool alwaysDisplayLoadDialog/*=true*/, bool* coordinatesShiftEnabled/*=0*/, CCVector3d* coordinatesShift/*=0*/)
{
	// Initialize the SDK manager. This object handles memory management.
	FbxManager* lSdkManager = FbxManager::Create();

	// Create the IO settings object.
	FbxIOSettings *ios = FbxIOSettings::Create(lSdkManager, IOSROOT);
	lSdkManager->SetIOSettings(ios);
	
	// Import options determine what kind of data is to be imported.
	// True is the default, but here we’ll set some to true explicitly, and others to false.
	//(*(lSdkManager->GetIOSettings())).SetBoolProp(IMP_FBX_MATERIAL,        true);
	//(*(lSdkManager->GetIOSettings())).SetBoolProp(IMP_FBX_TEXTURE,         true);
	
	// Create an importer using the SDK manager.
	FbxImporter* lImporter = FbxImporter::Create(lSdkManager,"");

	CC_FILE_ERROR result = CC_FERR_NO_ERROR;
	
	// Use the first argument as the filename for the importer.
	if (!lImporter->Initialize(filename, -1, lSdkManager->GetIOSettings()))
	{ 
		ccLog::Warning(QString("[FBX] Error: %1").arg(lImporter->GetStatus().GetErrorString()));
		result = CC_FERR_READING;
	}
	else
	{
		// Create a new scene so that it can be populated by the imported file.
		FbxScene* lScene = FbxScene::Create(lSdkManager,"myScene");

		// Import the contents of the file into the scene.
		if (lImporter->Import(lScene))
		{
			// Print the nodes of the scene and their attributes recursively.
			// Note that we are not printing the root node because it should
			// not contain any attributes.
			FbxNode* lRootNode = lScene->GetRootNode();
			std::vector<FbxNode*> nodes;
			nodes.push_back(lRootNode);

			while (!nodes.empty())
			{
				FbxNode* lNode = nodes.back();
				nodes.pop_back();

				const char* nodeName = lNode->GetName();
#ifdef _DEBUG
				ccLog::Print(QString("Node: %1 - %2 properties").arg(nodeName).arg(lNode->GetNodeAttributeCount()));
#endif
				// scan the node's attributes.
				for(int i=0; i<lNode->GetNodeAttributeCount(); i++)
				{
					FbxNodeAttribute* pAttribute = lNode->GetNodeAttributeByIndex(i);
					FbxNodeAttribute::EType type = pAttribute->GetAttributeType();
#ifdef _DEBUG
					ccLog::Print(QString("\tProp. #%1").arg(GetAttributeTypeName(type)));
#endif

					switch(type)
					{ 
					case FbxNodeAttribute::eMesh:
						{
							ccMesh* mesh = FromFbxMesh(static_cast<FbxMesh*>(pAttribute),alwaysDisplayLoadDialog,coordinatesShiftEnabled,coordinatesShift);
							if (mesh)
							{
								//apply transformation
								FbxAMatrix& transform = lNode->EvaluateGlobalTransform();
								ccGLMatrix mat;
								float* data = mat.data();
								for (int c=0; c<4; ++c)
								{
									FbxVector4 C = transform.GetColumn(c);
									*data++ = static_cast<float>(C[0]);
									*data++ = static_cast<float>(C[1]);
									*data++ = static_cast<float>(C[2]);
									*data++ = static_cast<float>(C[3]);
								}
								mesh->applyGLTransformation_recursive(&mat);

								if (mesh->getName().isEmpty())
									mesh->setName(nodeName);

								container.addChild(mesh);
							}
						}
						break;

					case FbxNodeAttribute::eUnknown: 
					case FbxNodeAttribute::eNull:
					case FbxNodeAttribute::eMarker:
					case FbxNodeAttribute::eSkeleton:
					case FbxNodeAttribute::eNurbs:
					case FbxNodeAttribute::ePatch:
					case FbxNodeAttribute::eCamera:
					case FbxNodeAttribute::eCameraStereo:
					case FbxNodeAttribute::eCameraSwitcher:
					case FbxNodeAttribute::eLight:
					case FbxNodeAttribute::eOpticalReference:
					case FbxNodeAttribute::eOpticalMarker:
					case FbxNodeAttribute::eNurbsCurve:
					case FbxNodeAttribute::eTrimNurbsSurface:
					case FbxNodeAttribute::eBoundary:
					case FbxNodeAttribute::eNurbsSurface:
					case FbxNodeAttribute::eShape:
					case FbxNodeAttribute::eLODGroup:
					case FbxNodeAttribute::eSubDiv:
					default:
						//not handled yet
						break;
					}
				}

				// Recursively add the children.
				for(int j=0; j<lNode->GetChildCount(); j++)
				{
					nodes.push_back(lNode->GetChild(j));
				}
			}
		}
	}

	// The file is imported, so get rid of the importer.
	lImporter->Destroy();
	// Destroy the SDK manager and all the other objects it was handling.
	lSdkManager->Destroy();

	return container.getChildrenNumber() == 0 ? CC_FERR_NO_LOAD : CC_FERR_NO_ERROR;
}
Exemple #29
0
int main(int argc, char **argv)
{
#ifndef _DEBUG
	if (argc != 2)
	{
		printf("invalid arg");
		return 0;
	}
	const char* filename = argv[1];
#else
	const char* filename = "*****@*****.**";
#endif
	
	output.open("output.txt", ios::out | ios::trunc);
	output2.open("output2.txt", ios::out | ios::trunc);
	output3.open("output3.txt", ios::out | ios::trunc);
	if (!output.is_open())
	{
		exit(1);
	}
	FbxManager* fm = FbxManager::Create();
	FbxIOSettings *ios = FbxIOSettings::Create(fm, IOSROOT);
	//ios->SetBoolProp(EXP_FBX_ANIMATION, false);
	ios->SetIntProp(EXP_FBX_COMPRESS_LEVEL, 9);
	
	ios->SetAllObjectFlags(true);
	fm->SetIOSettings(ios);

	FbxImporter* importer = FbxImporter::Create(fm, "");
	if (!importer->Initialize(filename, -1, fm->GetIOSettings()))
	{
		printf("error returned : %s\n", importer->GetStatus().GetErrorString());
		exit(-1);
	}

	FbxScene* scene = FbxScene::Create(fm, "myscene");

	importer->Import(scene);
	importer->Destroy();
	output << "some\n";
	output << "charcnt : " << scene->GetCharacterCount() << endl << "node cnt : " << scene->GetNodeCount() << endl;
	int animstackcnt = scene->GetSrcObjectCount<FbxAnimStack>();
	output << "animstackcnt : " << animstackcnt << endl;

	output << "------------" << endl;
	vector<FbxNode*> removableNodes;

	for (int i = 0; i < scene->GetNodeCount(); i++)
	{
		FbxNode* node = scene->GetNode(i);
		output << "scene's node " << i << " : " << node->GetName() << ", childcnt : " << node->GetChildCount();
		if (node->GetNodeAttribute())
		{
			output <<", att type : " << node->GetNodeAttribute()->GetAttributeType();
			if (node->GetNodeAttribute()->GetAttributeType() == FbxNodeAttribute::EType::eMesh)
			{
				FbxMesh* mesh = node->GetMesh();

				output << ", mem usage : " << mesh->MemoryUsage() << ", deformer cnt : " << mesh->GetDeformerCount(FbxDeformer::EDeformerType::eSkin) << endl;
				collapseMesh(mesh);
				FbxSkin* skin = (FbxSkin*) (mesh->GetDeformer(0, FbxDeformer::EDeformerType::eSkin));
				if (skin)
				{
					
					for (int cli = 0; cli < skin->GetClusterCount(); cli++)
					{
						FbxCluster* cluster = skin->GetCluster(cli);
						output << "\tcluster no." << cli << " has " << cluster->GetControlPointIndicesCount() << " connected verts" << endl;
						if (cluster->GetControlPointIndicesCount() == 0)
							removableNodes.push_back( cluster->GetLink() );
						
						//cluster->
						//skin->RemoveCluster(cluster);효과없음
					}

					
					
				}
				if (mesh->IsTriangleMesh())
				{
					output << "\tit's triangle mesh" << endl;
					
				}
				//mesh->RemoveDeformer(0);효과없음
			}
			else
				output << endl;
		}
		else
		{
			output << ", att type : none" << endl;
		}
	}

	for (int rni = 0; rni < removableNodes.size(); rni++)
	{
		FbxNode* rnd = removableNodes[rni];
		if (rnd && rnd->GetNodeAttribute()->GetAttributeType() == FbxNodeAttribute::EType::eSkeleton)
		{
			output3 << rnd->GetName() << " node with no vert attached's curve : " << rnd->GetSrcObjectCount<FbxAnimCurve>() << "," << rnd->GetSrcObjectCount<FbxAnimCurveNode>() << endl;
		}
	}

	output << "-----------animinfo" << endl;
	int cubic = 0, linear = 0, cons = 0;
	for (int si = 0; si < animstackcnt; si++)
	{
		FbxAnimStack* stack = scene->GetSrcObject<FbxAnimStack>(si);
		for (int i = 0; i < stack->GetMemberCount<FbxAnimLayer>(); i++)
		{
			FbxAnimLayer* layer = stack->GetMember<FbxAnimLayer>(i);
			int curvenodecnt = layer->GetMemberCount<FbxAnimCurveNode>();
			int compositcnt = 0;
			for (int j = 0; j < curvenodecnt; j++)
			{
				FbxAnimCurveNode* cnode = layer->GetMember<FbxAnimCurveNode>(j);
				compositcnt += (cnode->IsComposite() ? 1 : 0);
			}
			output << "\tanimstack's layer " << i << " : " << layer->GetName() << ", curve node cnt : " << curvenodecnt << ", composit node cnt : " << compositcnt << endl;
			vector<FbxAnimCurveNode*> nodes2del;
			
			for (int j = 0; j < curvenodecnt; j++)
			{
				FbxAnimCurveNode* cnode = layer->GetMember<FbxAnimCurveNode>(j);
				output << "\t\tcurvenode " << j << " channel cnt : " << cnode->GetChannelsCount() << ", dst obj cnt " << cnode->GetDstObjectCount() << "(";
				for (int dsti = 0; dsti < cnode->GetDstObjectCount(); dsti++)
				{
					output << "," << cnode->GetDstObject(dsti)->GetName();
					if (cnode->GetDstObject(dsti)->GetSrcObjectCount() > 0)
						output << "<" << cnode->GetDstObject(dsti)->GetSrcObjectCount<FbxSkeleton>() << ">";
				}
				output << ")";
				FbxTimeSpan interval;
				if (cnode->GetAnimationInterval(interval))
				{
					output << ", start : " << interval.GetStart().GetTimeString() << ", end : " << interval.GetStop().GetTimeString() << endl;
				}
				else
				{
					nodes2del.push_back(cnode);
					output << ", no interval" << endl;
				}

				for (int chi = 0; chi < cnode->GetChannelsCount(); chi++)
				{
					
					int curvecnt = cnode->GetCurveCount(chi);
					output << "\t\t\tchannel." << chi << " curvecnt : " << curvecnt << endl;
					for (int ci = 0; ci < curvecnt; ci++)
					{
						FbxAnimCurve* curve = cnode->GetCurve(chi, ci);
						int keycnt = curve->KeyGetCount();
						output << "\t\t\t\tcurve no." << ci << " : key count : " << keycnt;
						output2 << "curve  " << ci << endl;
						
						vector<int> keys2Remove;
						for (int cki = 0; cki < keycnt; cki++)
						{
							FbxAnimCurveKey prevkey, currkey, nextkey;

							if (cki == 0 || cki == keycnt - 1)
								continue;
							
							currkey = curve->KeyGet(cki);
							prevkey = curve->KeyGet(cki-1);
							nextkey = curve->KeyGet(cki + 1);
							
							bool keepit = true;

							output2 << ci << "-" << cki;

//							keepit = keepTestHorizon(curve, prevkey, currkey, nextkey);
	//						if (keepit)
	//							keepit = slopkeepTest(curve, prevkey, currkey, nextkey);

							if (!keepit)
							{
								if (!(currkey.GetInterpolation() == FbxAnimCurveDef::EInterpolationType::eInterpolationConstant && nextkey.GetInterpolation() != FbxAnimCurveDef::EInterpolationType::eInterpolationConstant))
									keys2Remove.push_back(cki);
							}
						}
						for (int kri = keys2Remove.size() - 1; kri >= 0; kri--)
						{
							
							//curve->KeyRemove(keys2Remove[kri]);
						}
						output2 << endl;
						//output << ", cubic:linear:const : " << cubic << ":" << linear << ":" << cons << endl;
						if (keys2Remove.size() > 0)
							output << ", " << keys2Remove.size() << " keys removed";

						keycnt = curve->KeyGetCount();
						
					}

				}
			}
			//이부분은 별로 효과없음
			/*
			for (int di = 0; di < nodes2del.size(); di++)
			{
				layer->RemoveMember(nodes2del[di]);
			}
			*/
			
		}
	}
	output << "cubic:linear:const  " << cubic << ":" << linear << ":" << cons << endl;
	FbxExporter* exporter = FbxExporter::Create(fm, "");
	const char* outFBXName = "after.fbx";

	bool exportstatus = exporter->Initialize(outFBXName, -1, fm->GetIOSettings());
	if (exportstatus == false)
	{
		puts("err export fail");
	}
	exporter->Export(scene);
	exporter->Destroy();
	scene->Destroy();
	
	ios->Destroy();
	fm->Destroy();
	output.close();
	output2.close();
	output3.close();
	return 0;
}
Exemple #30
-1
		void FbxLoader::LoadFromFile(const std::string& folder, const std::string& name, AxisMode axismode, float scaleFactor)
		{
			FbxManager* fbxManager = FbxManager::Create();
			FbxIOSettings* ios = FbxIOSettings::Create(fbxManager, IOSROOT);
			fbxManager->SetIOSettings(ios);


			std::string path = folder + "\\" + name;
			relativeFolder = folder;
			FbxImporter* importer = (FbxImporter::Create(fbxManager, ""));
			bool b = importer->Initialize(path.c_str(), -1, fbxManager->GetIOSettings());
			if(!b) {
			}
			scene = FbxScene::Create(fbxManager, path.c_str());
			importer->Import(scene);
			

			int fileMajor, fileMinor, fileRevision;
			importer->GetFileVersion(fileMajor, fileMinor, fileRevision);
			importer->Destroy();

			factor = scaleFactor;
			this->axismode = axismode;
			FbxNode* root = scene->GetRootNode();
			
			FbxGeometryConverter geometryConverter(fbxManager);
						
			FbxAxisSystem axis = FbxAxisSystem::MayaYUp;	
			axis.ConvertScene(scene);
			
			geometryConverter.Triangulate(scene, false);

			ProcessMaterial(scene);

			LoadAnimationClipData();

			ProcessMeshNode(root, rootNode);			
		}