OgreMaterial.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2025, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. #ifndef ASSIMP_BUILD_NO_OGRE_IMPORTER
  34. #include "OgreImporter.h"
  35. #include <assimp/StringUtils.h>
  36. #include <assimp/TinyFormatter.h>
  37. #include <assimp/fast_atof.h>
  38. #include <assimp/material.h>
  39. #include <assimp/scene.h>
  40. #include <assimp/DefaultLogger.hpp>
  41. #include <memory>
  42. #include <sstream>
  43. #include <vector>
  44. using namespace std;
  45. namespace Assimp {
  46. namespace Ogre {
  47. static const string partComment = "//";
  48. static const string partBlockStart = "{";
  49. static const string partBlockEnd = "}";
  50. void OgreImporter::ReadMaterials(const std::string &pFile, Assimp::IOSystem *pIOHandler, aiScene *pScene, Mesh *mesh) {
  51. std::vector<aiMaterial *> materials;
  52. // Create materials that can be found and parsed via the IOSystem.
  53. for (size_t i = 0, len = mesh->NumSubMeshes(); i < len; ++i) {
  54. SubMesh *submesh = mesh->GetSubMesh(i);
  55. if (submesh && !submesh->materialRef.empty()) {
  56. aiMaterial *material = ReadMaterial(pFile, pIOHandler, submesh->materialRef);
  57. if (material) {
  58. submesh->materialIndex = static_cast<int>(materials.size());
  59. materials.push_back(material);
  60. }
  61. }
  62. }
  63. AssignMaterials(pScene, materials);
  64. }
  65. void OgreImporter::ReadMaterials(const std::string &pFile, Assimp::IOSystem *pIOHandler, aiScene *pScene, MeshXml *mesh) {
  66. std::vector<aiMaterial *> materials;
  67. // Create materials that can be found and parsed via the IOSystem.
  68. for (size_t i = 0, len = mesh->NumSubMeshes(); i < len; ++i) {
  69. SubMeshXml *submesh = mesh->GetSubMesh(static_cast<uint16_t>(i));
  70. if (submesh && !submesh->materialRef.empty()) {
  71. aiMaterial *material = ReadMaterial(pFile, pIOHandler, submesh->materialRef);
  72. if (material) {
  73. submesh->materialIndex = static_cast<int>(materials.size());
  74. materials.push_back(material);
  75. }
  76. }
  77. }
  78. AssignMaterials(pScene, materials);
  79. }
  80. void OgreImporter::AssignMaterials(aiScene *pScene, std::vector<aiMaterial *> &materials) {
  81. pScene->mNumMaterials = static_cast<unsigned int>(materials.size());
  82. if (pScene->mNumMaterials > 0) {
  83. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  84. for (size_t i = 0; i < pScene->mNumMaterials; ++i) {
  85. pScene->mMaterials[i] = materials[i];
  86. }
  87. }
  88. }
  89. aiMaterial *OgreImporter::ReadMaterial(const std::string &pFile, Assimp::IOSystem *pIOHandler, const std::string &materialName) {
  90. if (materialName.empty()) {
  91. return nullptr;
  92. }
  93. // Full reference and examples of Ogre Material Script
  94. // can be found from http://www.ogre3d.org/docs/manual/manual_14.html
  95. /*and here is another one:
  96. import * from abstract_base_passes_depth.material
  97. import * from abstract_base.material
  98. import * from mat_shadow_caster.material
  99. import * from mat_character_singlepass.material
  100. material hero/hair/caster : mat_shadow_caster_skin_areject
  101. {
  102. set $diffuse_map "hero_hair_alpha_c.dds"
  103. }
  104. material hero/hair_alpha : mat_char_cns_singlepass_areject_4weights
  105. {
  106. set $diffuse_map "hero_hair_alpha_c.dds"
  107. set $specular_map "hero_hair_alpha_s.dds"
  108. set $normal_map "hero_hair_alpha_n.dds"
  109. set $light_map "black_lightmap.dds"
  110. set $shadow_caster_material "hero/hair/caster"
  111. }
  112. */
  113. stringstream ss;
  114. // Scope for scopre_ptr auto release
  115. {
  116. /* There are three .material options in priority order:
  117. 1) File with the material name (materialName)
  118. 2) File with the mesh files base name (pFile)
  119. 3) Optional user defined material library file (m_userDefinedMaterialLibFile) */
  120. std::vector<string> potentialFiles;
  121. potentialFiles.push_back(materialName + ".material");
  122. potentialFiles.push_back(pFile.substr(0, pFile.rfind(".mesh")) + ".material");
  123. if (!m_userDefinedMaterialLibFile.empty())
  124. potentialFiles.push_back(m_userDefinedMaterialLibFile);
  125. IOStream *materialFile = nullptr;
  126. for (size_t i = 0; i < potentialFiles.size(); ++i) {
  127. materialFile = pIOHandler->Open(potentialFiles[i]);
  128. if (materialFile) {
  129. break;
  130. }
  131. ASSIMP_LOG_VERBOSE_DEBUG("Source file for material '", materialName, "' ", potentialFiles[i], " does not exist");
  132. }
  133. if (!materialFile) {
  134. ASSIMP_LOG_ERROR("Failed to find source file for material '", materialName, "'");
  135. return nullptr;
  136. }
  137. std::unique_ptr<IOStream> stream(materialFile);
  138. if (stream->FileSize() == 0) {
  139. ASSIMP_LOG_WARN("Source file for material '", materialName, "' is empty (size is 0 bytes)");
  140. return nullptr;
  141. }
  142. // Read bytes
  143. vector<char> data(stream->FileSize());
  144. stream->Read(&data[0], stream->FileSize(), 1);
  145. // Convert to UTF-8 and terminate the string for ss
  146. BaseImporter::ConvertToUTF8(data);
  147. data.push_back('\0');
  148. ss << &data[0];
  149. }
  150. ASSIMP_LOG_VERBOSE_DEBUG("Reading material '", materialName, "'");
  151. aiMaterial *material = new aiMaterial();
  152. m_textures.clear();
  153. aiString matName(materialName);
  154. material->AddProperty(&matName, AI_MATKEY_NAME);
  155. // The stringstream will push words from a line until newline.
  156. // It will also trim whitespace from line start and between words.
  157. string linePart;
  158. ss >> linePart;
  159. const string partMaterial = "material";
  160. const string partTechnique = "technique";
  161. while (!ss.eof()) {
  162. // Skip commented lines
  163. if (linePart == partComment) {
  164. NextAfterNewLine(ss, linePart);
  165. continue;
  166. }
  167. if (linePart != partMaterial) {
  168. ss >> linePart;
  169. continue;
  170. }
  171. ss >> linePart;
  172. if (linePart != materialName) {
  173. ss >> linePart;
  174. continue;
  175. }
  176. NextAfterNewLine(ss, linePart);
  177. if (linePart != partBlockStart) {
  178. ASSIMP_LOG_ERROR("Invalid material: block start missing near index ", ss.tellg());
  179. return material;
  180. }
  181. ASSIMP_LOG_VERBOSE_DEBUG("material '", materialName, "'");
  182. while (linePart != partBlockEnd) {
  183. // Proceed to the first technique
  184. ss >> linePart;
  185. if (linePart == partTechnique) {
  186. std::string techniqueName = SkipLine(ss);
  187. ReadTechnique(ai_trim(techniqueName), ss, material);
  188. }
  189. // Read information from a custom material
  190. /** @todo This "set $x y" does not seem to be a official Ogre material system feature.
  191. Materials can inherit other materials and override texture units by using the (unique)
  192. parent texture unit name in your cloned material.
  193. This is not yet supported and below code is probably some hack from the original
  194. author of this Ogre importer. Should be removed? */
  195. if (linePart == "set") {
  196. ss >> linePart;
  197. if (linePart == "$specular") //todo load this values:
  198. {
  199. } else if (linePart == "$diffuse") {
  200. } else if (linePart == "$ambient") {
  201. } else if (linePart == "$colormap") {
  202. ss >> linePart;
  203. aiString cm(linePart);
  204. material->AddProperty(&cm, AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0));
  205. } else if (linePart == "$normalmap") {
  206. ss >> linePart;
  207. aiString nm(linePart);
  208. material->AddProperty(&nm, AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0));
  209. } else if (linePart == "$shininess_strength") {
  210. ss >> linePart;
  211. float Shininess = fast_atof(linePart.c_str());
  212. material->AddProperty(&Shininess, 1, AI_MATKEY_SHININESS_STRENGTH);
  213. } else if (linePart == "$shininess_exponent") {
  214. ss >> linePart;
  215. float Shininess = fast_atof(linePart.c_str());
  216. material->AddProperty(&Shininess, 1, AI_MATKEY_SHININESS);
  217. }
  218. //Properties from Venetica:
  219. else if (linePart == "$diffuse_map") {
  220. ss >> linePart;
  221. if (linePart[0] == '"') // "file" -> file
  222. linePart = linePart.substr(1, linePart.size() - 2);
  223. aiString ts(linePart);
  224. material->AddProperty(&ts, AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0));
  225. } else if (linePart == "$specular_map") {
  226. ss >> linePart;
  227. if (linePart[0] == '"') // "file" -> file
  228. linePart = linePart.substr(1, linePart.size() - 2);
  229. aiString ts(linePart);
  230. material->AddProperty(&ts, AI_MATKEY_TEXTURE(aiTextureType_SHININESS, 0));
  231. } else if (linePart == "$normal_map") {
  232. ss >> linePart;
  233. if (linePart[0] == '"') // "file" -> file
  234. linePart = linePart.substr(1, linePart.size() - 2);
  235. aiString ts(linePart);
  236. material->AddProperty(&ts, AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0));
  237. } else if (linePart == "$light_map") {
  238. ss >> linePart;
  239. if (linePart[0] == '"') {
  240. linePart = linePart.substr(1, linePart.size() - 2);
  241. }
  242. aiString ts(linePart);
  243. material->AddProperty(&ts, AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0));
  244. }
  245. }
  246. }
  247. ss >> linePart;
  248. }
  249. return material;
  250. }
  251. bool OgreImporter::ReadTechnique(const std::string &techniqueName, stringstream &ss, aiMaterial *material) {
  252. string linePart;
  253. ss >> linePart;
  254. if (linePart != partBlockStart) {
  255. ASSIMP_LOG_ERROR("Invalid material: Technique block start missing near index ", ss.tellg());
  256. return false;
  257. }
  258. ASSIMP_LOG_VERBOSE_DEBUG(" technique '", techniqueName, "'");
  259. const string partPass = "pass";
  260. while (linePart != partBlockEnd) {
  261. ss >> linePart;
  262. // Skip commented lines
  263. if (linePart == partComment) {
  264. SkipLine(ss);
  265. continue;
  266. }
  267. /// @todo Techniques have other attributes than just passes.
  268. if (linePart == partPass) {
  269. string passName = SkipLine(ss);
  270. ReadPass(ai_trim(passName), ss, material);
  271. }
  272. }
  273. return true;
  274. }
  275. bool OgreImporter::ReadPass(const std::string &passName, stringstream &ss, aiMaterial *material) {
  276. string linePart;
  277. ss >> linePart;
  278. if (linePart != partBlockStart) {
  279. ASSIMP_LOG_ERROR("Invalid material: Pass block start missing near index ", ss.tellg());
  280. return false;
  281. }
  282. ASSIMP_LOG_VERBOSE_DEBUG(" pass '", passName, "'");
  283. const string partAmbient = "ambient";
  284. const string partDiffuse = "diffuse";
  285. const string partSpecular = "specular";
  286. const string partEmissive = "emissive";
  287. const string partTextureUnit = "texture_unit";
  288. while (linePart != partBlockEnd) {
  289. ss >> linePart;
  290. // Skip commented lines
  291. if (linePart == partComment) {
  292. SkipLine(ss);
  293. continue;
  294. }
  295. // Colors
  296. /// @todo Support alpha via aiColor4D.
  297. if (linePart == partAmbient || linePart == partDiffuse || linePart == partSpecular || linePart == partEmissive) {
  298. float r, g, b;
  299. ss >> r >> g >> b;
  300. const aiColor3D color(r, g, b);
  301. ASSIMP_LOG_VERBOSE_DEBUG(" ", linePart, " ", r, " ", g, " ", b);
  302. if (linePart == partAmbient) {
  303. material->AddProperty(&color, 1, AI_MATKEY_COLOR_AMBIENT);
  304. } else if (linePart == partDiffuse) {
  305. material->AddProperty(&color, 1, AI_MATKEY_COLOR_DIFFUSE);
  306. } else if (linePart == partSpecular) {
  307. material->AddProperty(&color, 1, AI_MATKEY_COLOR_SPECULAR);
  308. } else if (linePart == partEmissive) {
  309. material->AddProperty(&color, 1, AI_MATKEY_COLOR_EMISSIVE);
  310. }
  311. } else if (linePart == partTextureUnit) {
  312. string textureUnitName = SkipLine(ss);
  313. ReadTextureUnit(ai_trim(textureUnitName), ss, material);
  314. }
  315. }
  316. return true;
  317. }
  318. bool OgreImporter::ReadTextureUnit(const std::string &textureUnitName, stringstream &ss, aiMaterial *material) {
  319. string linePart;
  320. ss >> linePart;
  321. if (linePart != partBlockStart) {
  322. ASSIMP_LOG_ERROR("Invalid material: Texture unit block start missing near index ", ss.tellg());
  323. return false;
  324. }
  325. ASSIMP_LOG_VERBOSE_DEBUG(" texture_unit '", textureUnitName, "'");
  326. const string partTexture = "texture";
  327. const string partTextCoordSet = "tex_coord_set";
  328. const string partColorOp = "colour_op";
  329. aiTextureType textureType = aiTextureType_NONE;
  330. std::string textureRef;
  331. int uvCoord = 0;
  332. while (linePart != partBlockEnd) {
  333. ss >> linePart;
  334. // Skip commented lines
  335. if (linePart == partComment) {
  336. SkipLine(ss);
  337. continue;
  338. }
  339. if (linePart == partTexture) {
  340. ss >> linePart;
  341. textureRef = linePart;
  342. // User defined Assimp config property to detect texture type from filename.
  343. if (m_detectTextureTypeFromFilename) {
  344. size_t posSuffix = textureRef.find_last_of('.');
  345. size_t posUnderscore = textureRef.find_last_of('_');
  346. if (posSuffix != string::npos && posUnderscore != string::npos && posSuffix > posUnderscore) {
  347. string identifier = ai_tolower(textureRef.substr(posUnderscore, posSuffix - posUnderscore));
  348. ASSIMP_LOG_VERBOSE_DEBUG("Detecting texture type from filename postfix '", identifier, "'");
  349. if (identifier == "_n" || identifier == "_nrm" || identifier == "_nrml" || identifier == "_normal" || identifier == "_normals" || identifier == "_normalmap") {
  350. textureType = aiTextureType_NORMALS;
  351. } else if (identifier == "_s" || identifier == "_spec" || identifier == "_specular" || identifier == "_specularmap") {
  352. textureType = aiTextureType_SPECULAR;
  353. } else if (identifier == "_l" || identifier == "_light" || identifier == "_lightmap" || identifier == "_occ" || identifier == "_occlusion") {
  354. textureType = aiTextureType_LIGHTMAP;
  355. } else if (identifier == "_disp" || identifier == "_displacement") {
  356. textureType = aiTextureType_DISPLACEMENT;
  357. } else {
  358. textureType = aiTextureType_DIFFUSE;
  359. }
  360. } else {
  361. textureType = aiTextureType_DIFFUSE;
  362. }
  363. }
  364. // Detect from texture unit name. This cannot be too broad as
  365. // authors might give names like "LightSaber" or "NormalNinja".
  366. else {
  367. string unitNameLower = ai_tolower(textureUnitName);
  368. if (unitNameLower.find("normalmap") != string::npos) {
  369. textureType = aiTextureType_NORMALS;
  370. } else if (unitNameLower.find("specularmap") != string::npos) {
  371. textureType = aiTextureType_SPECULAR;
  372. } else if (unitNameLower.find("lightmap") != string::npos) {
  373. textureType = aiTextureType_LIGHTMAP;
  374. } else if (unitNameLower.find("displacementmap") != string::npos) {
  375. textureType = aiTextureType_DISPLACEMENT;
  376. } else {
  377. textureType = aiTextureType_DIFFUSE;
  378. }
  379. }
  380. } else if (linePart == partTextCoordSet) {
  381. ss >> uvCoord;
  382. }
  383. /// @todo Implement
  384. else if (linePart == partColorOp) {
  385. /*
  386. ss >> linePart;
  387. if("replace"==linePart)//I don't think, assimp has something for this...
  388. {
  389. }
  390. else if("modulate"==linePart)
  391. {
  392. //TODO: set value
  393. //material->AddProperty(aiTextureOp_Multiply)
  394. }
  395. */
  396. }
  397. }
  398. if (textureRef.empty()) {
  399. ASSIMP_LOG_WARN("Texture reference is empty, ignoring texture_unit.");
  400. return false;
  401. }
  402. if (textureType == aiTextureType_NONE) {
  403. ASSIMP_LOG_WARN("Failed to detect texture type for '", textureRef, "', ignoring texture_unit.");
  404. return false;
  405. }
  406. unsigned int textureTypeIndex = m_textures[textureType];
  407. m_textures[textureType]++;
  408. ASSIMP_LOG_VERBOSE_DEBUG(" texture '", textureRef, "' type ", textureType,
  409. " index ", textureTypeIndex, " UV ", uvCoord);
  410. aiString assimpTextureRef(textureRef);
  411. material->AddProperty(&assimpTextureRef, AI_MATKEY_TEXTURE(textureType, textureTypeIndex));
  412. material->AddProperty(&uvCoord, 1, AI_MATKEY_UVWSRC(textureType, textureTypeIndex));
  413. return true;
  414. }
  415. } // namespace Ogre
  416. } // namespace Assimp
  417. #endif // ASSIMP_BUILD_NO_OGRE_IMPORTER