assimpAppMaterial.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. #define TORQUE_PBR_MATERIALS
  23. #include "platform/platform.h"
  24. #include "ts/loader/appSequence.h"
  25. #include "ts/assimp/assimpAppMaterial.h"
  26. #include "ts/assimp/assimpAppMesh.h"
  27. #include "materials/materialManager.h"
  28. #include "ts/tsMaterialList.h"
  29. #include "core/stream/fileStream.h"
  30. // assimp include files.
  31. #include <assimp/cimport.h>
  32. #include <assimp/scene.h>
  33. #include <assimp/postprocess.h>
  34. #include <assimp/types.h>
  35. U32 AssimpAppMaterial::sDefaultMatNumber = 0;
  36. String AppMaterial::cleanString(const String& str)
  37. {
  38. String cleanStr(str);
  39. // Replace invalid characters with underscores
  40. const String badChars(" -,.+=*/[]%$~;:");
  41. for (String::SizeType i = 0; i < badChars.length(); i++)
  42. cleanStr.replace(badChars[i], '_');
  43. // Prefix with an underscore if string starts with a number
  44. if ((cleanStr[0] >= '0') && (cleanStr[0] <= '9'))
  45. cleanStr.insert(0, '_');
  46. return cleanStr;
  47. }
  48. AssimpAppMaterial::AssimpAppMaterial(const char* matName)
  49. {
  50. name = ColladaUtils::getOptions().matNamePrefix;
  51. name += matName;
  52. // Set some defaults
  53. flags |= TSMaterialList::S_Wrap;
  54. flags |= TSMaterialList::T_Wrap;
  55. }
  56. AssimpAppMaterial::AssimpAppMaterial(aiMaterial* mtl) :
  57. mAIMat(mtl)
  58. {
  59. aiString matName;
  60. mtl->Get(AI_MATKEY_NAME, matName);
  61. name = matName.C_Str();
  62. if (name.isEmpty())
  63. {
  64. name = cleanString(TSShapeLoader::getShapePath().getFileName());
  65. name += "_defMat";
  66. name += String::ToString("%d", sDefaultMatNumber);
  67. sDefaultMatNumber++;
  68. }
  69. name = ColladaUtils::getOptions().matNamePrefix + name;
  70. Con::printf("[ASSIMP] Loading Material: %s", name.c_str());
  71. #ifdef TORQUE_DEBUG
  72. enumerateMaterialProperties(mtl);
  73. #endif
  74. }
  75. Material* AssimpAppMaterial::createMaterial(const Torque::Path& path) const
  76. {
  77. // The filename and material name are used as TorqueScript identifiers, so
  78. // clean them up first
  79. String cleanFile = cleanString(TSShapeLoader::getShapePath().getFileName());
  80. String cleanName = cleanString(getName());
  81. // Create the Material definition
  82. const String oldScriptFile = Con::getVariable("$Con::File");
  83. Con::setVariable("$Con::File", path.getFullPath()); // modify current script path so texture lookups are correct
  84. Material *newMat = MATMGR->allocateAndRegister(cleanName, getName());
  85. Con::setVariable("$Con::File", oldScriptFile); // restore script path
  86. initMaterial(path, newMat);
  87. return newMat;
  88. }
  89. void AssimpAppMaterial::initMaterial(const Torque::Path& path, Material* mat) const
  90. {
  91. String cleanFile = cleanString(TSShapeLoader::getShapePath().getFileName());
  92. String cleanName = cleanString(getName());
  93. // Determine the blend mode and transparency for this material
  94. Material::BlendOp blendOp = Material::None;
  95. bool translucent = false;
  96. float opacity = 1.0f;
  97. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_OPACITY, opacity))
  98. {
  99. if (opacity != 1.0f)
  100. {
  101. translucent = true;
  102. int blendInt;
  103. blendOp = Material::LerpAlpha;
  104. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_BLEND_FUNC, blendInt))
  105. {
  106. if (blendInt == aiBlendMode_Additive)
  107. blendOp = Material::Add;
  108. }
  109. }
  110. }
  111. else
  112. { // No opacity key, see if it's defined as a gltf property
  113. aiString opacityMode;
  114. if (AI_SUCCESS == mAIMat->Get("$mat.gltf.alphaMode", 0, 0, opacityMode))
  115. {
  116. if (dStrcmp("MASK", opacityMode.C_Str()) == 0)
  117. {
  118. translucent = true;
  119. blendOp = Material::None;
  120. float cutoff;
  121. if (AI_SUCCESS == mAIMat->Get("$mat.gltf.alphaCutoff", 0, 0, cutoff))
  122. {
  123. mat->mAlphaRef = (U32)(cutoff * 255); // alpha ref 0-255
  124. mat->mAlphaTest = true;
  125. }
  126. }
  127. else if (dStrcmp("BLEND", opacityMode.C_Str()) == 0)
  128. {
  129. translucent = true;
  130. blendOp = Material::LerpAlpha;
  131. mat->mAlphaTest = false;
  132. }
  133. else
  134. { // OPAQUE
  135. translucent = false;
  136. blendOp = Material::LerpAlpha; // Make default so it doesn't get written to materials.cs
  137. }
  138. }
  139. }
  140. mat->mTranslucent = translucent;
  141. mat->mTranslucentBlendOp = blendOp;
  142. // Assign color values.
  143. LinearColorF diffuseColor(1.0f, 1.0f, 1.0f, 1.0f);
  144. aiColor3D read_color(1.f, 1.f, 1.f);
  145. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_COLOR_DIFFUSE, read_color))
  146. diffuseColor.set(read_color.r, read_color.g, read_color.b, opacity);
  147. mat->mDiffuse[0] = diffuseColor;
  148. aiString texName;
  149. String torquePath;
  150. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), texName))
  151. {
  152. torquePath = texName.C_Str();
  153. if (!torquePath.isEmpty())
  154. mat->mDiffuseMapFilename[0] = cleanTextureName(torquePath, cleanFile, path, false);
  155. }
  156. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), texName))
  157. {
  158. torquePath = texName.C_Str();
  159. if (!torquePath.isEmpty())
  160. mat->mNormalMapFilename[0] = cleanTextureName(torquePath, cleanFile, path, false);
  161. }
  162. #ifdef TORQUE_PBR_MATERIALS
  163. float floatVal;
  164. if (AI_SUCCESS == mAIMat->Get("$mat.gltf.pbrMetallicRoughness.roughnessFactor", 0, 0, floatVal))
  165. { // The shape has pbr material definitions
  166. String aoName, rmName; // occlusion and roughness/metalness maps
  167. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0), texName))
  168. aoName = texName.C_Str();
  169. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_UNKNOWN, 0), texName))
  170. rmName = texName.C_Str();
  171. if (aoName.isNotEmpty() || rmName.isNotEmpty())
  172. { // If we have either map, fill all three slots
  173. if (rmName.isNotEmpty())
  174. {
  175. mat->mRoughMapFilename[0] = cleanTextureName(rmName, cleanFile, path, false); // Roughness
  176. mat->mSmoothnessChan[0] = 1.0f;
  177. mat->mInvertSmoothness[0] = (floatVal == 1.0f);
  178. mat->mMetalMapFilename[0] = cleanTextureName(rmName, cleanFile, path, false); // Metallic
  179. mat->mMetalChan[0] = 2.0f;
  180. }
  181. if (aoName.isNotEmpty())
  182. {
  183. mat->mAOMapFilename[0] = cleanTextureName(aoName, cleanFile, path, false); // occlusion
  184. mat->mAOChan[0] = 0.0f;
  185. }
  186. else
  187. {
  188. mat->mAOMapFilename[0] = cleanTextureName(rmName, cleanFile, path, false); // occlusion
  189. mat->mAOChan[0] = 0.0f;
  190. }
  191. }
  192. }
  193. #else
  194. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), texName))
  195. {
  196. torquePath = texName.C_Str();
  197. if (!torquePath.isEmpty())
  198. mat->mSpecularMapFilename[0] = cleanTextureName(torquePath, cleanFile, path, false);
  199. }
  200. /*LinearColorF specularColor(1.0f, 1.0f, 1.0f, 1.0f);
  201. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_COLOR_SPECULAR, read_color))
  202. specularColor.set(read_color.r, read_color.g, read_color.b, opacity);
  203. mat->mMetalness[0] = specularColor;
  204. // Specular Power
  205. F32 specularPower = 1.0f;
  206. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_SHININESS_STRENGTH, specularPower))
  207. mat->mSpecularPower[0] = specularPower;
  208. // Specular
  209. F32 specularStrength = 0.0f;
  210. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_SHININESS, specularStrength))
  211. mat->mSpecularStrength[0] = specularStrength;*/
  212. #endif
  213. // Double-Sided
  214. bool doubleSided = false;
  215. S32 dbl_sided = 0;
  216. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TWOSIDED, dbl_sided))
  217. doubleSided = (dbl_sided != 0);
  218. mat->mDoubleSided = doubleSided;
  219. }
  220. String AssimpAppMaterial::cleanTextureName(String& texName, String& shapeName, const Torque::Path& path, bool nameOnly /*= false*/)
  221. {
  222. Torque::Path foundPath;
  223. String cleanStr;
  224. if (texName[0] == '*')
  225. { // It's an embedded texture reference. Make the cached name and return
  226. cleanStr = shapeName;
  227. cleanStr += "_cachedTex";
  228. cleanStr += texName.substr(1);
  229. return cleanStr;
  230. }
  231. // See if the file exists
  232. bool fileFound = false;
  233. String testPath = path.getPath();
  234. testPath += '/';
  235. testPath += texName;
  236. testPath.replace('\\', '/');
  237. fileFound = Torque::FS::IsFile(testPath);
  238. cleanStr = texName;
  239. cleanStr.replace('\\', '/');
  240. if (fileFound)
  241. {
  242. if (cleanStr.equal(texName))
  243. return cleanStr;
  244. foundPath = testPath;
  245. }
  246. else
  247. {
  248. // See if the file is in a sub-directory of the shape
  249. Vector<String> foundFiles;
  250. Torque::Path inPath(cleanStr);
  251. String mainDotCsDir = Platform::getMainDotCsDir();
  252. mainDotCsDir += "/";
  253. S32 results = Torque::FS::FindByPattern(Torque::Path(mainDotCsDir + path.getPath() + "/"), inPath.getFullFileName(), true, foundFiles);
  254. if (results == 0 || foundFiles.size() == 0) // Not under shape directory, try the full tree
  255. results = Torque::FS::FindByPattern(Torque::Path(mainDotCsDir), inPath.getFullFileName(), true, foundFiles);
  256. if (results > 0 && foundFiles.size() > 0)
  257. {
  258. fileFound = true;
  259. foundPath = foundFiles[0];
  260. }
  261. }
  262. if (fileFound)
  263. {
  264. if (nameOnly)
  265. cleanStr = foundPath.getFullFileName();
  266. else
  267. { // Unless the file is in the same directory as the materials.cs (covered above)
  268. // we need to set the full path from the root directory. If we use "subdirectory/file.ext",
  269. // the material manager won't find the image file, but it will be found the next time the
  270. // material is loaded from file. If we use "./subdirectory/file.ext", the image will be found
  271. // now, but not the next time it's loaded from file...
  272. S32 rootLength = dStrlen(Platform::getMainDotCsDir());
  273. cleanStr = foundPath.getFullPathWithoutRoot().substr(rootLength-1);
  274. }
  275. }
  276. else if (nameOnly)
  277. cleanStr += " (Not Found)";
  278. return cleanStr;
  279. }
  280. #ifdef TORQUE_DEBUG
  281. void AssimpAppMaterial::enumerateMaterialProperties(aiMaterial* mtl)
  282. {
  283. for (U32 i = 0; i < mtl->mNumProperties; ++i)
  284. {
  285. aiMaterialProperty* matProp = mtl->mProperties[i];
  286. String outText;
  287. if (matProp)
  288. {
  289. outText = String::ToString(" Key: %s, Index: %d, Semantic: ", matProp->mKey.C_Str(), matProp->mIndex);
  290. switch (matProp->mSemantic)
  291. {
  292. case aiTextureType_NONE:
  293. outText += "aiTextureType_NONE";
  294. break;
  295. case aiTextureType_DIFFUSE:
  296. outText += "aiTextureType_DIFFUSE";
  297. break;
  298. case aiTextureType_SPECULAR:
  299. outText += "aiTextureType_SPECULAR";
  300. break;
  301. case aiTextureType_AMBIENT:
  302. outText += "aiTextureType_AMBIENT";
  303. break;
  304. case aiTextureType_EMISSIVE:
  305. outText += "aiTextureType_EMISSIVE";
  306. break;
  307. case aiTextureType_HEIGHT:
  308. outText += "aiTextureType_HEIGHT";
  309. break;
  310. case aiTextureType_NORMALS:
  311. outText += "aiTextureType_NORMALS";
  312. break;
  313. case aiTextureType_SHININESS:
  314. outText += "aiTextureType_SHININESS";
  315. break;
  316. case aiTextureType_OPACITY:
  317. outText += "aiTextureType_OPACITY";
  318. break;
  319. case aiTextureType_DISPLACEMENT:
  320. outText += "aiTextureType_DISPLACEMENT";
  321. break;
  322. case aiTextureType_LIGHTMAP:
  323. outText += "aiTextureType_LIGHTMAP";
  324. break;
  325. case aiTextureType_REFLECTION:
  326. outText += "aiTextureType_REFLECTION";
  327. break;
  328. default:
  329. outText += "aiTextureType_UNKNOWN";
  330. break;
  331. }
  332. aiString stringProp;
  333. F32* floatProp;
  334. double* doubleProp;
  335. S32* intProp;
  336. switch (matProp->mType)
  337. {
  338. case aiPTI_Float:
  339. floatProp = (F32*)matProp->mData;
  340. for (U32 j = 0; j < matProp->mDataLength / sizeof(F32); ++j)
  341. outText += String::ToString(", %0.4f", floatProp[j]);
  342. break;
  343. case aiPTI_Double:
  344. doubleProp = (double*)matProp->mData;
  345. for (U32 j = 0; j < matProp->mDataLength / sizeof(double); ++j)
  346. outText += String::ToString(", %0.4lf", doubleProp[j]);
  347. break;
  348. case aiPTI_String:
  349. aiGetMaterialString(mtl, matProp->mKey.C_Str(), matProp->mSemantic, matProp->mIndex, &stringProp);
  350. outText += String::ToString(", %s", stringProp.C_Str());
  351. break;
  352. case aiPTI_Integer:
  353. intProp = (S32*)matProp->mData;
  354. for (U32 j = 0; j < matProp->mDataLength / sizeof(S32); ++j)
  355. outText += String::ToString(", %d", intProp[j]);
  356. break;
  357. case aiPTI_Buffer:
  358. outText += ", aiPTI_Buffer format data";
  359. break;
  360. default:
  361. outText += ", Unknown data type";
  362. }
  363. Con::printf("%s", outText.c_str());
  364. }
  365. }
  366. }
  367. #endif