Example #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;
	}
}
Example #2
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();
	}
Example #3
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;
	}
	//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();
	}
void MyGameFbxSceneLoader::loadSceneFromFbx( MyGameScene::MyGameSceneManager* sceneMgr, const string& fileName, MyGameSceneNode* node, vector<MyGameSceneEntity*>& entityList )
{
	FbxManager* fbxMgr= FbxManager::Create();
	FbxIOSettings* fbxIO = FbxIOSettings::Create( fbxMgr, IOSROOT );
	fbxMgr->SetIOSettings( fbxIO );

	FbxScene* fbxScene = FbxScene::Create( fbxMgr, "test" );
	FbxImporter* importer = FbxImporter::Create( fbxMgr, "" );

	importer->Initialize( fileName.c_str(), -1, fbxMgr->GetIOSettings() );
	importer->Import( fbxScene );
	fbxIO->Destroy();

	FbxNode* rootNode = fbxScene->GetRootNode();

	FbxGeometryConverter converter( fbxMgr );
	converter.TriangulateInPlace( rootNode );


    getNodeFromFbxNode( sceneMgr, rootNode, node, entityList );

	rootNode->Destroy();


	fbxScene->Destroy();
	fbxMgr->Destroy();
}
Example #6
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;
}
Example #7
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;
	}
