assimpShapeLoader.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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, float 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 (unsigned int 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)", *(int*)scene->mMetaData->mValues[i].mData);
  137. break;
  138. case AI_UINT64:
  139. Con::printf(" Value: %llu (uint64)", *(uint64_t*)scene->mMetaData->mValues[i].mData);
  140. break;
  141. case AI_FLOAT:
  142. Con::printf(" Value: %f (float)", *(float*)scene->mMetaData->mValues[i].mData);
  143. break;
  144. case AI_DOUBLE:
  145. Con::printf(" Value: %f (double)", *(double*)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. unsigned int ppsteps = aiProcess_Triangulate | aiProcess_ConvertToLeftHanded & ~aiProcess_FlipWindingOrder;
  167. const auto& options = ColladaUtils::getOptions();
  168. if (options.reverseWindingOrder) ppsteps |= aiProcess_FlipWindingOrder;
  169. if (options.calcTangentSpace) ppsteps |= aiProcess_CalcTangentSpace;
  170. if (options.joinIdenticalVerts) ppsteps |= aiProcess_JoinIdenticalVertices;
  171. if (options.removeRedundantMats) ppsteps |= aiProcess_RemoveRedundantMaterials;
  172. if (options.genUVCoords) ppsteps |= aiProcess_GenUVCoords;
  173. if (options.transformUVCoords) ppsteps |= aiProcess_TransformUVCoords;
  174. if (options.findInstances) ppsteps |= aiProcess_FindInstances;
  175. if (options.limitBoneWeights) ppsteps |= aiProcess_LimitBoneWeights;
  176. if (Con::getBoolVariable("$Assimp::OptimizeMeshes", false)) {
  177. ppsteps |= aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph;
  178. }
  179. if (Con::getBoolVariable("$Assimp::SplitLargeMeshes", false)) {
  180. ppsteps |= aiProcess_SplitLargeMeshes;
  181. }
  182. ppsteps |= aiProcess_ValidateDataStructure;
  183. struct aiLogStream shapeLog = aiGetPredefinedLogStream(aiDefaultLogStream_STDOUT, NULL);
  184. shapeLog.callback = assimpLogCallback;
  185. shapeLog.user = 0;
  186. aiAttachLogStream(&shapeLog);
  187. #ifdef TORQUE_DEBUG
  188. aiEnableVerboseLogging(true);
  189. #endif
  190. // Read the file
  191. mScene = mImporter.ReadFile(shapePath.getFullPath().c_str(), ppsteps);
  192. if (!mScene || (mScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) || !mScene->mRootNode) {
  193. Con::errorf("[ASSIMP] ERROR: Could not load file: %s", shapePath.getFullPath().c_str());
  194. Con::errorf("[ASSIMP] Importer error: %s", mImporter.GetErrorString());
  195. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Import failed");
  196. return;
  197. }
  198. Con::printf("[ASSIMP] Mesh Count: %d", mScene->mNumMeshes);
  199. Con::printf("[ASSIMP] Material Count: %d", mScene->mNumMaterials);
  200. #ifdef TORQUE_DEBUG
  201. debugSceneMetaData(mScene);
  202. #endif
  203. ColladaUtils::getOptions().upAxis = UPAXISTYPE_Y_UP; // default to Y up for assimp.
  204. // Handle scaling
  205. configureImportUnits();
  206. // Format-specific adjustments
  207. String fileExt = String::ToLower(shapePath.getExtension());
  208. const aiImporterDesc* importerDescription = aiGetImporterDesc(fileExt.c_str());
  209. if (importerDescription && dStrcmp(importerDescription->mName, "Autodesk FBX Importer") == 0) {
  210. Con::printf("[ASSIMP] Detected FBX format, checking unit scale...");
  211. F32 scaleFactor = ColladaUtils::getOptions().unit;
  212. if (scaleFactor != 1.0f) {
  213. Con::printf("[ASSIMP] Applying FBX scale factor: %f", scaleFactor);
  214. scaleScene(mScene, scaleFactor);
  215. }
  216. else
  217. {
  218. scaleScene(mScene, 0.01f);
  219. }
  220. }
  221. // Extract embedded textures
  222. for (unsigned int i = 0; i < mScene->mNumTextures; ++i) {
  223. extractTexture(i, mScene->mTextures[i]);
  224. }
  225. // Load all materials
  226. AssimpAppMaterial::sDefaultMatNumber = 0;
  227. for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
  228. AppMesh::appMaterials.push_back(new AssimpAppMaterial(mScene->mMaterials[i]));
  229. }
  230. // Setup LOD checks
  231. detectDetails();
  232. // Process the scene graph
  233. AssimpAppNode* rootNode = new AssimpAppNode(mScene, mScene->mRootNode, 0);
  234. if (!processNode(rootNode)) {
  235. delete rootNode;
  236. }
  237. // Add a bounds node if none exists
  238. if (!boundsNode) {
  239. auto* reqNode = new aiNode("bounds");
  240. mScene->mRootNode->addChildren(1, &reqNode);
  241. auto* appBoundsNode = new AssimpAppNode(mScene, reqNode);
  242. if (!processNode(appBoundsNode)) {
  243. delete appBoundsNode;
  244. }
  245. }
  246. // Process animations if available
  247. processAnimations();
  248. // Clean up log stream
  249. aiDetachLogStream(&shapeLog);
  250. }
  251. void AssimpShapeLoader::configureImportUnits() {
  252. auto& options = ColladaUtils::getOptions();
  253. // Configure unit scaling
  254. if (options.unit <= 0.0f) {
  255. F64 unitScaleFactor = 1.0;
  256. if (!getMetaDouble("UnitScaleFactor", unitScaleFactor)) {
  257. float floatVal;
  258. int intVal;
  259. if (getMetaFloat("UnitScaleFactor", floatVal)) {
  260. unitScaleFactor = static_cast<F64>(floatVal);
  261. }
  262. else if (getMetaInt("UnitScaleFactor", intVal)) {
  263. unitScaleFactor = static_cast<F64>(intVal);
  264. }
  265. }
  266. options.unit = static_cast<float>(unitScaleFactor);
  267. }
  268. }
  269. void AssimpShapeLoader::processAnimations()
  270. {
  271. // add all animations into 1 ambient animation.
  272. aiAnimation* ambientSeq = new aiAnimation();
  273. ambientSeq->mName = "ambient";
  274. Vector<aiNodeAnim*> ambientChannels;
  275. F32 duration = 0.0f;
  276. F32 ticks = 0.0f;
  277. if (mScene->mNumAnimations > 0)
  278. {
  279. for (U32 i = 0; i < mScene->mNumAnimations; ++i)
  280. {
  281. aiAnimation* anim = mScene->mAnimations[i];
  282. ticks = anim->mTicksPerSecond;
  283. duration = 0.0f;
  284. for (U32 j = 0; j < anim->mNumChannels; j++)
  285. {
  286. aiNodeAnim* nodeAnim = anim->mChannels[j];
  287. // Determine the maximum keyframe time for this animation
  288. F32 maxKeyTime = 0.0f;
  289. for (U32 k = 0; k < nodeAnim->mNumPositionKeys; k++) {
  290. maxKeyTime = getMax(maxKeyTime, (F32)nodeAnim->mPositionKeys[k].mTime);
  291. }
  292. for (U32 k = 0; k < nodeAnim->mNumRotationKeys; k++) {
  293. maxKeyTime = getMax(maxKeyTime, (F32)nodeAnim->mRotationKeys[k].mTime);
  294. }
  295. for (U32 k = 0; k < nodeAnim->mNumScalingKeys; k++) {
  296. maxKeyTime = getMax(maxKeyTime, (F32)nodeAnim->mScalingKeys[k].mTime);
  297. }
  298. ambientChannels.push_back(nodeAnim);
  299. duration = getMax(duration, maxKeyTime);
  300. }
  301. }
  302. ambientSeq->mNumChannels = ambientChannels.size();
  303. ambientSeq->mChannels = ambientChannels.address();
  304. ambientSeq->mDuration = duration;
  305. ambientSeq->mTicksPerSecond = ticks;
  306. AssimpAppSequence* defaultAssimpSeq = new AssimpAppSequence(ambientSeq);
  307. appSequences.push_back(defaultAssimpSeq);
  308. }
  309. }
  310. void AssimpShapeLoader::computeBounds(Box3F& bounds)
  311. {
  312. TSShapeLoader::computeBounds(bounds);
  313. // Check if the model origin needs adjusting
  314. bool adjustCenter = ColladaUtils::getOptions().adjustCenter;
  315. bool adjustFloor = ColladaUtils::getOptions().adjustFloor;
  316. if (bounds.isValidBox() && (adjustCenter || adjustFloor))
  317. {
  318. // Compute shape offset
  319. Point3F shapeOffset = Point3F::Zero;
  320. if (adjustCenter)
  321. {
  322. bounds.getCenter(&shapeOffset);
  323. shapeOffset = -shapeOffset;
  324. }
  325. if (adjustFloor)
  326. shapeOffset.z = -bounds.minExtents.z;
  327. // Adjust bounds
  328. bounds.minExtents += shapeOffset;
  329. bounds.maxExtents += shapeOffset;
  330. // Now adjust all positions for root level nodes (nodes with no parent)
  331. for (S32 iNode = 0; iNode < shape->nodes.size(); iNode++)
  332. {
  333. if (!appNodes[iNode]->isParentRoot())
  334. continue;
  335. // Adjust default translation
  336. shape->defaultTranslations[iNode] += shapeOffset;
  337. // Adjust animated translations
  338. for (S32 iSeq = 0; iSeq < shape->sequences.size(); iSeq++)
  339. {
  340. const TSShape::Sequence& seq = shape->sequences[iSeq];
  341. if (seq.translationMatters.test(iNode))
  342. {
  343. for (S32 iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
  344. {
  345. S32 index = seq.baseTranslation + seq.translationMatters.count(iNode)*seq.numKeyframes + iFrame;
  346. shape->nodeTranslations[index] += shapeOffset;
  347. }
  348. }
  349. }
  350. }
  351. }
  352. }
  353. bool AssimpShapeLoader::fillGuiTreeView(const char* sourceShapePath, GuiTreeViewCtrl* tree)
  354. {
  355. Assimp::Importer importer;
  356. Torque::Path path(sourceShapePath);
  357. String cleanFile = AppMaterial::cleanString(path.getFileName());
  358. // Attempt to import with Assimp.
  359. const aiScene* shapeScene = importer.ReadFile(path.getFullPath().c_str(), (aiProcessPreset_TargetRealtime_Quality | aiProcess_CalcTangentSpace)
  360. & ~aiProcess_RemoveRedundantMaterials & ~aiProcess_GenSmoothNormals);
  361. if (!shapeScene)
  362. {
  363. Con::printf("AssimpShapeLoader::fillGuiTreeView - Assimp Error: %s", importer.GetErrorString());
  364. return false;
  365. }
  366. mScene = shapeScene;
  367. // Initialize tree
  368. tree->removeItem(0);
  369. S32 meshItem = tree->insertItem(0, "Meshes", String::ToString("%i", shapeScene->mNumMeshes));
  370. S32 matItem = tree->insertItem(0, "Materials", String::ToString("%i", shapeScene->mNumMaterials));
  371. S32 animItem = tree->insertItem(0, "Animations", String::ToString("%i", shapeScene->mNumAnimations));
  372. //S32 lightsItem = tree->insertItem(0, "Lights", String::ToString("%i", shapeScene->mNumLights));
  373. //S32 texturesItem = tree->insertItem(0, "Textures", String::ToString("%i", shapeScene->mNumTextures));
  374. //Details!
  375. U32 numPolys = 0;
  376. U32 numVerts = 0;
  377. for (U32 i = 0; i < shapeScene->mNumMeshes; i++)
  378. {
  379. tree->insertItem(meshItem, String::ToString("%s", shapeScene->mMeshes[i]->mName.C_Str()));
  380. numPolys += shapeScene->mMeshes[i]->mNumFaces;
  381. numVerts += shapeScene->mMeshes[i]->mNumVertices;
  382. }
  383. U32 defaultMatNumber = 0;
  384. for (U32 i = 0; i < shapeScene->mNumMaterials; i++)
  385. {
  386. aiMaterial* aiMat = shapeScene->mMaterials[i];
  387. aiString matName;
  388. aiMat->Get(AI_MATKEY_NAME, matName);
  389. String name = matName.C_Str();
  390. if (name.isEmpty())
  391. {
  392. name = AppMaterial::cleanString(path.getFileName());
  393. name += "_defMat";
  394. name += String::ToString("%d", defaultMatNumber);
  395. defaultMatNumber++;
  396. }
  397. aiString texPath;
  398. aiMat->GetTexture(aiTextureType::aiTextureType_DIFFUSE, 0, &texPath);
  399. String texName = texPath.C_Str();
  400. if (texName.isEmpty())
  401. {
  402. aiColor3D read_color(1.f, 1.f, 1.f);
  403. if (AI_SUCCESS == aiMat->Get(AI_MATKEY_COLOR_DIFFUSE, read_color))
  404. 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
  405. else
  406. texName = "No Texture";
  407. }
  408. else
  409. texName = AssimpAppMaterial::cleanTextureName(texName, cleanFile, sourceShapePath, true);
  410. tree->insertItem(matItem, String::ToString("%s", name.c_str()), String::ToString("%s", texName.c_str()));
  411. }
  412. if (shapeScene->mNumAnimations == 0)
  413. {
  414. tree->insertItem(animItem, "ambient", "animation", "", 0, 0);
  415. }
  416. else
  417. {
  418. for (U32 i = 0; i < shapeScene->mNumAnimations; i++)
  419. {
  420. tree->insertItem(animItem, shapeScene->mAnimations[i]->mName.C_Str(), "animation", "", 0, 0);
  421. }
  422. }
  423. U32 numNodes = 0;
  424. if (shapeScene->mRootNode)
  425. {
  426. S32 nodesItem = tree->insertItem(0, "Nodes", "");
  427. addNodeToTree(nodesItem, shapeScene->mRootNode, tree, numNodes);
  428. tree->setItemValue(nodesItem, String::ToString("%i", numNodes));
  429. }
  430. U32 numMetaTags = shapeScene->mMetaData ? shapeScene->mMetaData->mNumProperties : 0;
  431. if (numMetaTags)
  432. addMetaDataToTree(shapeScene->mMetaData, tree);
  433. F64 unit;
  434. if (!getMetaDouble("UnitScaleFactor", unit))
  435. unit = 1.0f;
  436. S32 upAxis;
  437. if (!getMetaInt("UpAxis", upAxis))
  438. upAxis = UPAXISTYPE_Z_UP;
  439. /*for (U32 i = 0; i < shapeScene->mNumLights; i++)
  440. {
  441. treeObj->insertItem(lightsItem, String::ToString("%s", shapeScene->mLights[i]->mType));
  442. }*/
  443. // Store shape information in the tree control
  444. tree->setDataField(StringTable->insert("_nodeCount"), 0, avar("%d", numNodes));
  445. tree->setDataField(StringTable->insert("_meshCount"), 0, avar("%d", shapeScene->mNumMeshes));
  446. tree->setDataField(StringTable->insert("_polygonCount"), 0, avar("%d", numPolys));
  447. tree->setDataField(StringTable->insert("_materialCount"), 0, avar("%d", shapeScene->mNumMaterials));
  448. tree->setDataField(StringTable->insert("_lightCount"), 0, avar("%d", shapeScene->mNumLights));
  449. tree->setDataField(StringTable->insert("_animCount"), 0, avar("%d", shapeScene->mNumAnimations));
  450. tree->setDataField(StringTable->insert("_textureCount"), 0, avar("%d", shapeScene->mNumTextures));
  451. tree->setDataField(StringTable->insert("_vertCount"), 0, avar("%d", numVerts));
  452. tree->setDataField(StringTable->insert("_metaTagCount"), 0, avar("%d", numMetaTags));
  453. tree->setDataField(StringTable->insert("_unit"), 0, avar("%g", (F32)unit));
  454. if (upAxis == UPAXISTYPE_X_UP)
  455. tree->setDataField(StringTable->insert("_upAxis"), 0, "X_AXIS");
  456. else if (upAxis == UPAXISTYPE_Y_UP)
  457. tree->setDataField(StringTable->insert("_upAxis"), 0, "Y_AXIS");
  458. else
  459. tree->setDataField(StringTable->insert("_upAxis"), 0, "Z_AXIS");
  460. return true;
  461. }
  462. void AssimpShapeLoader::updateMaterialsScript(const Torque::Path &path)
  463. {
  464. return;
  465. /*
  466. Torque::Path scriptPath(path);
  467. scriptPath.setFileName("materials");
  468. scriptPath.setExtension(TORQUE_SCRIPT_EXTENSION);
  469. // First see what materials we need to update
  470. PersistenceManager persistMgr;
  471. for ( U32 iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++ )
  472. {
  473. AssimpAppMaterial *mat = dynamic_cast<AssimpAppMaterial*>( AppMesh::appMaterials[iMat] );
  474. if ( mat )
  475. {
  476. Material *mappedMat;
  477. if ( Sim::findObject( MATMGR->getMapEntry( mat->getName() ), mappedMat ) )
  478. {
  479. // Only update existing materials if forced to
  480. if (ColladaUtils::getOptions().forceUpdateMaterials)
  481. {
  482. mat->initMaterial(scriptPath, mappedMat);
  483. persistMgr.setDirty(mappedMat);
  484. }
  485. }
  486. else
  487. {
  488. // Create a new material definition
  489. persistMgr.setDirty( mat->createMaterial( scriptPath ), scriptPath.getFullPath() );
  490. }
  491. }
  492. }
  493. if ( persistMgr.getDirtyList().empty() )
  494. return;
  495. persistMgr.saveDirty();
  496. */
  497. }
  498. /// Check if an up-to-date cached DTS is available for this DAE file
  499. bool AssimpShapeLoader::canLoadCachedDTS(const Torque::Path& path)
  500. {
  501. // Generate the cached filename
  502. Torque::Path cachedPath(path);
  503. cachedPath.setExtension("cached.dts");
  504. // Check if a cached DTS newer than this file is available
  505. FileTime cachedModifyTime;
  506. if (Platform::getFileTimes(cachedPath.getFullPath(), NULL, &cachedModifyTime))
  507. {
  508. bool forceLoad = Con::getBoolVariable("$assimp::forceLoad", false);
  509. FileTime daeModifyTime;
  510. if (!Platform::getFileTimes(path.getFullPath(), NULL, &daeModifyTime) ||
  511. (!forceLoad && (Platform::compareFileTimes(cachedModifyTime, daeModifyTime) >= 0) ))
  512. {
  513. // Original file not found, or cached DTS is newer
  514. return true;
  515. }
  516. }
  517. return false;
  518. }
  519. void AssimpShapeLoader::assimpLogCallback(const char* message, char* user)
  520. {
  521. Con::printf("[Assimp log message] %s", StringUnit::getUnit(message, 0, "\n"));
  522. }
  523. bool AssimpShapeLoader::ignoreNode(const String& name)
  524. {
  525. // Do not add AssimpFbx dummy nodes to the TSShape. See: Assimp::FBX::ImportSettings::preservePivots
  526. // https://github.com/assimp/assimp/blob/master/code/FBXImportSettings.h#L116-L135
  527. if (name.find("_$AssimpFbx$_") != String::NPos)
  528. return true;
  529. if (FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().alwaysImport, name, false))
  530. return false;
  531. return FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().neverImport, name, false);
  532. }
  533. bool AssimpShapeLoader::ignoreMesh(const String& name)
  534. {
  535. if (FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().alwaysImportMesh, name, false))
  536. return false;
  537. else
  538. return FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().neverImportMesh, name, false);
  539. }
  540. void AssimpShapeLoader::detectDetails()
  541. {
  542. // Set LOD option
  543. bool singleDetail = true;
  544. switch (ColladaUtils::getOptions().lodType)
  545. {
  546. case ColladaUtils::ImportOptions::DetectDTS:
  547. // Check for a baseXX->startXX hierarchy at the top-level, if we find
  548. // one, use trailing numbers for LOD, otherwise use a single size
  549. for (S32 iNode = 0; singleDetail && (iNode < mScene->mRootNode->mNumChildren); iNode++) {
  550. aiNode* node = mScene->mRootNode->mChildren[iNode];
  551. if (node && dStrStartsWith(node->mName.C_Str(), "base")) {
  552. for (S32 iChild = 0; iChild < node->mNumChildren; iChild++) {
  553. aiNode* child = node->mChildren[iChild];
  554. if (child && dStrStartsWith(child->mName.C_Str(), "start")) {
  555. singleDetail = false;
  556. break;
  557. }
  558. }
  559. }
  560. }
  561. break;
  562. case ColladaUtils::ImportOptions::SingleSize:
  563. singleDetail = true;
  564. break;
  565. case ColladaUtils::ImportOptions::TrailingNumber:
  566. singleDetail = false;
  567. break;
  568. default:
  569. break;
  570. }
  571. AssimpAppMesh::fixDetailSize(singleDetail, ColladaUtils::getOptions().singleDetailSize);
  572. }
  573. void AssimpShapeLoader::extractTexture(U32 index, aiTexture* pTex)
  574. { // Cache an embedded texture to disk
  575. updateProgress(Load_EnumerateScene, "Extracting Textures...", mScene->mNumTextures, index);
  576. Con::printf("[Assimp] Extracting Texture %s, W: %d, H: %d, %d of %d, format hint: (%s)", pTex->mFilename.C_Str(),
  577. pTex->mWidth, pTex->mHeight, index, mScene->mNumTextures, pTex->achFormatHint);
  578. // Create the texture filename
  579. String cleanFile = AppMaterial::cleanString(TSShapeLoader::getShapePath().getFileName());
  580. String texName = String::ToString("%s_cachedTex%d", cleanFile.c_str(), index);
  581. Torque::Path texPath = shapePath;
  582. texPath.setFileName(texName);
  583. if (pTex->mHeight == 0)
  584. { // Compressed format, write the data directly to disc
  585. texPath.setExtension(pTex->achFormatHint);
  586. FileStream *outputStream;
  587. if ((outputStream = FileStream::createAndOpen(texPath.getFullPath(), Torque::FS::File::Write)) != NULL)
  588. {
  589. outputStream->setPosition(0);
  590. outputStream->write(pTex->mWidth, pTex->pcData);
  591. outputStream->close();
  592. delete outputStream;
  593. }
  594. }
  595. else
  596. { // Embedded pixel data, fill a bitmap and save it.
  597. GFXTexHandle shapeTex;
  598. shapeTex.set(pTex->mWidth, pTex->mHeight, GFXFormatR8G8B8A8_SRGB, &GFXDynamicTextureSRGBProfile,
  599. String::ToString("AssimpShapeLoader (%s:%i)", __FILE__, __LINE__), 1, 0);
  600. GFXLockedRect *rect = shapeTex.lock();
  601. for (U32 y = 0; y < pTex->mHeight; ++y)
  602. {
  603. for (U32 x = 0; x < pTex->mWidth; ++x)
  604. {
  605. U32 targetIndex = (y * rect->pitch) + (x * 4);
  606. U32 sourceIndex = ((y * pTex->mWidth) + x) * 4;
  607. rect->bits[targetIndex] = pTex->pcData[sourceIndex].r;
  608. rect->bits[targetIndex + 1] = pTex->pcData[sourceIndex].g;
  609. rect->bits[targetIndex + 2] = pTex->pcData[sourceIndex].b;
  610. rect->bits[targetIndex + 3] = pTex->pcData[sourceIndex].a;
  611. }
  612. }
  613. shapeTex.unlock();
  614. texPath.setExtension("png");
  615. shapeTex->dumpToDisk("PNG", texPath.getFullPath());
  616. }
  617. }
  618. void AssimpShapeLoader::addNodeToTree(S32 parentItem, aiNode* node, GuiTreeViewCtrl* tree, U32& nodeCount)
  619. {
  620. // Add this node
  621. S32 nodeItem = parentItem;
  622. String nodeName = node->mName.C_Str();
  623. if (!ignoreNode(nodeName))
  624. {
  625. if (nodeName.isEmpty())
  626. nodeName = "null";
  627. nodeItem = tree->insertItem(parentItem, nodeName.c_str(), String::ToString("%i", node->mNumChildren));
  628. nodeCount++;
  629. }
  630. // Add any child nodes
  631. for (U32 n = 0; n < node->mNumChildren; ++n)
  632. addNodeToTree(nodeItem, node->mChildren[n], tree, nodeCount);
  633. }
  634. void AssimpShapeLoader::addMetaDataToTree(const aiMetadata* metaData, GuiTreeViewCtrl* tree)
  635. {
  636. S32 metaItem = tree->insertItem(0, "MetaData", String::ToString("%i", metaData->mNumProperties));
  637. aiString valString;
  638. aiVector3D valVec;
  639. for (U32 n = 0; n < metaData->mNumProperties; ++n)
  640. {
  641. String keyStr = metaData->mKeys[n].C_Str();
  642. keyStr += ": ";
  643. switch (metaData->mValues[n].mType)
  644. {
  645. case AI_BOOL:
  646. keyStr += ((bool)metaData->mValues[n].mData) ? "true" : "false";
  647. break;
  648. case AI_INT32:
  649. keyStr += String::ToString(*((S32*)(metaData->mValues[n].mData)));
  650. break;
  651. case AI_UINT64:
  652. keyStr += String::ToString("%I64u", *((U64*)metaData->mValues[n].mData));
  653. break;
  654. case AI_FLOAT:
  655. keyStr += String::ToString(*((F32*)metaData->mValues[n].mData));
  656. break;
  657. case AI_DOUBLE:
  658. keyStr += String::ToString(*((F64*)metaData->mValues[n].mData));
  659. break;
  660. case AI_AISTRING:
  661. metaData->Get<aiString>(metaData->mKeys[n], valString);
  662. keyStr += valString.C_Str();
  663. break;
  664. case AI_AIVECTOR3D:
  665. metaData->Get<aiVector3D>(metaData->mKeys[n], valVec);
  666. keyStr += String::ToString("%f, %f, %f", valVec.x, valVec.y, valVec.z);
  667. break;
  668. default:
  669. break;
  670. }
  671. tree->insertItem(metaItem, keyStr.c_str(), String::ToString("%i", n));
  672. }
  673. }
  674. bool AssimpShapeLoader::getMetabool(const char* key, bool& boolVal)
  675. {
  676. if (!mScene || !mScene->mMetaData)
  677. return false;
  678. String keyStr = key;
  679. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  680. {
  681. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  682. {
  683. if (mScene->mMetaData->mValues[n].mType == AI_BOOL)
  684. {
  685. boolVal = (bool)mScene->mMetaData->mValues[n].mData;
  686. return true;
  687. }
  688. }
  689. }
  690. return false;
  691. }
  692. bool AssimpShapeLoader::getMetaInt(const char* key, S32& intVal)
  693. {
  694. if (!mScene || !mScene->mMetaData)
  695. return false;
  696. String keyStr = key;
  697. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  698. {
  699. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  700. {
  701. if (mScene->mMetaData->mValues[n].mType == AI_INT32)
  702. {
  703. intVal = *((S32*)(mScene->mMetaData->mValues[n].mData));
  704. return true;
  705. }
  706. }
  707. }
  708. return false;
  709. }
  710. bool AssimpShapeLoader::getMetaFloat(const char* key, F32& floatVal)
  711. {
  712. if (!mScene || !mScene->mMetaData)
  713. return false;
  714. String keyStr = key;
  715. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  716. {
  717. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  718. {
  719. if (mScene->mMetaData->mValues[n].mType == AI_FLOAT)
  720. {
  721. floatVal = *((F32*)mScene->mMetaData->mValues[n].mData);
  722. return true;
  723. }
  724. }
  725. }
  726. return false;
  727. }
  728. bool AssimpShapeLoader::getMetaDouble(const char* key, F64& doubleVal)
  729. {
  730. if (!mScene || !mScene->mMetaData)
  731. return false;
  732. String keyStr = key;
  733. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  734. {
  735. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  736. {
  737. if (mScene->mMetaData->mValues[n].mType == AI_DOUBLE)
  738. {
  739. doubleVal = *((F64*)mScene->mMetaData->mValues[n].mData);
  740. return true;
  741. }
  742. }
  743. }
  744. return false;
  745. }
  746. bool AssimpShapeLoader::getMetaString(const char* key, String& stringVal)
  747. {
  748. if (!mScene || !mScene->mMetaData)
  749. return false;
  750. String keyStr = key;
  751. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  752. {
  753. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  754. {
  755. if (mScene->mMetaData->mValues[n].mType == AI_AISTRING)
  756. {
  757. aiString valString;
  758. mScene->mMetaData->Get<aiString>(mScene->mMetaData->mKeys[n], valString);
  759. stringVal = valString.C_Str();
  760. return true;
  761. }
  762. }
  763. }
  764. return false;
  765. }
  766. //-----------------------------------------------------------------------------
  767. /// This function is invoked by the resource manager based on file extension.
  768. TSShape* assimpLoadShape(const Torque::Path &path)
  769. {
  770. // TODO: add .cached.dts generation.
  771. // Generate the cached filename
  772. Torque::Path cachedPath(path);
  773. cachedPath.setExtension("cached.dts");
  774. // Check if an up-to-date cached DTS version of this file exists, and
  775. // if so, use that instead.
  776. if (AssimpShapeLoader::canLoadCachedDTS(path))
  777. {
  778. FileStream cachedStream;
  779. cachedStream.open(cachedPath.getFullPath(), Torque::FS::File::Read);
  780. if (cachedStream.getStatus() == Stream::Ok)
  781. {
  782. TSShape *shape = new TSShape;
  783. bool readSuccess = shape->read(&cachedStream);
  784. cachedStream.close();
  785. if (readSuccess)
  786. {
  787. #ifdef TORQUE_DEBUG
  788. Con::printf("Loaded cached shape from %s", cachedPath.getFullPath().c_str());
  789. #endif
  790. return shape;
  791. }
  792. else
  793. delete shape;
  794. }
  795. Con::warnf("Failed to load cached shape from %s", cachedPath.getFullPath().c_str());
  796. }
  797. if (!Torque::FS::IsFile(path))
  798. {
  799. // File does not exist, bail.
  800. return NULL;
  801. }
  802. // Allow TSShapeConstructor object to override properties
  803. ColladaUtils::getOptions().reset();
  804. TSShapeConstructor* tscon = TSShapeConstructor::findShapeConstructorByFilename(path.getFullPath());
  805. if (tscon)
  806. {
  807. ColladaUtils::getOptions() = tscon->mOptions;
  808. }
  809. AssimpShapeLoader loader;
  810. TSShape* tss = loader.generateShape(path);
  811. if (tss)
  812. {
  813. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Import complete");
  814. Con::printf("[ASSIMP] Shape created successfully.");
  815. // Cache the model to a DTS file for faster loading next time.
  816. FileStream dtsStream;
  817. if (dtsStream.open(cachedPath.getFullPath(), Torque::FS::File::Write))
  818. {
  819. Con::printf("Writing cached shape to %s", cachedPath.getFullPath().c_str());
  820. tss->write(&dtsStream);
  821. }
  822. loader.updateMaterialsScript(path);
  823. }
  824. loader.releaseImport();
  825. return tss;
  826. }
  827. DefineEngineFunction(GetShapeInfo, bool, (const char* shapePath, const char* ctrl, bool loadCachedDts), ("", "", true),
  828. "(string shapePath, GuiTreeViewCtrl ctrl) Collect scene information from "
  829. "a shape file and store it in a GuiTreeView control. This function is "
  830. "used by the assimp import gui to show a preview of the scene contents "
  831. "prior to import, and is probably not much use for anything else.\n"
  832. "@param shapePath shape filename\n"
  833. "@param ctrl GuiTreeView control to add elements to\n"
  834. "@return true if successful, false otherwise\n"
  835. "@ingroup Editors\n"
  836. "@internal")
  837. {
  838. GuiTreeViewCtrl* tree;
  839. if (!Sim::findObject(ctrl, tree))
  840. {
  841. Con::errorf("enumColladaScene::Could not find GuiTreeViewCtrl '%s'", ctrl);
  842. return false;
  843. }
  844. // Check if a cached DTS is available => no need to import the source file
  845. // if we can load the DTS instead
  846. Torque::Path path(shapePath);
  847. if (loadCachedDts && AssimpShapeLoader::canLoadCachedDTS(path))
  848. return false;
  849. AssimpShapeLoader loader;
  850. return loader.fillGuiTreeView(shapePath, tree);
  851. }