assimpShapeLoader.cpp 36 KB

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