assimpShapeLoader.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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/assimpAppMesh.h"
  33. #include "ts/assimp/assimpAppMaterial.h"
  34. #include "ts/assimp/assimpAppSequence.h"
  35. #include "core/util/tVector.h"
  36. #include "core/strings/findMatch.h"
  37. #include "core/strings/stringUnit.h"
  38. #include "core/stream/fileStream.h"
  39. #include "core/fileObject.h"
  40. #include "ts/tsShape.h"
  41. #include "ts/tsShapeInstance.h"
  42. #include "materials/materialManager.h"
  43. #include "console/persistenceManager.h"
  44. #include "ts/tsShapeConstruct.h"
  45. #include "core/util/zip/zipVolume.h"
  46. #include "gfx/bitmap/gBitmap.h"
  47. #include "gui/controls/guiTreeViewCtrl.h"
  48. // assimp include files.
  49. #include <assimp/cimport.h>
  50. #include <assimp/scene.h>
  51. #include <assimp/postprocess.h>
  52. #include <assimp/types.h>
  53. #include <assimp/config.h>
  54. #include <exception>
  55. MODULE_BEGIN( AssimpShapeLoader )
  56. MODULE_INIT_AFTER( ShapeLoader )
  57. MODULE_INIT
  58. {
  59. TSShapeLoader::addFormat("DirectX X", "x");
  60. TSShapeLoader::addFormat("Autodesk FBX", "fbx");
  61. TSShapeLoader::addFormat("Blender 3D", "blend" );
  62. TSShapeLoader::addFormat("3ds Max 3DS", "3ds");
  63. TSShapeLoader::addFormat("3ds Max ASE", "ase");
  64. TSShapeLoader::addFormat("Wavefront Object", "obj");
  65. TSShapeLoader::addFormat("Industry Foundation Classes (IFC/Step)", "ifc");
  66. TSShapeLoader::addFormat("Stanford Polygon Library", "ply");
  67. TSShapeLoader::addFormat("AutoCAD DXF", "dxf");
  68. TSShapeLoader::addFormat("LightWave", "lwo");
  69. TSShapeLoader::addFormat("LightWave Scene", "lws");
  70. TSShapeLoader::addFormat("Modo", "lxo");
  71. TSShapeLoader::addFormat("Stereolithography", "stl");
  72. TSShapeLoader::addFormat("AC3D", "ac");
  73. TSShapeLoader::addFormat("Milkshape 3D", "ms3d");
  74. TSShapeLoader::addFormat("TrueSpace COB", "cob");
  75. TSShapeLoader::addFormat("TrueSpace SCN", "scn");
  76. TSShapeLoader::addFormat("Ogre XML", "xml");
  77. TSShapeLoader::addFormat("Irrlicht Mesh", "irrmesh");
  78. TSShapeLoader::addFormat("Irrlicht Scene", "irr");
  79. TSShapeLoader::addFormat("Quake I", "mdl" );
  80. TSShapeLoader::addFormat("Quake II", "md2" );
  81. TSShapeLoader::addFormat("Quake III Mesh", "md3");
  82. TSShapeLoader::addFormat("Quake III Map/BSP", "pk3");
  83. TSShapeLoader::addFormat("Return to Castle Wolfenstein", "mdc");
  84. TSShapeLoader::addFormat("Doom 3", "md5" );
  85. TSShapeLoader::addFormat("Valve SMD", "smd");
  86. TSShapeLoader::addFormat("Valve VTA", "vta");
  87. TSShapeLoader::addFormat("Starcraft II M3", "m3");
  88. TSShapeLoader::addFormat("Unreal", "3d");
  89. TSShapeLoader::addFormat("BlitzBasic 3D", "b3d" );
  90. TSShapeLoader::addFormat("Quick3D Q3D", "q3d");
  91. TSShapeLoader::addFormat("Quick3D Q3S", "q3s");
  92. TSShapeLoader::addFormat("Neutral File Format", "nff");
  93. TSShapeLoader::addFormat("Object File Format", "off");
  94. TSShapeLoader::addFormat("PovRAY Raw", "raw");
  95. TSShapeLoader::addFormat("Terragen Terrain", "ter");
  96. TSShapeLoader::addFormat("3D GameStudio (3DGS)", "mdl");
  97. TSShapeLoader::addFormat("3D GameStudio (3DGS) Terrain", "hmp");
  98. TSShapeLoader::addFormat("Izware Nendo", "ndo");
  99. TSShapeLoader::addFormat("gltf", "gltf");
  100. TSShapeLoader::addFormat("gltf binary", "glb");
  101. }
  102. MODULE_END;
  103. //-----------------------------------------------------------------------------
  104. AssimpShapeLoader::AssimpShapeLoader()
  105. {
  106. mScene = NULL;
  107. }
  108. AssimpShapeLoader::~AssimpShapeLoader()
  109. {
  110. }
  111. void AssimpShapeLoader::releaseImport()
  112. {
  113. }
  114. void applyTransformation(aiNode* node, const aiMatrix4x4& transform) {
  115. node->mTransformation = transform * node->mTransformation; // Apply transformation to the node
  116. }
  117. void scaleScene(const aiScene* scene, F32 scaleFactor) {
  118. aiMatrix4x4 scaleMatrix;
  119. scaleMatrix = aiMatrix4x4::Scaling(aiVector3D(scaleFactor, scaleFactor, scaleFactor), scaleMatrix);
  120. applyTransformation(scene->mRootNode, scaleMatrix);
  121. }
  122. void debugSceneMetaData(const aiScene* scene) {
  123. if (!scene->mMetaData) {
  124. Con::printf("[ASSIMP] No metadata available.");
  125. return;
  126. }
  127. for (U32 i = 0; i < scene->mMetaData->mNumProperties; ++i) {
  128. const char* key = scene->mMetaData->mKeys[i].C_Str();
  129. aiMetadataType type = scene->mMetaData->mValues[i].mType;
  130. Con::printf("[ASSIMP] Metadata key: %s", key);
  131. switch (type) {
  132. case AI_BOOL:
  133. Con::printf(" Value: %d (bool)", *(bool*)scene->mMetaData->mValues[i].mData);
  134. break;
  135. case AI_INT32:
  136. Con::printf(" Value: %d (int)", *(S32*)scene->mMetaData->mValues[i].mData);
  137. break;
  138. case AI_UINT64:
  139. Con::printf(" Value: %llu (uint64)", *(U64*)scene->mMetaData->mValues[i].mData);
  140. break;
  141. case AI_FLOAT:
  142. Con::printf(" Value: %f (float)", *(F32*)scene->mMetaData->mValues[i].mData);
  143. break;
  144. case AI_DOUBLE:
  145. Con::printf(" Value: %f (double)", *(F64*)scene->mMetaData->mValues[i].mData);
  146. break;
  147. case AI_AISTRING:
  148. Con::printf(" Value: %s (string)", ((aiString*)scene->mMetaData->mValues[i].mData)->C_Str());
  149. break;
  150. case AI_AIVECTOR3D:
  151. {
  152. aiVector3D* vec = (aiVector3D*)scene->mMetaData->mValues[i].mData;
  153. Con::printf(" Value: (%f, %f, %f) (vector3d)", vec->x, vec->y, vec->z);
  154. }
  155. break;
  156. default:
  157. Con::printf(" Unknown metadata type.");
  158. }
  159. }
  160. }
  161. void AssimpShapeLoader::enumerateScene()
  162. {
  163. TSShapeLoader::updateProgress(TSShapeLoader::Load_ReadFile, "Reading File");
  164. Con::printf("[ASSIMP] Attempting to load file: %s", shapePath.getFullPath().c_str());
  165. // Define post-processing steps
  166. U32 ppsteps = aiProcess_Triangulate | /*aiProcess_PreTransformVertices |*/ aiProcess_ConvertToLeftHanded & ~aiProcess_MakeLeftHanded;
  167. const auto& options = ColladaUtils::getOptions();
  168. if (options.calcTangentSpace) ppsteps |= aiProcess_CalcTangentSpace;
  169. if (options.joinIdenticalVerts) ppsteps |= aiProcess_JoinIdenticalVertices;
  170. if (options.removeRedundantMats) ppsteps |= aiProcess_RemoveRedundantMaterials;
  171. if (options.genUVCoords) ppsteps |= aiProcess_GenUVCoords;
  172. if (options.transformUVCoords) ppsteps |= aiProcess_TransformUVCoords;
  173. if (options.findInstances) ppsteps |= aiProcess_FindInstances;
  174. if (options.limitBoneWeights) ppsteps |= aiProcess_LimitBoneWeights;
  175. if (Con::getBoolVariable("$Assimp::OptimizeMeshes", false)) {
  176. ppsteps |= aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph;
  177. }
  178. if (Con::getBoolVariable("$Assimp::SplitLargeMeshes", false)) {
  179. ppsteps |= aiProcess_SplitLargeMeshes;
  180. }
  181. ppsteps |= aiProcess_ValidateDataStructure;
  182. struct aiLogStream shapeLog = aiGetPredefinedLogStream(aiDefaultLogStream_STDOUT, NULL);
  183. shapeLog.callback = assimpLogCallback;
  184. shapeLog.user = 0;
  185. aiAttachLogStream(&shapeLog);
  186. #ifdef TORQUE_DEBUG
  187. aiEnableVerboseLogging(true);
  188. #endif
  189. /*mImporter.SetPropertyInteger(AI_CONFIG_PP_PTV_KEEP_HIERARCHY, 1);
  190. mImporter.SetPropertyInteger(AI_CONFIG_PP_PTV_ADD_ROOT_TRANSFORMATION, 1);
  191. mImporter.SetPropertyMatrix(AI_CONFIG_PP_PTV_ROOT_TRANSFORMATION, aiMatrix4x4(1, 0, 0, 0,
  192. 0, 0, -1, 0,
  193. 0, 1, 0, 0,
  194. 0, 0, 0, 1));*/
  195. // Read the file
  196. mScene = mImporter.ReadFile(shapePath.getFullPath().c_str(), ppsteps);
  197. if (!mScene || (mScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) || !mScene->mRootNode) {
  198. Con::errorf("[ASSIMP] ERROR: Could not load file: %s", shapePath.getFullPath().c_str());
  199. Con::errorf("[ASSIMP] Importer error: %s", mImporter.GetErrorString());
  200. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Import failed");
  201. return;
  202. }
  203. Con::printf("[ASSIMP] Mesh Count: %d", mScene->mNumMeshes);
  204. Con::printf("[ASSIMP] Material Count: %d", mScene->mNumMaterials);
  205. #ifdef TORQUE_DEBUG
  206. debugSceneMetaData(mScene);
  207. #endif
  208. ColladaUtils::getOptions().upAxis = UPAXISTYPE_Y_UP; // default to Y up for assimp.
  209. // Handle scaling
  210. configureImportUnits();
  211. // Format-specific adjustments
  212. String fileExt = String::ToLower(shapePath.getExtension());
  213. const aiImporterDesc* importerDescription = aiGetImporterDesc(fileExt.c_str());
  214. if (importerDescription && dStrcmp(importerDescription->mName, "Autodesk FBX Importer") == 0) {
  215. Con::printf("[ASSIMP] Detected FBX format, checking unit scale...");
  216. F32 scaleFactor = ColladaUtils::getOptions().unit;
  217. if (scaleFactor != 1.0f) {
  218. Con::printf("[ASSIMP] Applying FBX scale factor: %f", scaleFactor);
  219. scaleScene(mScene, scaleFactor);
  220. }
  221. else
  222. {
  223. scaleScene(mScene, 0.01f);
  224. }
  225. }
  226. for (U32 i = 0; i < mScene->mNumTextures; ++i) {
  227. extractTexture(i, mScene->mTextures[i]);
  228. }
  229. // Load all materials
  230. AssimpAppMaterial::sDefaultMatNumber = 0;
  231. for (U32 i = 0; i < mScene->mNumMaterials; ++i) {
  232. AppMesh::appMaterials.push_back(new AssimpAppMaterial(mScene->mMaterials[i]));
  233. }
  234. // Setup LOD checks
  235. detectDetails();
  236. aiMatrix4x4 sceneRoot = aiMatrix4x4(1, 0, 0, 0,
  237. 0, 0, -1, 0,
  238. 0, 1, 0, 0,
  239. 0, 0, 0, 1);
  240. applyTransformation(mScene->mRootNode, sceneRoot);
  241. // Process the scene graph
  242. AssimpAppNode* rootNode = new AssimpAppNode(mScene, mScene->mRootNode, 0);
  243. if (!processNode(rootNode)) {
  244. delete rootNode;
  245. }
  246. processAssimpNode(mScene->mRootNode, mScene, rootNode);
  247. // Add a bounds node if none exists
  248. if (!boundsNode) {
  249. aiNode* reqNode = new aiNode("bounds");
  250. mScene->mRootNode->addChildren(1, &reqNode);
  251. reqNode->mTransformation = aiMatrix4x4();// *sceneRoot;
  252. AssimpAppNode* appBoundsNode = new AssimpAppNode(mScene, reqNode);
  253. if (!processNode(appBoundsNode)) {
  254. delete appBoundsNode;
  255. }
  256. }
  257. // Process animations if available
  258. processAnimations();
  259. // Clean up log stream
  260. aiDetachLogStream(&shapeLog);
  261. }
  262. void AssimpShapeLoader::configureImportUnits() {
  263. auto& options = ColladaUtils::getOptions();
  264. // Configure unit scaling
  265. if (options.unit <= 0.0f) {
  266. F64 unitScaleFactor = 1.0;
  267. if (!getMetaDouble("UnitScaleFactor", unitScaleFactor)) {
  268. F32 floatVal;
  269. S32 intVal;
  270. if (getMetaFloat("UnitScaleFactor", floatVal)) {
  271. unitScaleFactor = static_cast<F64>(floatVal);
  272. }
  273. else if (getMetaInt("UnitScaleFactor", intVal)) {
  274. unitScaleFactor = static_cast<F64>(intVal);
  275. }
  276. }
  277. options.unit = static_cast<F32>(unitScaleFactor);
  278. }
  279. }
  280. void AssimpShapeLoader::processAssimpNode(const aiNode* node, const aiScene* scene, AssimpAppNode* parentNode)
  281. {
  282. AssimpAppNode* currNode;
  283. if (node == scene->mRootNode)
  284. {
  285. currNode = parentNode;
  286. }
  287. else
  288. {
  289. currNode = new AssimpAppNode(scene, node, parentNode);
  290. if (parentNode)
  291. {
  292. parentNode->addChild(currNode);
  293. }
  294. for (U32 i = 0; i < node->mNumMeshes; i++)
  295. {
  296. U32 meshIdx = node->mMeshes[i];
  297. const aiMesh* mesh = scene->mMeshes[meshIdx];
  298. AssimpAppMesh* curMesh = new AssimpAppMesh(mesh, currNode);
  299. currNode->addMesh(curMesh);
  300. }
  301. }
  302. // Recursively process child nodes
  303. for (U32 i = 0; i < node->mNumChildren; i++)
  304. {
  305. processAssimpNode(node->mChildren[i], scene, currNode);
  306. }
  307. }
  308. void AssimpShapeLoader::processAnimations()
  309. {
  310. // add all animations into 1 ambient animation.
  311. aiAnimation* ambientSeq = new aiAnimation();
  312. ambientSeq->mName = "ambient";
  313. Vector<aiNodeAnim*> ambientChannels;
  314. F32 duration = 0.0f;
  315. F32 ticks = 0.0f;
  316. if (mScene->mNumAnimations > 0)
  317. {
  318. for (U32 i = 0; i < mScene->mNumAnimations; ++i)
  319. {
  320. aiAnimation* anim = mScene->mAnimations[i];
  321. ticks = anim->mTicksPerSecond;
  322. duration = 0.0f;
  323. for (U32 j = 0; j < anim->mNumChannels; j++)
  324. {
  325. aiNodeAnim* nodeAnim = anim->mChannels[j];
  326. // Determine the maximum keyframe time for this animation
  327. F32 maxKeyTime = 0.0f;
  328. for (U32 k = 0; k < nodeAnim->mNumPositionKeys; k++) {
  329. maxKeyTime = getMax(maxKeyTime, (F32)nodeAnim->mPositionKeys[k].mTime);
  330. }
  331. for (U32 k = 0; k < nodeAnim->mNumRotationKeys; k++) {
  332. maxKeyTime = getMax(maxKeyTime, (F32)nodeAnim->mRotationKeys[k].mTime);
  333. }
  334. for (U32 k = 0; k < nodeAnim->mNumScalingKeys; k++) {
  335. maxKeyTime = getMax(maxKeyTime, (F32)nodeAnim->mScalingKeys[k].mTime);
  336. }
  337. ambientChannels.push_back(nodeAnim);
  338. duration = getMax(duration, maxKeyTime);
  339. }
  340. }
  341. ambientSeq->mNumChannels = ambientChannels.size();
  342. ambientSeq->mChannels = ambientChannels.address();
  343. ambientSeq->mDuration = duration;
  344. ambientSeq->mTicksPerSecond = ticks;
  345. AssimpAppSequence* defaultAssimpSeq = new AssimpAppSequence(ambientSeq);
  346. appSequences.push_back(defaultAssimpSeq);
  347. }
  348. }
  349. void AssimpShapeLoader::computeBounds(Box3F& bounds)
  350. {
  351. TSShapeLoader::computeBounds(bounds);
  352. // Check if the model origin needs adjusting
  353. bool adjustCenter = ColladaUtils::getOptions().adjustCenter;
  354. bool adjustFloor = ColladaUtils::getOptions().adjustFloor;
  355. if (bounds.isValidBox() && (adjustCenter || adjustFloor))
  356. {
  357. // Compute shape offset
  358. Point3F shapeOffset = Point3F::Zero;
  359. if (adjustCenter)
  360. {
  361. bounds.getCenter(&shapeOffset);
  362. shapeOffset = -shapeOffset;
  363. }
  364. if (adjustFloor)
  365. shapeOffset.z = -bounds.minExtents.z;
  366. // Adjust bounds
  367. bounds.minExtents += shapeOffset;
  368. bounds.maxExtents += shapeOffset;
  369. // Now adjust all positions for root level nodes (nodes with no parent)
  370. for (S32 iNode = 0; iNode < shape->nodes.size(); iNode++)
  371. {
  372. if (!appNodes[iNode]->isParentRoot())
  373. continue;
  374. // Adjust default translation
  375. shape->defaultTranslations[iNode] += shapeOffset;
  376. // Adjust animated translations
  377. for (S32 iSeq = 0; iSeq < shape->sequences.size(); iSeq++)
  378. {
  379. const TSShape::Sequence& seq = shape->sequences[iSeq];
  380. if (seq.translationMatters.test(iNode))
  381. {
  382. for (S32 iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
  383. {
  384. S32 index = seq.baseTranslation + seq.translationMatters.count(iNode)*seq.numKeyframes + iFrame;
  385. shape->nodeTranslations[index] += shapeOffset;
  386. }
  387. }
  388. }
  389. }
  390. }
  391. }
  392. bool AssimpShapeLoader::fillGuiTreeView(const char* sourceShapePath, GuiTreeViewCtrl* tree)
  393. {
  394. Assimp::Importer importer;
  395. Torque::Path path(sourceShapePath);
  396. String cleanFile = AppMaterial::cleanString(path.getFileName());
  397. // Attempt to import with Assimp.
  398. const aiScene* shapeScene = importer.ReadFile(path.getFullPath().c_str(), (aiProcessPreset_TargetRealtime_Quality | aiProcess_CalcTangentSpace)
  399. & ~aiProcess_RemoveRedundantMaterials & ~aiProcess_GenSmoothNormals);
  400. if (!shapeScene)
  401. {
  402. Con::printf("AssimpShapeLoader::fillGuiTreeView - Assimp Error: %s", importer.GetErrorString());
  403. return false;
  404. }
  405. mScene = shapeScene;
  406. // Initialize tree
  407. tree->removeItem(0);
  408. S32 meshItem = tree->insertItem(0, "Meshes", String::ToString("%i", shapeScene->mNumMeshes));
  409. S32 matItem = tree->insertItem(0, "Materials", String::ToString("%i", shapeScene->mNumMaterials));
  410. S32 animItem = tree->insertItem(0, "Animations", String::ToString("%i", shapeScene->mNumAnimations));
  411. //S32 lightsItem = tree->insertItem(0, "Lights", String::ToString("%i", shapeScene->mNumLights));
  412. //S32 texturesItem = tree->insertItem(0, "Textures", String::ToString("%i", shapeScene->mNumTextures));
  413. //Details!
  414. U32 numPolys = 0;
  415. U32 numVerts = 0;
  416. for (U32 i = 0; i < shapeScene->mNumMeshes; i++)
  417. {
  418. tree->insertItem(meshItem, String::ToString("%s", shapeScene->mMeshes[i]->mName.C_Str()));
  419. numPolys += shapeScene->mMeshes[i]->mNumFaces;
  420. numVerts += shapeScene->mMeshes[i]->mNumVertices;
  421. }
  422. U32 defaultMatNumber = 0;
  423. for (U32 i = 0; i < shapeScene->mNumMaterials; i++)
  424. {
  425. aiMaterial* aiMat = shapeScene->mMaterials[i];
  426. aiString matName;
  427. aiMat->Get(AI_MATKEY_NAME, matName);
  428. String name = matName.C_Str();
  429. if (name.isEmpty())
  430. {
  431. name = AppMaterial::cleanString(path.getFileName());
  432. name += "_defMat";
  433. name += String::ToString("%d", defaultMatNumber);
  434. defaultMatNumber++;
  435. }
  436. aiString texPath;
  437. aiMat->GetTexture(aiTextureType::aiTextureType_DIFFUSE, 0, &texPath);
  438. String texName = texPath.C_Str();
  439. if (texName.isEmpty())
  440. {
  441. aiColor3D read_color(1.f, 1.f, 1.f);
  442. if (AI_SUCCESS == aiMat->Get(AI_MATKEY_COLOR_DIFFUSE, read_color))
  443. texName = String::ToString("Color: %0.3f %0.3f %0.3f", (F32)read_color.r, (F32)read_color.g, (F32)read_color.b); //formatted as words for easy parsing
  444. else
  445. texName = "No Texture";
  446. }
  447. else
  448. texName = AssimpAppMaterial::cleanTextureName(texName, cleanFile, sourceShapePath, true);
  449. tree->insertItem(matItem, String::ToString("%s", name.c_str()), String::ToString("%s", texName.c_str()));
  450. }
  451. if (shapeScene->mNumAnimations == 0)
  452. {
  453. tree->insertItem(animItem, "ambient", "animation", "", 0, 0);
  454. }
  455. else
  456. {
  457. for (U32 i = 0; i < shapeScene->mNumAnimations; i++)
  458. {
  459. tree->insertItem(animItem, shapeScene->mAnimations[i]->mName.C_Str(), "animation", "", 0, 0);
  460. }
  461. }
  462. U32 numNodes = 0;
  463. if (shapeScene->mRootNode)
  464. {
  465. S32 nodesItem = tree->insertItem(0, "Nodes", "");
  466. addNodeToTree(nodesItem, shapeScene->mRootNode, tree, numNodes);
  467. tree->setItemValue(nodesItem, String::ToString("%i", numNodes));
  468. }
  469. U32 numMetaTags = shapeScene->mMetaData ? shapeScene->mMetaData->mNumProperties : 0;
  470. if (numMetaTags)
  471. addMetaDataToTree(shapeScene->mMetaData, tree);
  472. F64 unit;
  473. if (!getMetaDouble("UnitScaleFactor", unit))
  474. unit = 1.0f;
  475. S32 upAxis;
  476. if (!getMetaInt("UpAxis", upAxis))
  477. upAxis = UPAXISTYPE_Z_UP;
  478. /*for (U32 i = 0; i < shapeScene->mNumLights; i++)
  479. {
  480. treeObj->insertItem(lightsItem, String::ToString("%s", shapeScene->mLights[i]->mType));
  481. }*/
  482. // Store shape information in the tree control
  483. tree->setDataField(StringTable->insert("_nodeCount"), 0, avar("%d", numNodes));
  484. tree->setDataField(StringTable->insert("_meshCount"), 0, avar("%d", shapeScene->mNumMeshes));
  485. tree->setDataField(StringTable->insert("_polygonCount"), 0, avar("%d", numPolys));
  486. tree->setDataField(StringTable->insert("_materialCount"), 0, avar("%d", shapeScene->mNumMaterials));
  487. tree->setDataField(StringTable->insert("_lightCount"), 0, avar("%d", shapeScene->mNumLights));
  488. tree->setDataField(StringTable->insert("_animCount"), 0, avar("%d", shapeScene->mNumAnimations));
  489. tree->setDataField(StringTable->insert("_textureCount"), 0, avar("%d", shapeScene->mNumTextures));
  490. tree->setDataField(StringTable->insert("_vertCount"), 0, avar("%d", numVerts));
  491. tree->setDataField(StringTable->insert("_metaTagCount"), 0, avar("%d", numMetaTags));
  492. tree->setDataField(StringTable->insert("_unit"), 0, avar("%g", (F32)unit));
  493. if (upAxis == UPAXISTYPE_X_UP)
  494. tree->setDataField(StringTable->insert("_upAxis"), 0, "X_AXIS");
  495. else if (upAxis == UPAXISTYPE_Y_UP)
  496. tree->setDataField(StringTable->insert("_upAxis"), 0, "Y_AXIS");
  497. else
  498. tree->setDataField(StringTable->insert("_upAxis"), 0, "Z_AXIS");
  499. return true;
  500. }
  501. void AssimpShapeLoader::updateMaterialsScript(const Torque::Path &path)
  502. {
  503. return;
  504. /*
  505. Torque::Path scriptPath(path);
  506. scriptPath.setFileName("materials");
  507. scriptPath.setExtension(TORQUE_SCRIPT_EXTENSION);
  508. // First see what materials we need to update
  509. PersistenceManager persistMgr;
  510. for ( U32 iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++ )
  511. {
  512. AssimpAppMaterial *mat = dynamic_cast<AssimpAppMaterial*>( AppMesh::appMaterials[iMat] );
  513. if ( mat )
  514. {
  515. Material *mappedMat;
  516. if ( Sim::findObject( MATMGR->getMapEntry( mat->getName() ), mappedMat ) )
  517. {
  518. // Only update existing materials if forced to
  519. if (ColladaUtils::getOptions().forceUpdateMaterials)
  520. {
  521. mat->initMaterial(scriptPath, mappedMat);
  522. persistMgr.setDirty(mappedMat);
  523. }
  524. }
  525. else
  526. {
  527. // Create a new material definition
  528. persistMgr.setDirty( mat->createMaterial( scriptPath ), scriptPath.getFullPath() );
  529. }
  530. }
  531. }
  532. if ( persistMgr.getDirtyList().empty() )
  533. return;
  534. persistMgr.saveDirty();
  535. */
  536. }
  537. /// Check if an up-to-date cached DTS is available for this DAE file
  538. bool AssimpShapeLoader::canLoadCachedDTS(const Torque::Path& path)
  539. {
  540. // Generate the cached filename
  541. Torque::Path cachedPath(path);
  542. cachedPath.setExtension("cached.dts");
  543. // Check if a cached DTS newer than this file is available
  544. FileTime cachedModifyTime;
  545. if (Platform::getFileTimes(cachedPath.getFullPath(), NULL, &cachedModifyTime))
  546. {
  547. bool forceLoad = Con::getBoolVariable("$assimp::forceLoad", false);
  548. FileTime daeModifyTime;
  549. if (!Platform::getFileTimes(path.getFullPath(), NULL, &daeModifyTime) ||
  550. (!forceLoad && (Platform::compareFileTimes(cachedModifyTime, daeModifyTime) >= 0) ))
  551. {
  552. // Original file not found, or cached DTS is newer
  553. return true;
  554. }
  555. }
  556. return false;
  557. }
  558. void AssimpShapeLoader::assimpLogCallback(const char* message, char* user)
  559. {
  560. Con::printf("[Assimp log message] %s", StringUnit::getUnit(message, 0, "\n"));
  561. }
  562. bool AssimpShapeLoader::ignoreNode(const String& name)
  563. {
  564. // Do not add AssimpFbx dummy nodes to the TSShape. See: Assimp::FBX::ImportSettings::preservePivots
  565. // https://github.com/assimp/assimp/blob/master/code/FBXImportSettings.h#L116-L135
  566. if (name.find("_$AssimpFbx$_") != String::NPos)
  567. return true;
  568. if (FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().alwaysImport, name, false))
  569. return false;
  570. return FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().neverImport, name, false);
  571. }
  572. bool AssimpShapeLoader::ignoreMesh(const String& name)
  573. {
  574. if (FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().alwaysImportMesh, name, false))
  575. return false;
  576. else
  577. return FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().neverImportMesh, name, false);
  578. }
  579. void AssimpShapeLoader::detectDetails()
  580. {
  581. // Set LOD option
  582. bool singleDetail = true;
  583. switch (ColladaUtils::getOptions().lodType)
  584. {
  585. case ColladaUtils::ImportOptions::DetectDTS:
  586. // Check for a baseXX->startXX hierarchy at the top-level, if we find
  587. // one, use trailing numbers for LOD, otherwise use a single size
  588. for (S32 iNode = 0; singleDetail && (iNode < mScene->mRootNode->mNumChildren); iNode++) {
  589. aiNode* node = mScene->mRootNode->mChildren[iNode];
  590. if (node && dStrStartsWith(node->mName.C_Str(), "base")) {
  591. for (S32 iChild = 0; iChild < node->mNumChildren; iChild++) {
  592. aiNode* child = node->mChildren[iChild];
  593. if (child && dStrStartsWith(child->mName.C_Str(), "start")) {
  594. singleDetail = false;
  595. break;
  596. }
  597. }
  598. }
  599. }
  600. break;
  601. case ColladaUtils::ImportOptions::SingleSize:
  602. singleDetail = true;
  603. break;
  604. case ColladaUtils::ImportOptions::TrailingNumber:
  605. singleDetail = false;
  606. break;
  607. default:
  608. break;
  609. }
  610. AssimpAppMesh::fixDetailSize(singleDetail, ColladaUtils::getOptions().singleDetailSize);
  611. }
  612. void AssimpShapeLoader::extractTexture(U32 index, aiTexture* pTex)
  613. { // Cache an embedded texture to disk
  614. updateProgress(Load_EnumerateScene, "Extracting Textures...", mScene->mNumTextures, index);
  615. Con::printf("[Assimp] Extracting Texture %s, W: %d, H: %d, %d of %d, format hint: (%s)", pTex->mFilename.C_Str(),
  616. pTex->mWidth, pTex->mHeight, index, mScene->mNumTextures, pTex->achFormatHint);
  617. // Create the texture filename
  618. String cleanFile = AppMaterial::cleanString(TSShapeLoader::getShapePath().getFileName());
  619. String texName = String::ToString("%s_cachedTex%d", cleanFile.c_str(), index);
  620. Torque::Path texPath = shapePath;
  621. texPath.setFileName(texName);
  622. if (pTex->mHeight == 0)
  623. { // Compressed format, write the data directly to disc
  624. texPath.setExtension(pTex->achFormatHint);
  625. FileStream *outputStream;
  626. if ((outputStream = FileStream::createAndOpen(texPath.getFullPath(), Torque::FS::File::Write)) != NULL)
  627. {
  628. outputStream->setPosition(0);
  629. outputStream->write(pTex->mWidth, pTex->pcData);
  630. outputStream->close();
  631. delete outputStream;
  632. }
  633. }
  634. else
  635. { // Embedded pixel data, fill a bitmap and save it.
  636. GFXTexHandle shapeTex;
  637. shapeTex.set(pTex->mWidth, pTex->mHeight, GFXFormatR8G8B8A8_SRGB, &GFXDynamicTextureSRGBProfile,
  638. String::ToString("AssimpShapeLoader (%s:%i)", __FILE__, __LINE__), 1, 0);
  639. GFXLockedRect *rect = shapeTex.lock();
  640. for (U32 y = 0; y < pTex->mHeight; ++y)
  641. {
  642. for (U32 x = 0; x < pTex->mWidth; ++x)
  643. {
  644. U32 targetIndex = (y * rect->pitch) + (x * 4);
  645. U32 sourceIndex = ((y * pTex->mWidth) + x) * 4;
  646. rect->bits[targetIndex] = pTex->pcData[sourceIndex].r;
  647. rect->bits[targetIndex + 1] = pTex->pcData[sourceIndex].g;
  648. rect->bits[targetIndex + 2] = pTex->pcData[sourceIndex].b;
  649. rect->bits[targetIndex + 3] = pTex->pcData[sourceIndex].a;
  650. }
  651. }
  652. shapeTex.unlock();
  653. texPath.setExtension("png");
  654. shapeTex->dumpToDisk("PNG", texPath.getFullPath());
  655. }
  656. }
  657. void AssimpShapeLoader::addNodeToTree(S32 parentItem, aiNode* node, GuiTreeViewCtrl* tree, U32& nodeCount)
  658. {
  659. // Add this node
  660. S32 nodeItem = parentItem;
  661. String nodeName = node->mName.C_Str();
  662. if (!ignoreNode(nodeName))
  663. {
  664. if (nodeName.isEmpty())
  665. nodeName = "null";
  666. nodeItem = tree->insertItem(parentItem, nodeName.c_str(), String::ToString("%i", node->mNumChildren));
  667. nodeCount++;
  668. }
  669. // Add any child nodes
  670. for (U32 n = 0; n < node->mNumChildren; ++n)
  671. addNodeToTree(nodeItem, node->mChildren[n], tree, nodeCount);
  672. }
  673. void AssimpShapeLoader::addMetaDataToTree(const aiMetadata* metaData, GuiTreeViewCtrl* tree)
  674. {
  675. S32 metaItem = tree->insertItem(0, "MetaData", String::ToString("%i", metaData->mNumProperties));
  676. aiString valString;
  677. aiVector3D valVec;
  678. for (U32 n = 0; n < metaData->mNumProperties; ++n)
  679. {
  680. String keyStr = metaData->mKeys[n].C_Str();
  681. keyStr += ": ";
  682. switch (metaData->mValues[n].mType)
  683. {
  684. case AI_BOOL:
  685. keyStr += ((bool)metaData->mValues[n].mData) ? "true" : "false";
  686. break;
  687. case AI_INT32:
  688. keyStr += String::ToString(*((S32*)(metaData->mValues[n].mData)));
  689. break;
  690. case AI_UINT64:
  691. keyStr += String::ToString("%I64u", *((U64*)metaData->mValues[n].mData));
  692. break;
  693. case AI_FLOAT:
  694. keyStr += String::ToString(*((F32*)metaData->mValues[n].mData));
  695. break;
  696. case AI_DOUBLE:
  697. keyStr += String::ToString(*((F64*)metaData->mValues[n].mData));
  698. break;
  699. case AI_AISTRING:
  700. metaData->Get<aiString>(metaData->mKeys[n], valString);
  701. keyStr += valString.C_Str();
  702. break;
  703. case AI_AIVECTOR3D:
  704. metaData->Get<aiVector3D>(metaData->mKeys[n], valVec);
  705. keyStr += String::ToString("%f, %f, %f", valVec.x, valVec.y, valVec.z);
  706. break;
  707. default:
  708. break;
  709. }
  710. tree->insertItem(metaItem, keyStr.c_str(), String::ToString("%i", n));
  711. }
  712. }
  713. bool AssimpShapeLoader::getMetabool(const char* key, bool& boolVal)
  714. {
  715. if (!mScene || !mScene->mMetaData)
  716. return false;
  717. String keyStr = key;
  718. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  719. {
  720. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  721. {
  722. if (mScene->mMetaData->mValues[n].mType == AI_BOOL)
  723. {
  724. boolVal = (bool)mScene->mMetaData->mValues[n].mData;
  725. return true;
  726. }
  727. }
  728. }
  729. return false;
  730. }
  731. bool AssimpShapeLoader::getMetaInt(const char* key, S32& intVal)
  732. {
  733. if (!mScene || !mScene->mMetaData)
  734. return false;
  735. String keyStr = key;
  736. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  737. {
  738. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  739. {
  740. if (mScene->mMetaData->mValues[n].mType == AI_INT32)
  741. {
  742. intVal = *((S32*)(mScene->mMetaData->mValues[n].mData));
  743. return true;
  744. }
  745. }
  746. }
  747. return false;
  748. }
  749. bool AssimpShapeLoader::getMetaFloat(const char* key, F32& floatVal)
  750. {
  751. if (!mScene || !mScene->mMetaData)
  752. return false;
  753. String keyStr = key;
  754. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  755. {
  756. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  757. {
  758. if (mScene->mMetaData->mValues[n].mType == AI_FLOAT)
  759. {
  760. floatVal = *((F32*)mScene->mMetaData->mValues[n].mData);
  761. return true;
  762. }
  763. }
  764. }
  765. return false;
  766. }
  767. bool AssimpShapeLoader::getMetaDouble(const char* key, F64& doubleVal)
  768. {
  769. if (!mScene || !mScene->mMetaData)
  770. return false;
  771. String keyStr = key;
  772. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  773. {
  774. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  775. {
  776. if (mScene->mMetaData->mValues[n].mType == AI_DOUBLE)
  777. {
  778. doubleVal = *((F64*)mScene->mMetaData->mValues[n].mData);
  779. return true;
  780. }
  781. }
  782. }
  783. return false;
  784. }
  785. bool AssimpShapeLoader::getMetaString(const char* key, String& stringVal)
  786. {
  787. if (!mScene || !mScene->mMetaData)
  788. return false;
  789. String keyStr = key;
  790. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  791. {
  792. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  793. {
  794. if (mScene->mMetaData->mValues[n].mType == AI_AISTRING)
  795. {
  796. aiString valString;
  797. mScene->mMetaData->Get<aiString>(mScene->mMetaData->mKeys[n], valString);
  798. stringVal = valString.C_Str();
  799. return true;
  800. }
  801. }
  802. }
  803. return false;
  804. }
  805. //-----------------------------------------------------------------------------
  806. /// This function is invoked by the resource manager based on file extension.
  807. TSShape* assimpLoadShape(const Torque::Path &path)
  808. {
  809. // TODO: add .cached.dts generation.
  810. // Generate the cached filename
  811. Torque::Path cachedPath(path);
  812. cachedPath.setExtension("cached.dts");
  813. // Check if an up-to-date cached DTS version of this file exists, and
  814. // if so, use that instead.
  815. if (AssimpShapeLoader::canLoadCachedDTS(path))
  816. {
  817. FileStream cachedStream;
  818. cachedStream.open(cachedPath.getFullPath(), Torque::FS::File::Read);
  819. if (cachedStream.getStatus() == Stream::Ok)
  820. {
  821. TSShape *shape = new TSShape;
  822. bool readSuccess = shape->read(&cachedStream);
  823. cachedStream.close();
  824. if (readSuccess)
  825. {
  826. #ifdef TORQUE_DEBUG
  827. Con::printf("Loaded cached shape from %s", cachedPath.getFullPath().c_str());
  828. #endif
  829. return shape;
  830. }
  831. else
  832. delete shape;
  833. }
  834. Con::warnf("Failed to load cached shape from %s", cachedPath.getFullPath().c_str());
  835. }
  836. if (!Torque::FS::IsFile(path))
  837. {
  838. // File does not exist, bail.
  839. return NULL;
  840. }
  841. // Allow TSShapeConstructor object to override properties
  842. ColladaUtils::getOptions().reset();
  843. TSShapeConstructor* tscon = TSShapeConstructor::findShapeConstructorByFilename(path.getFullPath());
  844. if (tscon)
  845. {
  846. ColladaUtils::getOptions() = tscon->mOptions;
  847. }
  848. AssimpShapeLoader loader;
  849. TSShape* tss = loader.generateShape(path);
  850. if (tss)
  851. {
  852. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Import complete");
  853. Con::printf("[ASSIMP] Shape created successfully.");
  854. // Cache the model to a DTS file for faster loading next time.
  855. FileStream dtsStream;
  856. if (dtsStream.open(cachedPath.getFullPath(), Torque::FS::File::Write))
  857. {
  858. Con::printf("Writing cached shape to %s", cachedPath.getFullPath().c_str());
  859. tss->write(&dtsStream);
  860. }
  861. loader.updateMaterialsScript(path);
  862. }
  863. loader.releaseImport();
  864. return tss;
  865. }
  866. DefineEngineFunction(GetShapeInfo, bool, (const char* shapePath, const char* ctrl, bool loadCachedDts), ("", "", true),
  867. "(string shapePath, GuiTreeViewCtrl ctrl) Collect scene information from "
  868. "a shape file and store it in a GuiTreeView control. This function is "
  869. "used by the assimp import gui to show a preview of the scene contents "
  870. "prior to import, and is probably not much use for anything else.\n"
  871. "@param shapePath shape filename\n"
  872. "@param ctrl GuiTreeView control to add elements to\n"
  873. "@return true if successful, false otherwise\n"
  874. "@ingroup Editors\n"
  875. "@internal")
  876. {
  877. GuiTreeViewCtrl* tree;
  878. if (!Sim::findObject(ctrl, tree))
  879. {
  880. Con::errorf("enumColladaScene::Could not find GuiTreeViewCtrl '%s'", ctrl);
  881. return false;
  882. }
  883. // Check if a cached DTS is available => no need to import the source file
  884. // if we can load the DTS instead
  885. Torque::Path path(shapePath);
  886. if (loadCachedDts && AssimpShapeLoader::canLoadCachedDTS(path))
  887. return false;
  888. AssimpShapeLoader loader;
  889. return loader.fillGuiTreeView(shapePath, tree);
  890. }