assimpShapeLoader.cpp 35 KB

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