assimpShapeLoader.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. /*
  23. Resource stream -> Buffer
  24. Buffer -> Collada DOM
  25. Collada DOM -> TSShapeLoader
  26. TSShapeLoader installed into TSShape
  27. */
  28. //-----------------------------------------------------------------------------
  29. #include "platform/platform.h"
  30. #include "ts/assimp/assimpShapeLoader.h"
  31. #include "ts/assimp/assimpAppNode.h"
  32. #include "ts/assimp/assimpAppMaterial.h"
  33. #include "ts/assimp/assimpAppSequence.h"
  34. #include "core/util/tVector.h"
  35. #include "core/strings/findMatch.h"
  36. #include "core/stream/fileStream.h"
  37. #include "core/fileObject.h"
  38. #include "ts/tsShape.h"
  39. #include "ts/tsShapeInstance.h"
  40. #include "materials/materialManager.h"
  41. #include "console/persistenceManager.h"
  42. #include "ts/tsShapeConstruct.h"
  43. #include "core/util/zip/zipVolume.h"
  44. #include "gfx/bitmap/gBitmap.h"
  45. #include "gui/controls/guiTreeViewCtrl.h"
  46. // assimp include files.
  47. #include <assimp/cimport.h>
  48. #include <assimp/scene.h>
  49. #include <assimp/postprocess.h>
  50. #include <assimp/types.h>
  51. #include <assimp/config.h>
  52. #include <exception>
  53. #include <assimp/Importer.hpp>
  54. MODULE_BEGIN( AssimpShapeLoader )
  55. MODULE_INIT_AFTER( ShapeLoader )
  56. MODULE_INIT
  57. {
  58. TSShapeLoader::addFormat("DirectX X", "x");
  59. TSShapeLoader::addFormat("Autodesk FBX", "fbx");
  60. TSShapeLoader::addFormat("Blender 3D", "blend" );
  61. TSShapeLoader::addFormat("3ds Max 3DS", "3ds");
  62. TSShapeLoader::addFormat("3ds Max ASE", "ase");
  63. TSShapeLoader::addFormat("Wavefront Object", "obj");
  64. TSShapeLoader::addFormat("Industry Foundation Classes (IFC/Step)", "ifc");
  65. TSShapeLoader::addFormat("Stanford Polygon Library", "ply");
  66. TSShapeLoader::addFormat("AutoCAD DXF", "dxf");
  67. TSShapeLoader::addFormat("LightWave", "lwo");
  68. TSShapeLoader::addFormat("LightWave Scene", "lws");
  69. TSShapeLoader::addFormat("Modo", "lxo");
  70. TSShapeLoader::addFormat("Stereolithography", "stl");
  71. TSShapeLoader::addFormat("AC3D", "ac");
  72. TSShapeLoader::addFormat("Milkshape 3D", "ms3d");
  73. TSShapeLoader::addFormat("TrueSpace COB", "cob");
  74. TSShapeLoader::addFormat("TrueSpace SCN", "scn");
  75. TSShapeLoader::addFormat("Ogre XML", "xml");
  76. TSShapeLoader::addFormat("Irrlicht Mesh", "irrmesh");
  77. TSShapeLoader::addFormat("Irrlicht Scene", "irr");
  78. TSShapeLoader::addFormat("Quake I", "mdl" );
  79. TSShapeLoader::addFormat("Quake II", "md2" );
  80. TSShapeLoader::addFormat("Quake III Mesh", "md3");
  81. TSShapeLoader::addFormat("Quake III Map/BSP", "pk3");
  82. TSShapeLoader::addFormat("Return to Castle Wolfenstein", "mdc");
  83. TSShapeLoader::addFormat("Doom 3", "md5" );
  84. TSShapeLoader::addFormat("Valve SMD", "smd");
  85. TSShapeLoader::addFormat("Valve VTA", "vta");
  86. TSShapeLoader::addFormat("Starcraft II M3", "m3");
  87. TSShapeLoader::addFormat("Unreal", "3d");
  88. TSShapeLoader::addFormat("BlitzBasic 3D", "b3d" );
  89. TSShapeLoader::addFormat("Quick3D Q3D", "q3d");
  90. TSShapeLoader::addFormat("Quick3D Q3S", "q3s");
  91. TSShapeLoader::addFormat("Neutral File Format", "nff");
  92. TSShapeLoader::addFormat("Object File Format", "off");
  93. TSShapeLoader::addFormat("PovRAY Raw", "raw");
  94. TSShapeLoader::addFormat("Terragen Terrain", "ter");
  95. TSShapeLoader::addFormat("3D GameStudio (3DGS)", "mdl");
  96. TSShapeLoader::addFormat("3D GameStudio (3DGS) Terrain", "hmp");
  97. TSShapeLoader::addFormat("Izware Nendo", "ndo");
  98. TSShapeLoader::addFormat("gltf", "gltf");
  99. TSShapeLoader::addFormat("gltf binary", "glb");
  100. }
  101. MODULE_END;
  102. //-----------------------------------------------------------------------------
  103. AssimpShapeLoader::AssimpShapeLoader()
  104. {
  105. mScene = NULL;
  106. }
  107. AssimpShapeLoader::~AssimpShapeLoader()
  108. {
  109. }
  110. void AssimpShapeLoader::releaseImport()
  111. {
  112. aiReleaseImport(mScene);
  113. }
  114. void AssimpShapeLoader::enumerateScene()
  115. {
  116. TSShapeLoader::updateProgress(TSShapeLoader::Load_ReadFile, "Reading File");
  117. Con::printf("[ASSIMP] Attempting to load file: %s", shapePath.getFullPath().c_str());
  118. // Post-Processing
  119. unsigned int ppsteps =
  120. Con::getBoolVariable("$Assimp::ConvertToLeftHanded", false) ? aiProcess_ConvertToLeftHanded : 0 |
  121. Con::getBoolVariable("$Assimp::CalcTangentSpace", false) ? aiProcess_CalcTangentSpace : 0 |
  122. Con::getBoolVariable("$Assimp::JoinIdenticalVertices", false) ? aiProcess_JoinIdenticalVertices : 0 |
  123. Con::getBoolVariable("$Assimp::ValidateDataStructure", false) ? aiProcess_ValidateDataStructure : 0 |
  124. Con::getBoolVariable("$Assimp::ImproveCacheLocality", false) ? aiProcess_ImproveCacheLocality : 0 |
  125. Con::getBoolVariable("$Assimp::RemoveRedundantMaterials", false) ? aiProcess_RemoveRedundantMaterials : 0 |
  126. Con::getBoolVariable("$Assimp::FindDegenerates", false) ? aiProcess_FindDegenerates : 0 |
  127. Con::getBoolVariable("$Assimp::FindInvalidData", false) ? aiProcess_FindInvalidData : 0 |
  128. Con::getBoolVariable("$Assimp::GenUVCoords", false) ? aiProcess_GenUVCoords : 0 |
  129. Con::getBoolVariable("$Assimp::TransformUVCoords", false) ? aiProcess_TransformUVCoords : 0 |
  130. Con::getBoolVariable("$Assimp::FindInstances", false) ? aiProcess_FindInstances : 0 |
  131. Con::getBoolVariable("$Assimp::LimitBoneWeights", false) ? aiProcess_LimitBoneWeights : 0 |
  132. Con::getBoolVariable("$Assimp::OptimizeMeshes", false) ? aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph : 0 |
  133. 0;
  134. if(Con::getBoolVariable("$Assimp::Triangulate", true))
  135. ppsteps |= aiProcess_Triangulate;
  136. if (Con::getBoolVariable("$Assimp::OptimizeMeshes", false))
  137. ppsteps |= aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph;
  138. if (Con::getBoolVariable("$Assimp::SplitLargeMeshes", false))
  139. ppsteps |= aiProcess_SplitLargeMeshes;
  140. //aiProcess_SortByPType | // make 'clean' meshes which consist of a single typ of primitives
  141. aiPropertyStore* props = aiCreatePropertyStore();
  142. aiSetImportPropertyInteger(props, AI_CONFIG_IMPORT_TER_MAKE_UVS, 1);
  143. aiSetImportPropertyInteger(props, AI_CONFIG_PP_SBP_REMOVE, (aiProcessPreset_TargetRealtime_Quality
  144. | aiProcess_FlipWindingOrder | aiProcess_FlipUVs
  145. | aiProcess_CalcTangentSpace
  146. | aiProcess_FixInfacingNormals)
  147. & ~aiProcess_RemoveRedundantMaterials);
  148. aiSetImportPropertyInteger(props, AI_CONFIG_GLOB_MEASURE_TIME, 1);
  149. aiSetImportPropertyFloat(props, AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE, 80.f);
  150. //aiSetImportPropertyInteger(props,AI_CONFIG_PP_PTV_KEEP_HIERARCHY,1);
  151. //Assimp::Importer importer;
  152. // Attempt to import with Assimp.
  153. //mScene = importer.ReadFile(shapePath.getFullPath().c_str(), (aiProcessPreset_TargetRealtime_Quality | aiProcess_FlipWindingOrder | aiProcess_FlipUVs | aiProcess_CalcTangentSpace)
  154. // & ~aiProcess_RemoveRedundantMaterials);
  155. mScene = (aiScene*)aiImportFileExWithProperties(shapePath.getFullPath().c_str(), ppsteps, NULL, props);
  156. aiReleasePropertyStore(props);
  157. if ( mScene )
  158. {
  159. Con::printf("[ASSIMP] Mesh Count: %d", mScene->mNumMeshes);
  160. Con::printf("[ASSIMP] Material Count: %d", mScene->mNumMaterials);
  161. // Load all the materials.
  162. for ( U32 i = 0; i < mScene->mNumMaterials; i++ )
  163. AppMesh::appMaterials.push_back(new AssimpAppMaterial(mScene->mMaterials[i]));
  164. // Define the root node, and process down the chain.
  165. AssimpAppNode* node = new AssimpAppNode(mScene, mScene->mRootNode, 0);
  166. if (!processNode(node))
  167. delete node;
  168. // Check for animations and process those.
  169. processAnimations();
  170. }
  171. else
  172. {
  173. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Import failed");
  174. Con::printf("[ASSIMP] Import Error: %s", aiGetErrorString());
  175. }
  176. }
  177. void AssimpShapeLoader::processAnimations()
  178. {
  179. for(U32 n = 0; n < mScene->mNumAnimations; ++n)
  180. {
  181. Con::printf("[ASSIMP] Animation Found: %s", mScene->mAnimations[n]->mName.C_Str());
  182. AssimpAppSequence* newAssimpSeq = new AssimpAppSequence(mScene->mAnimations[n]);
  183. appSequences.push_back(newAssimpSeq);
  184. }
  185. }
  186. void AssimpShapeLoader::updateMaterialsScript(const Torque::Path &path)
  187. {
  188. Torque::Path scriptPath(path);
  189. scriptPath.setFileName("materials");
  190. scriptPath.setExtension("cs");
  191. // First see what materials we need to update
  192. PersistenceManager persistMgr;
  193. for ( U32 iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++ )
  194. {
  195. AssimpAppMaterial *mat = dynamic_cast<AssimpAppMaterial*>( AppMesh::appMaterials[iMat] );
  196. if ( mat )
  197. {
  198. Material *mappedMat;
  199. if ( Sim::findObject( MATMGR->getMapEntry( mat->getName() ), mappedMat ) )
  200. {
  201. // Only update existing materials if forced to
  202. if ( ColladaUtils::getOptions().forceUpdateMaterials )
  203. persistMgr.setDirty( mappedMat );
  204. }
  205. else
  206. {
  207. // Create a new material definition
  208. persistMgr.setDirty( mat->createMaterial( scriptPath ), scriptPath.getFullPath() );
  209. }
  210. }
  211. }
  212. if ( persistMgr.getDirtyList().empty() )
  213. return;
  214. persistMgr.saveDirty();
  215. }
  216. /// Check if an up-to-date cached DTS is available for this DAE file
  217. bool AssimpShapeLoader::canLoadCachedDTS(const Torque::Path& path)
  218. {
  219. return false;
  220. // Generate the cached filename
  221. Torque::Path cachedPath(path);
  222. cachedPath.setExtension("cached.dts");
  223. // Check if a cached DTS newer than this file is available
  224. FileTime cachedModifyTime;
  225. if (Platform::getFileTimes(cachedPath.getFullPath(), NULL, &cachedModifyTime))
  226. {
  227. bool forceLoadDAE = Con::getBoolVariable("$assimp::forceLoad", false);
  228. FileTime daeModifyTime;
  229. if (!Platform::getFileTimes(path.getFullPath(), NULL, &daeModifyTime) ||
  230. (!forceLoadDAE && (Platform::compareFileTimes(cachedModifyTime, daeModifyTime) >= 0) ))
  231. {
  232. // DAE not found, or cached DTS is newer
  233. return true;
  234. }
  235. }
  236. return false;
  237. }
  238. bool AssimpShapeLoader::ignoreNode(const String& name)
  239. {
  240. // Do not add AssimpFbx dummy nodes to the TSShape. See: Assimp::FBX::ImportSettings::preservePivots
  241. // https://github.com/assimp/assimp/blob/master/code/FBXImportSettings.h#L116-L135
  242. if (name.find("_$AssimpFbx$_") != String::NPos)
  243. return true;
  244. return false;
  245. }
  246. //-----------------------------------------------------------------------------
  247. /// This function is invoked by the resource manager based on file extension.
  248. TSShape* assimpLoadShape(const Torque::Path &path)
  249. {
  250. // TODO: add .cached.dts generation.
  251. // Generate the cached filename
  252. Torque::Path cachedPath(path);
  253. cachedPath.setExtension("cached.dts");
  254. // Check if an up-to-date cached DTS version of this file exists, and
  255. // if so, use that instead.
  256. if (AssimpShapeLoader::canLoadCachedDTS(path))
  257. {
  258. FileStream cachedStream;
  259. cachedStream.open(cachedPath.getFullPath(), Torque::FS::File::Read);
  260. if (cachedStream.getStatus() == Stream::Ok)
  261. {
  262. TSShape *shape = new TSShape;
  263. bool readSuccess = shape->read(&cachedStream);
  264. cachedStream.close();
  265. if (readSuccess)
  266. {
  267. #ifdef TORQUE_DEBUG
  268. Con::printf("Loaded cached shape from %s", cachedPath.getFullPath().c_str());
  269. #endif
  270. return shape;
  271. }
  272. else
  273. delete shape;
  274. }
  275. Con::warnf("Failed to load cached shape from %s", cachedPath.getFullPath().c_str());
  276. }
  277. if (!Torque::FS::IsFile(path))
  278. {
  279. // File does not exist, bail.
  280. return NULL;
  281. }
  282. AssimpShapeLoader loader;
  283. TSShape* tss = loader.generateShape(path);
  284. if (tss)
  285. {
  286. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Import complete");
  287. Con::printf("[ASSIMP] Shape created successfully.");
  288. // Cache the model to a DTS file for faster loading next time.
  289. FileStream dtsStream;
  290. if (dtsStream.open(cachedPath.getFullPath(), Torque::FS::File::Write))
  291. {
  292. Con::printf("Writing cached shape to %s", cachedPath.getFullPath().c_str());
  293. tss->write(&dtsStream);
  294. }
  295. loader.updateMaterialsScript(path);
  296. }
  297. loader.releaseImport();
  298. return tss;
  299. }
  300. DefineEngineFunction(GetShapeInfo, GuiTreeViewCtrl*, (String filePath), ,
  301. "Returns a list of supported shape formats in filter form.\n"
  302. "Example output: DSQ Files|*.dsq|COLLADA Files|*.dae|")
  303. {
  304. Assimp::Importer importer;
  305. GuiTreeViewCtrl* treeObj = new GuiTreeViewCtrl();
  306. treeObj->registerObject();
  307. Torque::Path path = Torque::Path(filePath);
  308. // Attempt to import with Assimp.
  309. const aiScene* shapeScene = importer.ReadFile(path.getFullPath().c_str(), (aiProcessPreset_TargetRealtime_Quality | aiProcess_CalcTangentSpace)
  310. & ~aiProcess_RemoveRedundantMaterials & ~aiProcess_GenSmoothNormals);
  311. //Populate info
  312. S32 meshItem = treeObj->insertItem(0, "Shape", String::ToString("%i", shapeScene->mNumMeshes));
  313. S32 matItem = treeObj->insertItem(0, "Materials", String::ToString("%i", shapeScene->mNumMaterials));
  314. S32 animItem = treeObj->insertItem(0, "Animations", String::ToString("%i", shapeScene->mNumAnimations));
  315. S32 lightsItem = treeObj->insertItem(0, "Lights", String::ToString("%i", shapeScene->mNumLights));
  316. S32 texturesItem = treeObj->insertItem(0, "Textures", String::ToString("%i", shapeScene->mNumTextures));
  317. //S32 meshItem = ->insertItem(0, "Cameras", String::ToString("%s", shapeScene->mNumCameras));
  318. //Details!
  319. for (U32 i = 0; i < shapeScene->mNumMeshes; i++)
  320. {
  321. treeObj->insertItem(meshItem, String::ToString("%s", shapeScene->mMeshes[i]->mName));
  322. }
  323. for (U32 i = 0; i < shapeScene->mNumMaterials; i++)
  324. {
  325. aiMaterial* aiMat = shapeScene->mMaterials[i];
  326. aiString matName;
  327. aiMat->Get(AI_MATKEY_NAME, matName);
  328. aiString texPath;
  329. aiMat->GetTexture(aiTextureType::aiTextureType_DIFFUSE, 0, &texPath);
  330. treeObj->insertItem(matItem, String::ToString("%s", matName.C_Str()), String::ToString("%s", texPath.C_Str()));
  331. }
  332. for (U32 i = 0; i < shapeScene->mNumAnimations; i++)
  333. {
  334. treeObj->insertItem(animItem, String::ToString("%s", shapeScene->mAnimations[i]->mName.C_Str()));
  335. }
  336. /*for (U32 i = 0; i < shapeScene->mNumLights; i++)
  337. {
  338. treeObj->insertItem(lightsItem, String::ToString("%s", shapeScene->mLights[i]->mType));
  339. }*/
  340. return treeObj;
  341. }