assimpShapeLoader.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. }
  99. MODULE_END;
  100. //-----------------------------------------------------------------------------
  101. AssimpShapeLoader::AssimpShapeLoader()
  102. {
  103. mScene = NULL;
  104. }
  105. AssimpShapeLoader::~AssimpShapeLoader()
  106. {
  107. }
  108. void AssimpShapeLoader::releaseImport()
  109. {
  110. aiReleaseImport(mScene);
  111. }
  112. void AssimpShapeLoader::enumerateScene()
  113. {
  114. TSShapeLoader::updateProgress(TSShapeLoader::Load_ReadFile, "Reading File");
  115. Con::printf("[ASSIMP] Attempting to load file: %s", shapePath.getFullPath().c_str());
  116. // Post-Processing
  117. unsigned int ppsteps =
  118. Con::getBoolVariable("$Assimp::ConvertToLeftHanded", false) ? aiProcess_ConvertToLeftHanded : 0 |
  119. Con::getBoolVariable("$Assimp::CalcTangentSpace", false) ? aiProcess_CalcTangentSpace : 0 |
  120. Con::getBoolVariable("$Assimp::JoinIdenticalVertices", false) ? aiProcess_JoinIdenticalVertices : 0 |
  121. Con::getBoolVariable("$Assimp::ValidateDataStructure", false) ? aiProcess_ValidateDataStructure : 0 |
  122. Con::getBoolVariable("$Assimp::ImproveCacheLocality", false) ? aiProcess_ImproveCacheLocality : 0 |
  123. Con::getBoolVariable("$Assimp::RemoveRedundantMaterials", false) ? aiProcess_RemoveRedundantMaterials : 0 |
  124. Con::getBoolVariable("$Assimp::FindDegenerates", false) ? aiProcess_FindDegenerates : 0 |
  125. Con::getBoolVariable("$Assimp::FindInvalidData", false) ? aiProcess_FindInvalidData : 0 |
  126. Con::getBoolVariable("$Assimp::GenUVCoords", false) ? aiProcess_GenUVCoords : 0 |
  127. Con::getBoolVariable("$Assimp::TransformUVCoords", false) ? aiProcess_TransformUVCoords : 0 |
  128. Con::getBoolVariable("$Assimp::FindInstances", false) ? aiProcess_FindInstances : 0 |
  129. Con::getBoolVariable("$Assimp::LimitBoneWeights", false) ? aiProcess_LimitBoneWeights : 0 |
  130. Con::getBoolVariable("$Assimp::OptimizeMeshes", false) ? aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph : 0 |
  131. 0;
  132. if(Con::getBoolVariable("$Assimp::Triangulate", false))
  133. ppsteps |= aiProcess_Triangulate;
  134. if (Con::getBoolVariable("$Assimp::OptimizeMeshes", false))
  135. ppsteps |= aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph;
  136. if (Con::getBoolVariable("$Assimp::SplitLargeMeshes", false))
  137. ppsteps |= aiProcess_SplitLargeMeshes;
  138. //aiProcess_SortByPType | // make 'clean' meshes which consist of a single typ of primitives
  139. aiPropertyStore* props = aiCreatePropertyStore();
  140. aiSetImportPropertyInteger(props, AI_CONFIG_IMPORT_TER_MAKE_UVS, 1);
  141. aiSetImportPropertyInteger(props, AI_CONFIG_PP_SBP_REMOVE, (aiProcessPreset_TargetRealtime_Quality
  142. | aiProcess_FlipWindingOrder | aiProcess_FlipUVs
  143. | aiProcess_CalcTangentSpace
  144. | aiProcess_FixInfacingNormals)
  145. & ~aiProcess_RemoveRedundantMaterials);
  146. aiSetImportPropertyInteger(props, AI_CONFIG_GLOB_MEASURE_TIME, 1);
  147. aiSetImportPropertyFloat(props, AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE, 80.f);
  148. //aiSetImportPropertyInteger(props,AI_CONFIG_PP_PTV_KEEP_HIERARCHY,1);
  149. //Assimp::Importer importer;
  150. // Attempt to import with Assimp.
  151. //mScene = importer.ReadFile(shapePath.getFullPath().c_str(), (aiProcessPreset_TargetRealtime_Quality | aiProcess_FlipWindingOrder | aiProcess_FlipUVs | aiProcess_CalcTangentSpace)
  152. // & ~aiProcess_RemoveRedundantMaterials);
  153. mScene = (aiScene*)aiImportFileExWithProperties(shapePath.getFullPath().c_str(), ppsteps, NULL, props);
  154. aiReleasePropertyStore(props);
  155. if ( mScene )
  156. {
  157. Con::printf("[ASSIMP] Mesh Count: %d", mScene->mNumMeshes);
  158. Con::printf("[ASSIMP] Material Count: %d", mScene->mNumMaterials);
  159. // Load all the materials.
  160. for ( U32 i = 0; i < mScene->mNumMaterials; i++ )
  161. AppMesh::appMaterials.push_back(new AssimpAppMaterial(mScene->mMaterials[i]));
  162. // Define the root node, and process down the chain.
  163. AssimpAppNode* node = new AssimpAppNode(mScene, mScene->mRootNode, 0);
  164. if (!processNode(node))
  165. delete node;
  166. // Check for animations and process those.
  167. processAnimations();
  168. }
  169. else
  170. {
  171. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Import failed");
  172. Con::printf("[ASSIMP] Import Error: %s", aiGetErrorString());
  173. }
  174. }
  175. void AssimpShapeLoader::processAnimations()
  176. {
  177. for(U32 n = 0; n < mScene->mNumAnimations; ++n)
  178. {
  179. Con::printf("[ASSIMP] Animation Found: %s", mScene->mAnimations[n]->mName.C_Str());
  180. AssimpAppSequence* newAssimpSeq = new AssimpAppSequence(mScene->mAnimations[n]);
  181. appSequences.push_back(newAssimpSeq);
  182. }
  183. }
  184. void AssimpShapeLoader::updateMaterialsScript(const Torque::Path &path)
  185. {
  186. Torque::Path scriptPath(path);
  187. scriptPath.setFileName("materials");
  188. scriptPath.setExtension("cs");
  189. // First see what materials we need to update
  190. PersistenceManager persistMgr;
  191. for ( U32 iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++ )
  192. {
  193. AssimpAppMaterial *mat = dynamic_cast<AssimpAppMaterial*>( AppMesh::appMaterials[iMat] );
  194. if ( mat )
  195. {
  196. Material *mappedMat;
  197. if ( Sim::findObject( MATMGR->getMapEntry( mat->getName() ), mappedMat ) )
  198. {
  199. // Only update existing materials if forced to
  200. if ( ColladaUtils::getOptions().forceUpdateMaterials )
  201. persistMgr.setDirty( mappedMat );
  202. }
  203. else
  204. {
  205. // Create a new material definition
  206. persistMgr.setDirty( mat->createMaterial( scriptPath ), scriptPath.getFullPath() );
  207. }
  208. }
  209. }
  210. if ( persistMgr.getDirtyList().empty() )
  211. return;
  212. persistMgr.saveDirty();
  213. }
  214. /// Check if an up-to-date cached DTS is available for this DAE file
  215. bool AssimpShapeLoader::canLoadCachedDTS(const Torque::Path& path)
  216. {
  217. return false;
  218. // Generate the cached filename
  219. Torque::Path cachedPath(path);
  220. cachedPath.setExtension("cached.dts");
  221. // Check if a cached DTS newer than this file is available
  222. FileTime cachedModifyTime;
  223. if (Platform::getFileTimes(cachedPath.getFullPath(), NULL, &cachedModifyTime))
  224. {
  225. bool forceLoadDAE = Con::getBoolVariable("$assimp::forceLoad", false);
  226. FileTime daeModifyTime;
  227. if (!Platform::getFileTimes(path.getFullPath(), NULL, &daeModifyTime) ||
  228. (!forceLoadDAE && (Platform::compareFileTimes(cachedModifyTime, daeModifyTime) >= 0) ))
  229. {
  230. // DAE not found, or cached DTS is newer
  231. return true;
  232. }
  233. }
  234. return false;
  235. }
  236. //-----------------------------------------------------------------------------
  237. /// This function is invoked by the resource manager based on file extension.
  238. TSShape* assimpLoadShape(const Torque::Path &path)
  239. {
  240. // TODO: add .cached.dts generation.
  241. // Generate the cached filename
  242. Torque::Path cachedPath(path);
  243. cachedPath.setExtension("cached.dts");
  244. // Check if an up-to-date cached DTS version of this file exists, and
  245. // if so, use that instead.
  246. if (AssimpShapeLoader::canLoadCachedDTS(path))
  247. {
  248. FileStream cachedStream;
  249. cachedStream.open(cachedPath.getFullPath(), Torque::FS::File::Read);
  250. if (cachedStream.getStatus() == Stream::Ok)
  251. {
  252. TSShape *shape = new TSShape;
  253. bool readSuccess = shape->read(&cachedStream);
  254. cachedStream.close();
  255. if (readSuccess)
  256. {
  257. #ifdef TORQUE_DEBUG
  258. Con::printf("Loaded cached shape from %s", cachedPath.getFullPath().c_str());
  259. #endif
  260. return shape;
  261. }
  262. else
  263. delete shape;
  264. }
  265. Con::warnf("Failed to load cached shape from %s", cachedPath.getFullPath().c_str());
  266. }
  267. if (!Torque::FS::IsFile(path))
  268. {
  269. // File does not exist, bail.
  270. return NULL;
  271. }
  272. AssimpShapeLoader loader;
  273. TSShape* tss = loader.generateShape(path);
  274. if (tss)
  275. {
  276. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Import complete");
  277. Con::printf("[ASSIMP] Shape created successfully.");
  278. // Cache the model to a DTS file for faster loading next time.
  279. FileStream dtsStream;
  280. if (dtsStream.open(cachedPath.getFullPath(), Torque::FS::File::Write))
  281. {
  282. Con::printf("Writing cached shape to %s", cachedPath.getFullPath().c_str());
  283. tss->write(&dtsStream);
  284. }
  285. loader.updateMaterialsScript(path);
  286. }
  287. loader.releaseImport();
  288. return tss;
  289. }
  290. DefineConsoleFunction(GetShapeInfo, GuiTreeViewCtrl*, (String filePath), ,
  291. "Returns a list of supported shape formats in filter form.\n"
  292. "Example output: DSQ Files|*.dsq|COLLADA Files|*.dae|")
  293. {
  294. Assimp::Importer importer;
  295. GuiTreeViewCtrl* treeObj = new GuiTreeViewCtrl();
  296. treeObj->registerObject();
  297. Torque::Path path = Torque::Path(filePath);
  298. // Attempt to import with Assimp.
  299. const aiScene* shapeScene = importer.ReadFile(path.getFullPath().c_str(), (aiProcessPreset_TargetRealtime_Quality | aiProcess_CalcTangentSpace)
  300. & ~aiProcess_RemoveRedundantMaterials & ~aiProcess_GenSmoothNormals);
  301. //Populate info
  302. S32 meshItem = treeObj->insertItem(0, "Shape", String::ToString("%i", shapeScene->mNumMeshes));
  303. S32 matItem = treeObj->insertItem(0, "Materials", String::ToString("%i", shapeScene->mNumMaterials));
  304. S32 animItem = treeObj->insertItem(0, "Animations", String::ToString("%i", shapeScene->mNumAnimations));
  305. S32 lightsItem = treeObj->insertItem(0, "Lights", String::ToString("%i", shapeScene->mNumLights));
  306. S32 texturesItem = treeObj->insertItem(0, "Textures", String::ToString("%i", shapeScene->mNumTextures));
  307. //S32 meshItem = ->insertItem(0, "Cameras", String::ToString("%s", shapeScene->mNumCameras));
  308. //Details!
  309. for (U32 i = 0; i < shapeScene->mNumMeshes; i++)
  310. {
  311. treeObj->insertItem(meshItem, String::ToString("%s", shapeScene->mMeshes[i]->mName));
  312. }
  313. for (U32 i = 0; i < shapeScene->mNumMaterials; i++)
  314. {
  315. aiMaterial* aiMat = shapeScene->mMaterials[i];
  316. aiString matName;
  317. aiMat->Get(AI_MATKEY_NAME, matName);
  318. aiString texPath;
  319. aiMat->GetTexture(aiTextureType::aiTextureType_DIFFUSE, 0, &texPath);
  320. treeObj->insertItem(matItem, String::ToString("%s", matName.C_Str()), String::ToString("%s", texPath.C_Str()));
  321. }
  322. for (U32 i = 0; i < shapeScene->mNumAnimations; i++)
  323. {
  324. treeObj->insertItem(animItem, String::ToString("%s", shapeScene->mAnimations[i]->mName.C_Str()));
  325. }
  326. /*for (U32 i = 0; i < shapeScene->mNumLights; i++)
  327. {
  328. treeObj->insertItem(lightsItem, String::ToString("%s", shapeScene->mLights[i]->mType));
  329. }*/
  330. return treeObj;
  331. }