assimpShapeLoader.cpp 34 KB

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