Example #8
0
Model::Model(char* name)
{
	FbxManager* lSdkManager = FbxManager::Create();
	FbxIOSettings * ios = FbxIOSettings::Create(lSdkManager, IOSROOT);
	this->modelName = name;		
	lSdkManager->SetIOSettings(ios);
	FbxImporter* lImporter = FbxImporter::Create(lSdkManager, "");
	std::string path = MODELS_SUBDIR + std::string(name);
	if (!lImporter->Initialize(path.c_str(), -1, lSdkManager->GetIOSettings()))
		TriggerCrash("Nie mo¿na znaleœæ modelu!");
	FbxScene* lScene = FbxScene::Create(lSdkManager, "myScene");	//pobranie calego fbx'a
	lImporter->Import(lScene);
	for (int i = 0; i < lScene->GetRootNode()->GetChildCount(); i++){	//leci po wszystkich modelach w fbx
		FbxNode* node = lScene->GetRootNode()->GetChild(i);
		char* texBaseName = (char*) node->GetName();
		this->objects.push_back(new ModelObject(node));
	}
	Models.push_back(this);
}
// 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;
}
Example #10
0
bool Animation::save(QString file)
{
    // ex:
    // create a SdkManager
    FbxManager* lSdkManager = FbxManager::Create();
    // create an IOSettings object
    FbxIOSettings* ios = FbxIOSettings::Create(lSdkManager, IOSROOT);
    // set some IOSettings options
    ios->SetBoolProp(EXP_FBX_MATERIAL, true);
    ios->SetBoolProp(EXP_FBX_TEXTURE,  true);
    ios->SetBoolProp(EXP_FBX_SHAPE, true);
    ios->SetBoolProp(EXP_FBX_GOBO,            true);
    ios->SetBoolProp(EXP_FBX_ANIMATION,       true);
    ios->SetBoolProp(EXP_FBX_GLOBAL_SETTINGS, true);
    // create an empty scene
    FbxScene* pScene = FbxScene::Create(lSdkManager, m_name.toStdString().c_str());

    QMap<int,FbxNode*> nodes;

    FbxNode* lRootNode = pScene->GetRootNode();


    // Create the Animation Stack
    FbxAnimStack* lAnimStack = FbxAnimStack::Create(pScene, "Show all faces");
    // The animation nodes can only exist on AnimLayers therefore it is mandatory to
    // add at least one AnimLayer to the AnimStack. And for the purpose of this example,
    // one layer is all we need.
    FbxAnimLayer* lAnimLayer = FbxAnimLayer::Create(pScene, "Base animation Layer");
    lAnimStack->AddMember(lAnimLayer);

    int time = 0;

    foreach (const Frame &frame, m_frames)
    {
        time += frame.elapsedTime();

        foreach (const Marker &marker, frame.markers())
        {
            int id = marker.id();

            if(! nodes.contains(id))
            {
                FbxNode *newMarker = WccToFbxExporter::createSphere(pScene, (QString("marker_")+QString::number(id)).toStdString().c_str() , 1.0f);
                nodes[id] = newMarker;
                lRootNode->AddChild(newMarker);
            }

            WccToFbxExporter::addPositionKeyToNode(nodes[id], lAnimLayer, time, marker.position()*m_roomDimensions);
        }
    }
Example #11
0
// Load Fbx File
void GenerateLOD::LoadFbx()
{
	FbxManager *fbxManager = FbxManager::Create();

	//Create an IOSetting
	FbxIOSettings *ios = FbxIOSettings::Create(fbxManager, IOSROOT);
	fbxManager->SetIOSettings(ios);

	//Create an impoter
	FbxImporter *lImporter = FbxImporter::Create(fbxManager, "myImporter");
	std::string tmp = std::string(".\\LODs\\") + srcFbxName;
	bool lImporterStatus = lImporter->Initialize(tmp.c_str(), -1, fbxManager->GetIOSettings());
	if (!lImporterStatus) {
		MessageBox(NULL, "No Scuh File in .\\LODs\\ directory !", "Warning", 0);
		return;
	}

	FbxScene *fbxScene = FbxScene::Create(fbxManager, "myScene");
	lImporter->Import(fbxScene);

	FbxNode *rootNode = fbxScene->GetRootNode();
	if (rootNode != NULL) {
		for (int i = 0; i < rootNode->GetChildCount(); ++i) {
			FbxNode *node = rootNode->GetChild(i);
			FbxNodeAttribute *Att = node->GetNodeAttribute();
			if (Att != NULL && Att->GetAttributeType() == FbxNodeAttribute::eMesh) {
				FbxMesh *lMesh = (FbxMesh *)(Att);
				//FbxMesh *lMesh = dynamic_cast<FbxMesh *>(Att);
				if (!lMesh->IsTriangleMesh()) {
					FbxGeometryConverter converter = FbxGeometryConverter(fbxManager);
					FbxNodeAttribute *Attr = converter.Triangulate(lMesh, true);
					lMesh = (FbxMesh *)(Attr);
				}

				//Following is the SImplification
				Reduction_EdgesCollapse_UV(node, lMesh, fbxManager, fbxScene);

			}
		}
	}

	//MessageBox(NULL, "Export Succeed!", "Export", 0);
	fbxManager->Destroy();
}
Example #12
0
Model::Model(const std::string &filename) {
  key = filename;

  if (ResourceManager::access<Data *>(key))
    return;

  int level = 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);

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

  Data *model = new Data();

  // Create a new scene so that it can be populated by the imported file.
  if (!lImporter->Initialize(filename.c_str(), -1, lSdkManager->GetIOSettings())) {
    LOG(FATAL) << "Failed to load model " << filename;
  }

  // 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);

  // 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) {
    LOG(INFO) << "Root Node " << lRootNode->GetName();
    for (int i = 0; i < lRootNode->GetChildCount(); i++) {
      level = processNode(lRootNode->GetChild(i), level, *model);
    }
  }

  ResourceManager::store(filename, Resource::Type::Model, model);
}
GameObject * loadFBXFromFile(const std::string& filename)
{
	GameObject *rootGo = NULL;
	level = 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);

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

	// Create a new scene so that it can be populated by the imported file.
	if (!lImporter->Initialize(filename.c_str(), -1, lSdkManager->GetIOSettings())) 
	{
		return rootGo;
	}

	// 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);

	// 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) {
		rootGo = new GameObject();
		rootGo->setTransform(new Transform());

		std::cout << "Root Node " << lRootNode->GetName() << std::endl;
		for (int i = 0; i < lRootNode->GetChildCount(); i++)
		{
			processNode(lRootNode->GetChild(i), rootGo);
		}
	}

	return rootGo;
}
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();
}
Example #15
0
    //-----------------------------------------------------------------------------------
    void FbxListScene(const char* filename)
    {
        FbxManager* fbxManager = FbxManager::Create();
        if (nullptr == fbxManager)
        {
            Console::instance->PrintLine("Could not create fbx manager.");
            DebuggerPrintf("Could not create fbx manager.");
            return;
        }
        
        FbxIOSettings* ioSettings = FbxIOSettings::Create(fbxManager, IOSROOT); //Name of object is blank, we don't care
        fbxManager->SetIOSettings(ioSettings);

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

        bool loadSuccessful = importer->Initialize(filename, -1, fbxManager->GetIOSettings());
        if (loadSuccessful)
        {
            //We have imported the FBX
            FbxScene* scene = FbxScene::Create(fbxManager, "");
            bool importSuccessful = importer->Import(scene);
            if (importSuccessful)
            {
                FbxNode* root = scene->GetRootNode();
                PrintNode(root, 0);
            }

            FBX_SAFE_DESTROY(scene);
        }
        else
        {
            Console::instance->PrintLine(Stringf("Could not import scene: %s", filename));
            DebuggerPrintf("Could not import scene: %s", filename);
        }

        FBX_SAFE_DESTROY(importer);
        FBX_SAFE_DESTROY(ioSettings);
        FBX_SAFE_DESTROY(fbxManager);
    }
