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; KFbxSdkManager* pSdkManager = KFbxSdkManager::Create(); if (!pSdkManager) { return ReadResult::ERROR_IN_READING_FILE; } CleanUpFbx cleanUpFbx(pSdkManager); pSdkManager->SetIOSettings(KFbxIOSettings::Create(pSdkManager, IOSROOT)); KFbxScene* pScene = KFbxScene::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 KFbxImporter* lImporter = KFbxImporter::Create(pSdkManager, ""); if (!lImporter->Initialize(utf8filename.c_str(), -1, pSdkManager->GetIOSettings())) { return std::string(lImporter->GetLastErrorString()); } if (!lImporter->IsFBX()) { return ReadResult::ERROR_IN_READING_FILE; } for (int i = 0; i < lImporter->GetTakeCount(); i++) { KFbxTakeInfo* lTakeInfo = lImporter->GetTakeInfo(i); lTakeInfo->mSelect = true; } if (!lImporter->Import(pScene)) { return std::string(lImporter->GetLastErrorString()); } //KFbxAxisSystem::OpenGL.ConvertScene(pScene); // Doesn't work as expected. Still need to transform vertices. if (KFbxNode* pNode = pScene->GetRootNode()) { pScene->SetCurrentTake(pScene->GetCurrentTakeName()); bool useFbxRoot = false; if (options) { std::istringstream iss(options->getOptionString()); std::string opt; while (iss >> opt) { if (opt == "UseFbxRoot") { useFbxRoot = true; } } } osg::ref_ptr<osgAnimation::AnimationManagerBase> pAnimationManager; 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()); std::set<const KFbxNode*> fbxSkeletons; findLinkedFbxSkeletonNodes(pNode, fbxSkeletons); std::map<KFbxNode*, osg::Node*> nodeMap; BindMatrixMap boneBindMatrices; std::map<KFbxNode*, osgAnimation::Skeleton*> skeletonMap; ReadResult res = readFbxNode(*pSdkManager, *pScene, pNode, pAnimationManager, bIsBone, nLightCount, fbxMaterialToOsgStateSet, nodeMap, boneBindMatrices, fbxSkeletons, skeletonMap, *localOptions); if (res.success()) { fbxMaterialToOsgStateSet.checkInvertTransparency(); resolveBindMatrices(*res.getNode(), boneBindMatrices, nodeMap); osg::Node* osgNode = res.getNode(); osgNode->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON); osgNode->getOrCreateStateSet()->setMode(GL_NORMALIZE,osg::StateAttribute::ON); if (pAnimationManager.valid()) { if (osgNode->getUpdateCallback()) { osg::Group* osgGroup = new osg::Group; osgGroup->addChild(osgNode); osgNode = osgGroup; } //because the animations may be altered after registering pAnimationManager->buildTargetReference(); osgNode->setUpdateCallback(pAnimationManager.get()); } KFbxAxisSystem fbxAxis = pScene->GetGlobalSettings().GetAxisSystem(); if (fbxAxis != KFbxAxisSystem::OpenGL) { int upSign; KFbxAxisSystem::eUpVector eUp = fbxAxis.GetUpVector(upSign); bool bLeftHanded = fbxAxis.GetCoorSystem() == KFbxAxisSystem::LeftHanded; float fSign = upSign < 0 ? -1.0f : 1.0f; float zScale = bLeftHanded ? -1.0f : 1.0f; osg::Matrix mat; switch (eUp) { case KFbxAxisSystem::XAxis: mat.set(0,fSign,0,0,-fSign,0,0,0,0,0,zScale,0,0,0,0,1); break; case KFbxAxisSystem::YAxis: mat.set(1,0,0,0,0,fSign,0,0,0,0,fSign*zScale,0,0,0,0,1); break; case KFbxAxisSystem::ZAxis: 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; }
/** * Read from SoInput and convert to OSG. * This is a method used by readNode(string,options) and readNode(istream,options). */ osgDB::ReaderWriter::ReadResult ReaderWriterIV::readNodeFromSoInput(SoInput &input, std::string &fileName, const osgDB::ReaderWriter::Options *options) const { // Parse options and add search paths to SoInput const osgDB::FilePathList *searchPaths = options ? &options->getDatabasePathList() : NULL; if (options) addSearchPaths(searchPaths); // Create the inventor scenegraph by reading from SoInput SoSeparator* rootIVNode = SoDB::readAll(&input); // Remove recently appened search paths if (options) removeSearchPaths(searchPaths); // Close the file input.closeFile(); // Perform conversion ReadResult result; if (rootIVNode) { rootIVNode->ref(); // Convert the inventor scenegraph to an osg scenegraph ConvertFromInventor convertIV; convertIV.preprocess(rootIVNode); result = convertIV.convert(rootIVNode); rootIVNode->unref(); } else result = ReadResult::FILE_NOT_HANDLED; // Notify if (result.success()) { if (fileName.length()) { OSG_NOTICE << "osgDB::ReaderWriterIV::readNode() " << "File " << fileName << " loaded successfully." << std::endl; } else { OSG_NOTICE << "osgDB::ReaderWriterIV::readNode() " << "Stream loaded successfully." << std::endl; } } else { if (fileName.length()) { OSG_WARN << "osgDB::ReaderWriterIV::readNode() " << "Failed to load file " << fileName << "." << std::endl; } else { OSG_WARN << "osgDB::ReaderWriterIV::readNode() " << "Failed to load stream." << std::endl; } } return result; }
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; }
virtual ReadResult readNode(const std::string& file, const Options* options) const { SERIALIZER(); std::string ext = osgDB::getLowerCaseFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName = osgDB::findDataFile(file, options); if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; // in local cache? { osg::Node* node = flt::Registry::instance()->getExternalFromLocalCache(fileName); if (node) return ReadResult(node, ReaderWriter::ReadResult::FILE_LOADED_FROM_CACHE); } // setting up the database path so that internally referenced file are searched for on relative paths. osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options; local_opt->setDatabasePath(osgDB::getFilePath(fileName)); ReadResult rr; // read file { osgDB::ifstream istream; istream.imbue(std::locale::classic()); istream.open(fileName.c_str(), std::ios::in | std::ios::binary); if (istream) { rr = readNode(istream,local_opt.get()); } } static int nestedExternalsLevel = 0; if (rr.success()) { // add to local cache. flt::Registry::instance()->addExternalToLocalCache(fileName,rr.getNode()); bool keepExternalReferences = false; if (options) keepExternalReferences = (options->getOptionString().find("keepExternalReferences")!=std::string::npos); if ( !keepExternalReferences ) { osg::notify(osg::DEBUG_INFO) << "keepExternalReferences not found, so externals will be re-readed"<<std::endl; // read externals. if (rr.getNode()) { nestedExternalsLevel++; ReadExternalsVisitor visitor(local_opt.get()); rr.getNode()->accept(visitor); nestedExternalsLevel--; } } else { osg::notify(osg::DEBUG_INFO) << "keepExternalReferences found, so externals will be left as ProxyNodes"<<std::endl; } } // clear local cache. if (nestedExternalsLevel==0) flt::Registry::instance()->clearLocalCache(); return rr; }