assimpShapeLoader.cpp 36 KB

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