Example #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;
}
Example #17
0
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();
}
Example #18
0
FBXLoader::FBXLoader(const char *filename)
{
  m_error = true;
  if (m_fbx_sdk_manager == nullptr)
  {
    m_fbx_sdk_manager = FbxManager::Create();
    m_fbx_sdk_manager->SetIOSettings(FbxIOSettings::Create(m_fbx_sdk_manager, IOSROOT));
  }
  FbxImporter *importer = FbxImporter::Create(m_fbx_sdk_manager, "");
  FbxScene *scene = FbxScene::Create(m_fbx_sdk_manager, "");
  if (!importer->Initialize(filename, -1, m_fbx_sdk_manager->GetIOSettings()))
    return;
  if (!importer->Import(scene))
    return;
  importer->Destroy();

  FbxNode *root_node = scene->GetRootNode();
  if (root_node)
  {
    for (int i = 0; i < root_node->GetChildCount(); i++)
    {
      FbxNode *child_node = root_node->GetChild(i);
      if (child_node->GetNodeAttribute() == NULL)
        continue;

      FbxNodeAttribute::EType type = child_node->GetNodeAttribute()->GetAttributeType();
      if (type != FbxNodeAttribute::eMesh)
        continue;

      FbxMesh *mesh = (FbxMesh *) child_node->GetNodeAttribute();
      FbxVector4 *vertices = mesh->GetControlPoints();
      for (int j = 0; j < mesh->GetPolygonCount(); j++)
      {
        int num_verts = mesh->GetPolygonSize(j);
        assert(num_verts == 3);
        DirectX::XMFLOAT3 vertex[3];
        FbxVector4 polygon_normal(0, 0, 0);

        for (int k = 0; k < num_verts; k++)
        {
          int control_point_idx = mesh->GetPolygonVertex(j, k);
          FbxVector4 vertex_normal;
          mesh->GetPolygonVertexNormal(j, k, vertex_normal);
          polygon_normal += vertex_normal;
          vertex[k].x = (float) vertices[control_point_idx].mData[0];
          vertex[k].y = (float) vertices[control_point_idx].mData[1];
          vertex[k].z = (float) vertices[control_point_idx].mData[2];
        }

        if (IsClockwise(vertex, num_verts, polygon_normal))
        {
          for (int i = 0; i < num_verts; i++)
            m_vertices.push_back(ToD3DCoordinateSystem(vertex[i]));
        }
        else
        {
          for (int i = 0; i < num_verts; i++)
            m_vertices.push_back(ToD3DCoordinateSystem(vertex[num_verts - 1 - i]));
        }
      }
    }
  }

  for (size_t i = 0; i < m_vertices.size(); i++)
    m_indices.push_back(i);

  m_error = false;
}
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;
}
int main()
{
	// ※パスは「/」でしか通らない
	const char* filename = "../datas/box.fbx";

	//==============================================================================
	// 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)
	{
		printf("FBXファイルインポートエラー\n");
		printf("エラー内容: %s\n\n", pImporter->GetStatus().GetErrorString());
		return 1;
	}

	// シーンへインポート
	if(pImporter->Import(pScene) == false)
	{
		printf("FBXシーンインポートエラー\n");
		printf("エラー内容: %s\n\n", pImporter->GetStatus().GetErrorString());
		return 1;
	}

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

	//==============================================================================
	// FBXオブジェクトの処理
	//==============================================================================
	// ノードを表示してみる
	traverseScene(pScene->GetRootNode());

	// シーンのものすべてを三角化
	FbxGeometryConverter geometryConverte(pFBXManager);
	geometryConverte.Triangulate(pScene, true);

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

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

	printf("全処理終了\n");
	getchar();

	return 0;
}
Example #21
0
int main(int argc, char** argv) {
	if (argc < 2) {
		printf("Usage: emdfbx model.emd skeleton.esk output.fbx\n       Can include multiple emd and esk files into one fbx.");
		getchar();
		return 1;
	}

	LibXenoverse::initializeDebuggingLog();

	vector<string> model_filenames;
	vector<string> skeleton_filenames;
	vector<string> animation_filenames;
	string export_filename = "";

	for (int i = 1; i < argc; i++)  {
		string parameter = ToString(argv[i]);

		string extension = LibXenoverse::extensionFromFilename(parameter);

		if (extension == "emd") {
			model_filenames.push_back(parameter);
		}

		if (extension == "esk") {
			skeleton_filenames.push_back(parameter);
		}

		if (extension == "ean") {
			animation_filenames.push_back(parameter);
		}

		if (extension == "fbx") {
			export_filename = parameter;
		}
	}

	if (!export_filename.size()) {
		if (model_filenames.size()) {
			export_filename = model_filenames[0] + ".fbx";
		}
		else if (skeleton_filenames.size()) {
			export_filename = skeleton_filenames[0] + ".fbx";
		}
		else {
			export_filename = "Out.fbx";
		}
	}

	// Create FBX Manager
	FbxManager *sdk_manager = FbxManager::Create();
	FbxIOSettings *ios = FbxIOSettings::Create(sdk_manager, IOSROOT);
	ios->SetBoolProp(EXP_FBX_EMBEDDED, true);
	sdk_manager->SetIOSettings(ios);

	// Create Scene
	vector<FbxNode *> global_fbx_bones;
	global_fbx_bones.reserve(300);
	vector<size_t> global_fbx_bones_index;													//TODO find a better way to link skeleton and animations
	global_fbx_bones_index.reserve(300);

	vector<FbxAnimCurveNode *> global_fbx_animation;
	global_fbx_animation.reserve(300);

	FbxScene *scene = FbxScene::Create(sdk_manager, "EMDFBXScene");


	// Load Shaders and convert it to fx file (will be use by fbx).
	vector<string> shader_names;
	shader_names.push_back("adam_shader/shader_age_vs.emb");								//must specified vs folloxed by ps shaders
	shader_names.push_back("adam_shader/shader_age_ps.emb");
	shader_names.push_back("adam_shader/shader_default_vs.emb");
	shader_names.push_back("adam_shader/shader_default_ps.emb");
	

	bool needs_install_shaders = false;
	for (size_t i = 0; i < shader_names.size(); i++) {
		if (!LibXenoverse::fileCheck(shader_names[i])) {
			needs_install_shaders = true;
			break;
		}
	}

	if (needs_install_shaders) {
		printf("Shaders not found. Please use Xenoviewer to prepare shaders in bin folder.");
		return -1;
	}

	for (size_t i = 0; i+1 < shader_names.size(); i+=2) {
		
		LibXenoverse::EMB *shader_pack_vs = new LibXenoverse::EMB();
		LibXenoverse::EMB *shader_pack_ps = new LibXenoverse::EMB();

		if (!shader_pack_vs->load(shader_names[i])) {
			delete shader_pack_vs;
			printf("Couldn't load Shader Pack %s. File is either missing, open by another application, or corrupt.", shader_names[i].c_str());
			continue;
		}
		if (!shader_pack_ps->load(shader_names[i+1])) {
			delete shader_pack_vs;
			delete shader_pack_ps;
			printf("Couldn't load Shader Pack %s. File is either missing, open by another application, or corrupt.", shader_names[i].c_str());
			continue;
		}

		shader_pack_vs->exportShadersToFx(shader_pack_vs, shader_pack_ps);					//convert all shaders in fx file with defaults program parameters (like Ogre's version).
	}



	//build FBX skeleton
	for (size_t i = 0; i < skeleton_filenames.size(); i++) {
		LibXenoverse::ESK *esk_skeleton = new LibXenoverse::ESK();
		esk_skeleton->load(skeleton_filenames[i]);
		vector<FbxNode *> fbx_bones = esk_skeleton->createFBXSkeleton(scene);

		for (size_t j = 0; j < fbx_bones.size(); j++) {
			global_fbx_bones.push_back(fbx_bones[j]);
			global_fbx_bones_index.push_back(j);											//kepp index of bone to link with animations.
		}
	}



	//build FBX animations
	for (size_t i = 0; i < animation_filenames.size(); i++) {
		
		string filename = animation_filenames.at(i);
		string ean_name = LibXenoverse::nameFromFilenameNoExtension(filename, true);

		//vector<FbxAnimCurveNode *> global_fbx_animation;

		LibXenoverse::EAN *animation = new LibXenoverse::EAN();
		if (animation->load(filename)) {

			std::vector<FbxAnimStack *> list_AnimStack;
			size_t nbAnims = animation->getAnimations().size();
			for (size_t j = 0; j < nbAnims; j++) {													//we create only one stack and one layer by animation. each will animate all bones of all skeleton.

				LibXenoverse::EANAnimation *anim_tmp = &(animation->getAnimations().at(j));

				FbxAnimStack* lAnimStack = FbxAnimStack::Create(scene, anim_tmp->getName().c_str());
				FbxAnimLayer* lAnimLayer = FbxAnimLayer::Create(scene, (anim_tmp->getName() + "_Layer0").c_str());
				lAnimStack->AddMember(lAnimLayer);

				list_AnimStack.push_back(lAnimStack);
			}

			size_t k = 0;
			for (vector<FbxNode *>::iterator it = global_fbx_bones.begin(); it != global_fbx_bones.end(); it++) {

				vector<FbxAnimCurveNode *> fbx_anim = animation->exportFBXAnimations(scene, list_AnimStack, *it, global_fbx_bones_index.at(k));

				for (size_t j = 0; j < fbx_anim.size(); j++) {
					global_fbx_animation.push_back(fbx_anim[j]);
				}
				k++;
			}
		}
		else {
			delete animation;
			animation = NULL;
		}
	}




	for (size_t i = 0; i < model_filenames.size(); i++) {
		string node_name = LibXenoverse::nameFromFilenameNoExtension(model_filenames[i]);
		string path = model_filenames[i].substr(0, model_filenames[i].size() - LibXenoverse::nameFromFilename(model_filenames[i]).size());

		LibXenoverse::EMD *emd_model = new LibXenoverse::EMD();
		emd_model->load(model_filenames[i]);

		// Fill Scene
		FbxNode *lMeshNode = NULL;

		// Create Node
		lMeshNode = FbxNode::Create(scene, node_name.c_str());
		lMeshNode->LclTranslation.Set(FbxVector4(0, 0, 0));
		lMeshNode->LclScaling.Set(FbxVector4(1, 1, 1));
		lMeshNode->LclRotation.Set(FbxVector4(0, 0, 0));

		// Create and attach Mesh
		FbxMesh *lMesh = emd_model->exportFBX(scene, lMeshNode, path);
		lMeshNode->SetNodeAttribute(lMesh);

		if (global_fbx_bones.size()) {
			emd_model->exportFBXSkin(scene, lMesh, global_fbx_bones, lMeshNode->EvaluateGlobalTransform());
		}

		// Add node to scene
		FbxNode *lRootNode = scene->GetRootNode();
		lRootNode->AddChild(lMeshNode);

	}

	// Export FBX
	int lFileFormat = sdk_manager->GetIOPluginRegistry()->GetNativeWriterFormat();
	FbxExporter* lExporter = FbxExporter::Create(sdk_manager, "");
	bool lExportStatus = lExporter->Initialize(export_filename.c_str(), lFileFormat, sdk_manager->GetIOSettings());

	if (!lExportStatus) {
		printf("Call to FbxExporter::Initialize() failed.\n");
		printf("Error returned: %s\n\n", lExporter->GetStatus().GetErrorString());
		return 1;
	}

	scene->GetGlobalSettings().SetAxisSystem(FbxAxisSystem::eMax);
	scene->GetGlobalSettings().SetSystemUnit(FbxSystemUnit::m);
	

	// Export scene
	lExporter->Export(scene);
	lExporter->Destroy();
	return 0;
}
Example #22
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;
}
Example #23
0
osgDB::ReaderWriter::ReadResult
ReaderWriterFBX::readNode(const std::string& filenameInit,
                          const Options* options) const
{
    try
    {
        std::string ext(osgDB::getLowerCaseFileExtension(filenameInit));
        if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;

        std::string filename(osgDB::findDataFile(filenameInit, options));
        if (filename.empty()) return ReadResult::FILE_NOT_FOUND;

        FbxManager* pSdkManager = FbxManager::Create();

        if (!pSdkManager)
        {
            return ReadResult::ERROR_IN_READING_FILE;
        }

        CleanUpFbx cleanUpFbx(pSdkManager);

        pSdkManager->SetIOSettings(FbxIOSettings::Create(pSdkManager, IOSROOT));

        FbxScene* pScene = FbxScene::Create(pSdkManager, "");

        // The FBX SDK interprets the filename as UTF-8
#ifdef OSG_USE_UTF8_FILENAME
        const std::string& utf8filename(filename);
#else
        std::string utf8filename(osgDB::convertStringFromCurrentCodePageToUTF8(filename));
#endif

        FbxImporter* lImporter = FbxImporter::Create(pSdkManager, "");

        if (!lImporter->Initialize(utf8filename.c_str(), -1, pSdkManager->GetIOSettings()))
        {
#if FBXSDK_VERSION_MAJOR < 2014
            return std::string(lImporter->GetLastErrorString());
#else
            return std::string(lImporter->GetStatus().GetErrorString());
#endif
        }

        if (!lImporter->IsFBX())
        {
            return ReadResult::ERROR_IN_READING_FILE;
        }

        for (int i = 0; FbxTakeInfo* lTakeInfo = lImporter->GetTakeInfo(i); i++)
        {
            lTakeInfo->mSelect = true;
        }

        if (!lImporter->Import(pScene))
        {
#if FBXSDK_VERSION_MAJOR < 2014
            return std::string(lImporter->GetLastErrorString());
#else 
            return std::string(lImporter->GetStatus().GetErrorString());
#endif
        }

        //FbxAxisSystem::OpenGL.ConvertScene(pScene);        // Doesn't work as expected. Still need to transform vertices.

        if (FbxNode* pNode = pScene->GetRootNode())
        {
            bool useFbxRoot = false;
            bool lightmapTextures = false;
            bool tessellatePolygons = false;
            if (options)
            {
                std::istringstream iss(options->getOptionString());
                std::string opt;
                while (iss >> opt)
                {
                    if (opt == "UseFbxRoot")
                    {
                        useFbxRoot = true;
                    }
                    if (opt == "LightmapTextures")
                    {
                        lightmapTextures = true;
                    }
                    if (opt == "TessellatePolygons")
                    {
                        tessellatePolygons = true;
                    }
                }
            }

            bool bIsBone = false;
            int nLightCount = 0;
            osg::ref_ptr<Options> localOptions = NULL;
            if (options)
                localOptions = options->cloneOptions();
            else
                localOptions = new osgDB::Options();
            localOptions->setObjectCacheHint(osgDB::ReaderWriter::Options::CACHE_IMAGES);

            std::string filePath = osgDB::getFilePath(filename);
            FbxMaterialToOsgStateSet fbxMaterialToOsgStateSet(filePath, localOptions.get(), lightmapTextures);

            std::set<const FbxNode*> fbxSkeletons;
            findLinkedFbxSkeletonNodes(pNode, fbxSkeletons);

            OsgFbxReader::AuthoringTool authoringTool = OsgFbxReader::UNKNOWN;
            if (FbxDocumentInfo* pDocInfo = pScene->GetDocumentInfo())
            {
                struct ToolName
                {
                    const char* name;
                    OsgFbxReader::AuthoringTool tool;
                };

                ToolName authoringTools[] = {
                    {"OpenSceneGraph", OsgFbxReader::OPENSCENEGRAPH},
                    {"3ds Max", OsgFbxReader::AUTODESK_3DSTUDIO_MAX}
                };

                FbxString appName = pDocInfo->LastSaved_ApplicationName.Get();

                for (unsigned int i = 0; i < sizeof(authoringTools) / sizeof(authoringTools[0]); ++i)
                {
                    if (0 ==
#ifdef WIN32
                        _strnicmp
#else
                        strncasecmp
#endif
                        (appName, authoringTools[i].name, strlen(authoringTools[i].name)))
                    {
                        authoringTool = authoringTools[i].tool;
                        break;
                    }
                }
            }


            OsgFbxReader reader(*pSdkManager,
                *pScene,
                fbxMaterialToOsgStateSet,
                fbxSkeletons,
                *localOptions,
                authoringTool,
                lightmapTextures,
                tessellatePolygons);

            ReadResult res = reader.readFbxNode(pNode, bIsBone, nLightCount);

            if (res.success())
            {
                fbxMaterialToOsgStateSet.checkInvertTransparency();

                resolveBindMatrices(*res.getNode(), reader.boneBindMatrices, reader.nodeMap);

                osg::Node* osgNode = res.getNode();
                osgNode->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);
                osgNode->getOrCreateStateSet()->setMode(GL_NORMALIZE,osg::StateAttribute::ON);

                if (reader.pAnimationManager.valid())
                {
                    if (osgNode->getUpdateCallback())
                    {
                        osg::Group* osgGroup = new osg::Group;
                        osgGroup->addChild(osgNode);
                        osgNode = osgGroup;
                    }

                    //because the animations may be altered after registering
                    reader.pAnimationManager->buildTargetReference();
                    osgNode->setUpdateCallback(reader.pAnimationManager.get());
                }

                FbxAxisSystem fbxAxis = pScene->GetGlobalSettings().GetAxisSystem();

                if (fbxAxis != FbxAxisSystem::OpenGL)
                {
                    int upSign;
                    FbxAxisSystem::EUpVector eUp = fbxAxis.GetUpVector(upSign);
                    bool bLeftHanded = fbxAxis.GetCoorSystem() == FbxAxisSystem::eLeftHanded;
                    float fSign = upSign < 0 ? -1.0f : 1.0f;
                    float zScale = bLeftHanded ? -1.0f : 1.0f;

                    osg::Matrix mat;
                    switch (eUp)
                    {
                    case FbxAxisSystem::eXAxis:
                        mat.set(0,fSign,0,0,-fSign,0,0,0,0,0,zScale,0,0,0,0,1);
                        break;
                    case FbxAxisSystem::eYAxis:
                        mat.set(1,0,0,0,0,fSign,0,0,0,0,fSign*zScale,0,0,0,0,1);
                        break;
                    case FbxAxisSystem::eZAxis:
                        mat.set(1,0,0,0,0,0,-fSign*zScale,0,0,fSign,0,0,0,0,0,1);
                        break;
                    }

                    osg::Transform* pTransformTemp = osgNode->asTransform();
                    osg::MatrixTransform* pMatrixTransform = pTransformTemp ?
                        pTransformTemp->asMatrixTransform() : NULL;
                    if (pMatrixTransform)
                    {
                        pMatrixTransform->setMatrix(pMatrixTransform->getMatrix() * mat);
                    }
                    else
                    {
                        pMatrixTransform = new osg::MatrixTransform(mat);
                        if (useFbxRoot && isBasicRootNode(*osgNode))
                        {
                            // If root node is a simple group, put all FBX elements under the OSG root
                            osg::Group* osgGroup = osgNode->asGroup();
                            for(unsigned int i = 0; i < osgGroup->getNumChildren(); ++i)
                            {
                                pMatrixTransform->addChild(osgGroup->getChild(i));
                            }
                            pMatrixTransform->setName(osgGroup->getName());
                        }
                        else
                        {
                            pMatrixTransform->addChild(osgNode);
                        }
                    }
                    osgNode = pMatrixTransform;
                }

                osgNode->setName(filenameInit);
                return osgNode;
            }
        }
    }
    catch (...)
    {
        OSG_WARN << "Exception thrown while importing \"" << filenameInit << '\"' << std::endl;
    }

    return ReadResult::ERROR_IN_READING_FILE;
}
Example #24
0
CC_FILE_ERROR FBXFilter::saveToFile(ccHObject* entity, const char* filename)
{
	if (!entity)
		return CC_FERR_BAD_ARGUMENT;
	
	std::vector<ccGenericMesh*> meshes;
	if (entity->isKindOf(CC_MESH))
	{
		meshes.push_back(static_cast<ccGenericMesh*>(entity));
	}
	else if (entity->isA(CC_HIERARCHY_OBJECT))
	{
		for (unsigned i=0; i<entity->getChildrenNumber(); ++i)
		{
			ccHObject* child = entity->getChild(i);
			if (child->isKindOf(CC_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());
	}

	//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);
			if (meshNode)
				lRootNode->AddChild(meshNode);
			else
				ccLog::Warning(QString("[FBX] Failed to convert mesh '%1' to FBX mesh/node!").arg(meshes[i]->getName()));
		}
	}

	// Save the scene.
    bool lResult = SaveScene(lSdkManager, lScene, filename);

    // Destroy all objects created by the FBX SDK.
    if( lSdkManager )
		lSdkManager->Destroy();

	return lResult ? CC_FERR_NO_ERROR : CC_FERR_CONSOLE_ERROR;
}
Example #25
0
Bone::Bone(FbxScene& scene) {
  //construct hierarchy
  *this = Bone { *(scene.GetRootNode()) };

  std::map<std::string, std::pair<unsigned int, scm::math::mat4f> > bone_info{}
  ;
  unsigned num_bones = 0;
  for (unsigned int i = 0; i < scene.GetGeometryCount(); i++) {
    FbxGeometry* geo = scene.GetGeometry(i);
    if (geo->GetAttributeType() == FbxNodeAttribute::eMesh) {

      //check for skinning, use first skin deformer
      FbxSkin* skin;
      for (unsigned i = 0; i < geo->GetDeformerCount(); ++i) {
        FbxDeformer* defPtr = { geo->GetDeformer(i) };
        if (defPtr->GetDeformerType() == FbxDeformer::eSkin) {
          skin = static_cast<FbxSkin*>(defPtr);
          break;
        }
      }

      if (!skin) {
        Logger::LOG_ERROR << "Mesh does not contain skin deformer" << std::endl;
        assert(false);
      }

      //one cluster corresponds to one bone
      for (unsigned i = 0; i < skin->GetClusterCount(); ++i) {
        FbxCluster* cluster = skin->GetCluster(i);
        FbxNode* node = cluster->GetLink();

        if (!node) {
          Logger::LOG_ERROR << "associated node does not exist!" << std::endl;
          assert(false);
        }

        std::string bone_name(node->GetName());
        //helper to check for matrix magnitude
        auto magnitude = [](scm::math::mat4f const & mat)->float {
          float mag = 0.0f;
          for (unsigned i = 0; i < 16; ++i) {
            mag += mat[i] * mat[i];
          }
          return mag;
        }
        ;

        //reference pose of bone
        FbxAMatrix bind_transform;
        cluster->GetTransformLinkMatrix(bind_transform);
        //check if the clusters have an extra transformation
        FbxAMatrix cluster_transform;
        cluster->GetTransformMatrix(cluster_transform);
        if (magnitude(to_gua::mat4f(cluster_transform) -
                      scm::math::mat4f::identity()) > 0.000000001f) {
          Logger::LOG_WARNING
              << "weight cluster of bone '" << bone_name
              << "' has transformation, animation will be skewed" << std::endl;
        }
        //add bone to list if it is not already included
        if (bone_info.find(bone_name) == bone_info.end()) {
          bone_info[bone_name] = std::make_pair(
              num_bones,
              to_gua::mat4f(bind_transform.Inverse() * cluster_transform));
          ++num_bones;
        }
      }

      // traverse hierarchy and set accumulated values in the bone
      this->set_properties(bone_info);
    }
  }
}
Example #26
0
Model* FbxModelLoader::LoadModel(const char* fileName)
{
	Model* model = nullptr;

	if (!m_importer->Initialize(fileName, -1, m_manager->GetIOSettings()))
	{
		return nullptr;
	}

	FbxScene* lScene = FbxScene::Create(m_manager, "myscene");
	m_importer->Import(lScene);


	FbxNode* lRootNode = lScene->GetRootNode();

	if (lRootNode)
	{
		if (lRootNode->GetChildCount() > 0)
		{
			FbxNode* lNode = lRootNode->GetChild(0);

			FbxMesh* lMesh = lNode->GetMesh();

			

			if (!lMesh)
				return nullptr;

			
			std::ofstream file;

			file.open("DataFromFbxVector.txt");
			char* buffer = new char[1024];

			sprintf_s(buffer, 1024, "Number of children in Root: %d\n\n\n\n", lRootNode->GetChildCount());

			file << buffer;

			if (lMesh->IsTriangleMesh())
				file << "It's a triangle mesh!";
			else
				file << "It's NOT a triangle mesh!";

			


			FbxVector4* vertexArray = lMesh->GetControlPoints();

			for (int i = 0; i < lMesh->GetControlPointsCount(); i++)
			{
				sprintf(buffer, "(%f, %f, %f)\n", vertexArray[i].mData[0], vertexArray[i].mData[1], vertexArray[i].mData[2]);
				file << buffer;
			}

			delete buffer;

			file.close();

			Polygon* polygons = new Polygon[lMesh->GetPolygonCount()];

			int polygonCount = lMesh->GetPolygonCount();

			int index = 0;

			buffer = new char[1024];
			file.open("DataFromPolygons.txt");

			for (int i = 0; i < lMesh->GetPolygonCount(); i++)
			{
				

				index = lMesh->GetPolygonVertex(i, 0);

				sprintf(buffer, "\n\nPolygon #%d\nPolygon Vertex Index #%d: ", i, index);
				file << buffer;

				polygons[i].vertex1.x = (float)vertexArray[index].mData[0];
				polygons[i].vertex1.y = (float)vertexArray[index].mData[1];
				polygons[i].vertex1.z = (float)vertexArray[index].mData[2];

				sprintf(buffer, "(%f, %f, %f)\n", polygons[i].vertex1.x, polygons[i].vertex1.y, polygons[i].vertex1.z);
				file << buffer;


				
				index = lMesh->GetPolygonVertex(i, 1);
				sprintf(buffer, "Polygon Vertex Index #%d: ", index);
				file << buffer;

				polygons[i].vertex2.x = (float)vertexArray[index].mData[0];
				polygons[i].vertex2.y = (float)vertexArray[index].mData[1];
				polygons[i].vertex2.z = (float)vertexArray[index].mData[2];
				sprintf(buffer, "(%f, %f, %f)\n", polygons[i].vertex2.x, polygons[i].vertex2.y, polygons[i].vertex2.z);
				file << buffer;
				
				index = lMesh->GetPolygonVertex(i, 2);
				sprintf(buffer, "Polygon Vertex Index #%d: ", index);
				file << buffer;

				polygons[i].vertex3.x = (float)vertexArray[index].mData[0];
				polygons[i].vertex3.y = (float)vertexArray[index].mData[1];
				polygons[i].vertex3.z = (float)vertexArray[index].mData[2];
				sprintf(buffer, "(%f, %f, %f)\n", polygons[i].vertex3.x, polygons[i].vertex3.y, polygons[i].vertex3.z);
				file << buffer;
			}

			file.close();
			delete buffer;


			model = new Model();
			model->Vertices = new DirectX::XMFLOAT3[polygonCount * 3];
			model->NumVertices = polygonCount * 3;

			file.open("DataFromPolygonToModelTransfer.txt");
			buffer = new char[1024];

			for (int i = 0; i < lMesh->GetPolygonCount() * 3; i += 3)
			{
				model->Vertices[i] = polygons[i/3].vertex1;
				model->Vertices[i+1] = polygons[i/3].vertex2;
				model->Vertices[i+2] = polygons[i/3].vertex3;
			
				sprintf_s(buffer, 1024, "Polygon #%d:\n(%f, %f, %f)\n(%f, %f, %f)\n(%f, %f, %f)\n\n"
					, i / 3
					, model->Vertices[i].x, model->Vertices[i].y, model->Vertices[i].z
					, model->Vertices[i+1].x, model->Vertices[i+1].y, model->Vertices[i+1].z
					, model->Vertices[i+2].x, model->Vertices[i+2].y, model->Vertices[i+2].z);
			
				file << buffer;
			}

			delete buffer;
			file.close();


			// delete [] polygons;
		}
		else
			return nullptr;
	}
	else
		return nullptr;



	return model;
}
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;
}
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);
        }
    }
}
Example #29
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;
}
	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;
	}