OgreMaterial.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2012, 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. #include "AssimpPCH.h"
  34. #ifndef ASSIMP_BUILD_NO_OGRE_IMPORTER
  35. #include <vector>
  36. #include <sstream>
  37. #include "OgreImporter.h"
  38. #include "irrXMLWrapper.h"
  39. #include "TinyFormatter.h"
  40. using namespace std;
  41. namespace Assimp
  42. {
  43. namespace Ogre
  44. {
  45. static const string partComment = "//";
  46. static const string partBlockStart = "{";
  47. static const string partBlockEnd = "}";
  48. aiMaterial* OgreImporter::ReadMaterial(const std::string &pFile, Assimp::IOSystem *pIOHandler, const std::string materialName)
  49. {
  50. /// @todo Should we return null ptr here or a empty material?
  51. if (materialName.empty())
  52. return new aiMaterial();
  53. // Full reference and examples of Ogre Material Script
  54. // can be found from http://www.ogre3d.org/docs/manual/manual_14.html
  55. /*and here is another one:
  56. import * from abstract_base_passes_depth.material
  57. import * from abstract_base.material
  58. import * from mat_shadow_caster.material
  59. import * from mat_character_singlepass.material
  60. material hero/hair/caster : mat_shadow_caster_skin_areject
  61. {
  62. set $diffuse_map "hero_hair_alpha_c.dds"
  63. }
  64. material hero/hair_alpha : mat_char_cns_singlepass_areject_4weights
  65. {
  66. set $diffuse_map "hero_hair_alpha_c.dds"
  67. set $specular_map "hero_hair_alpha_s.dds"
  68. set $normal_map "hero_hair_alpha_n.dds"
  69. set $light_map "black_lightmap.dds"
  70. set $shadow_caster_material "hero/hair/caster"
  71. }
  72. */
  73. stringstream ss;
  74. // Scope for scopre_ptr auto release
  75. {
  76. /* There are three .material options in priority order:
  77. 1) File with the material name (materialName)
  78. 2) File with the mesh files base name (pFile)
  79. 3) Optional user defined material library file (m_userDefinedMaterialLibFile) */
  80. std::vector<string> potentialFiles;
  81. potentialFiles.push_back(materialName + ".material");
  82. potentialFiles.push_back(pFile.substr(0, pFile.rfind(".mesh")) + ".material");
  83. if (!m_userDefinedMaterialLibFile.empty())
  84. potentialFiles.push_back(m_userDefinedMaterialLibFile);
  85. IOStream *materialFile = 0;
  86. for(size_t i=0; i<potentialFiles.size(); ++i)
  87. {
  88. materialFile = pIOHandler->Open(potentialFiles[i]);
  89. if (materialFile)
  90. break;
  91. DefaultLogger::get()->debug(Formatter::format() << "Source file for material '" << materialName << "' " << potentialFiles[i] << " does not exist");
  92. }
  93. if (!materialFile)
  94. {
  95. /// @todo Should we return null ptr here or a empty material?
  96. DefaultLogger::get()->error(Formatter::format() << "Failed to find source file for material '" << materialName << "'");
  97. return new aiMaterial();
  98. }
  99. boost::scoped_ptr<IOStream> stream(materialFile);
  100. if (stream->FileSize() == 0)
  101. {
  102. /// @todo Should we return null ptr here or a empty material?
  103. DefaultLogger::get()->warn(Formatter::format() << "Source file for material '" << materialName << "' is empty (size is 0 bytes)");
  104. return new aiMaterial();
  105. }
  106. // Read bytes
  107. vector<char> data(stream->FileSize());
  108. stream->Read(&data[0], stream->FileSize(), 1);
  109. // Convert to UTF-8 and terminate the string for ss
  110. BaseImporter::ConvertToUTF8(data);
  111. data.push_back('\0');
  112. ss << &data[0];
  113. }
  114. DefaultLogger::get()->debug("Reading material '" + materialName + "'");
  115. aiMaterial *material = new aiMaterial();
  116. m_textures.clear();
  117. aiString ts(materialName);
  118. material->AddProperty(&ts, AI_MATKEY_NAME);
  119. // The stringstream will push words from a line until newline.
  120. // It will also trim whitespace from line start and between words.
  121. string linePart;
  122. ss >> linePart;
  123. const string partMaterial = "material";
  124. const string partTechnique = "technique";
  125. while(!ss.eof())
  126. {
  127. // Skip commented lines
  128. if (linePart == partComment)
  129. {
  130. string postComment = NextAfterNewLine(ss, linePart);
  131. DefaultLogger::get()->debug("//" + postComment + " (comment line ignored)");
  132. continue;
  133. }
  134. if (linePart != partMaterial)
  135. {
  136. ss >> linePart;
  137. continue;
  138. }
  139. ss >> linePart;
  140. if (linePart != materialName)
  141. {
  142. //DefaultLogger::get()->debug(Formatter::format() << "Found material '" << linePart << "' that does not match at index " << ss.tellg());
  143. ss >> linePart;
  144. continue;
  145. }
  146. NextAfterNewLine(ss, linePart);
  147. if (linePart != partBlockStart)
  148. {
  149. DefaultLogger::get()->error(Formatter::format() << "Invalid material: block start missing near index " << ss.tellg());
  150. return material;
  151. }
  152. DefaultLogger::get()->debug("material '" + materialName + "'");
  153. while(linePart != partBlockEnd)
  154. {
  155. // Proceed to the first technique
  156. ss >> linePart;
  157. if (linePart == partTechnique)
  158. {
  159. string techniqueName = Trim(SkipLine(ss));
  160. ReadTechnique(techniqueName, ss, material);
  161. }
  162. // Read informations from a custom material
  163. /** @todo This "set $x y" does not seem to be a official Ogre material system feature.
  164. Materials can inherit other materials and override texture units by using the (unique)
  165. parent texture unit name in your cloned material.
  166. This is not yet supported and below code is probably some hack from the original
  167. author of this Ogre importer. Should be removed? */
  168. if(linePart=="set")
  169. {
  170. ss >> linePart;
  171. if(linePart=="$specular")//todo load this values:
  172. {
  173. }
  174. if(linePart=="$diffuse")
  175. {
  176. }
  177. if(linePart=="$ambient")
  178. {
  179. }
  180. if(linePart=="$colormap")
  181. {
  182. ss >> linePart;
  183. aiString ts(linePart.c_str());
  184. material->AddProperty(&ts, AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0));
  185. }
  186. if(linePart=="$normalmap")
  187. {
  188. ss >> linePart;
  189. aiString ts(linePart.c_str());
  190. material->AddProperty(&ts, AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0));
  191. }
  192. if(linePart=="$shininess_strength")
  193. {
  194. ss >> linePart;
  195. float Shininess=fast_atof(linePart.c_str());
  196. material->AddProperty(&Shininess, 1, AI_MATKEY_SHININESS_STRENGTH);
  197. }
  198. if(linePart=="$shininess_exponent")
  199. {
  200. ss >> linePart;
  201. float Shininess=fast_atof(linePart.c_str());
  202. material->AddProperty(&Shininess, 1, AI_MATKEY_SHININESS);
  203. }
  204. //Properties from Venetica:
  205. if(linePart=="$diffuse_map")
  206. {
  207. ss >> linePart;
  208. if(linePart[0]=='"')// "file" -> file
  209. linePart=linePart.substr(1, linePart.size()-2);
  210. aiString ts(linePart.c_str());
  211. material->AddProperty(&ts, AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0));
  212. }
  213. if(linePart=="$specular_map")
  214. {
  215. ss >> linePart;
  216. if(linePart[0]=='"')// "file" -> file
  217. linePart=linePart.substr(1, linePart.size()-2);
  218. aiString ts(linePart.c_str());
  219. material->AddProperty(&ts, AI_MATKEY_TEXTURE(aiTextureType_SHININESS, 0));
  220. }
  221. if(linePart=="$normal_map")
  222. {
  223. ss >> linePart;
  224. if(linePart[0]=='"')// "file" -> file
  225. linePart=linePart.substr(1, linePart.size()-2);
  226. aiString ts(linePart.c_str());
  227. material->AddProperty(&ts, AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0));
  228. }
  229. if(linePart=="$light_map")
  230. {
  231. ss >> linePart;
  232. if(linePart[0]=='"')// "file" -> file
  233. linePart=linePart.substr(1, linePart.size()-2);
  234. aiString ts(linePart.c_str());
  235. material->AddProperty(&ts, AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0));
  236. }
  237. }
  238. }
  239. ss >> linePart;
  240. }
  241. return material;
  242. }
  243. bool OgreImporter::ReadTechnique(const std::string &techniqueName, stringstream &ss, aiMaterial *material)
  244. {
  245. string linePart;
  246. ss >> linePart;
  247. if (linePart != partBlockStart)
  248. {
  249. DefaultLogger::get()->error(Formatter::format() << "Invalid material: Technique block start missing near index " << ss.tellg());
  250. return false;
  251. }
  252. DefaultLogger::get()->debug(" technique '" + techniqueName + "'");
  253. const string partPass = "pass";
  254. while(linePart != partBlockEnd)
  255. {
  256. ss >> linePart;
  257. // Skip commented lines
  258. if (linePart == partComment)
  259. {
  260. string postComment = SkipLine(ss);
  261. DefaultLogger::get()->debug(" //" + postComment + " (comment line ignored)");
  262. continue;
  263. }
  264. /// @todo Techniques have other attributes than just passes.
  265. if (linePart == partPass)
  266. {
  267. string passName = Trim(SkipLine(ss));
  268. ReadPass(passName, ss, material);
  269. }
  270. }
  271. return true;
  272. }
  273. bool OgreImporter::ReadPass(const std::string &passName, stringstream &ss, aiMaterial *material)
  274. {
  275. string linePart;
  276. ss >> linePart;
  277. if (linePart != partBlockStart)
  278. {
  279. DefaultLogger::get()->error(Formatter::format() << "Invalid material: Pass block start missing near index " << ss.tellg());
  280. return false;
  281. }
  282. DefaultLogger::get()->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. {
  290. ss >> linePart;
  291. // Skip commented lines
  292. if (linePart == partComment)
  293. {
  294. string postComment = SkipLine(ss);
  295. DefaultLogger::get()->debug(" //" + postComment + " (comment line ignored)");
  296. continue;
  297. }
  298. // Colors
  299. /// @todo Support alpha via aiColor4D.
  300. if (linePart == partAmbient || linePart == partDiffuse || linePart == partSpecular || linePart == partEmissive)
  301. {
  302. float r, g, b;
  303. ss >> r >> g >> b;
  304. const aiColor3D color(r, g, b);
  305. DefaultLogger::get()->debug(Formatter::format() << " " << linePart << " " << r << " " << g << " " << b);
  306. if (linePart == partAmbient)
  307. material->AddProperty(&color, 1, AI_MATKEY_COLOR_AMBIENT);
  308. else if (linePart == partDiffuse)
  309. material->AddProperty(&color, 1, AI_MATKEY_COLOR_DIFFUSE);
  310. else if (linePart == partSpecular)
  311. material->AddProperty(&color, 1, AI_MATKEY_COLOR_SPECULAR);
  312. else if (linePart == partEmissive)
  313. material->AddProperty(&color, 1, AI_MATKEY_COLOR_EMISSIVE);
  314. }
  315. else if (linePart == partTextureUnit)
  316. {
  317. string textureUnitName = Trim(SkipLine(ss));
  318. ReadTextureUnit(textureUnitName, ss, material);
  319. }
  320. }
  321. return true;
  322. }
  323. bool OgreImporter::ReadTextureUnit(const std::string &textureUnitName, stringstream &ss, aiMaterial *material)
  324. {
  325. string linePart;
  326. ss >> linePart;
  327. if (linePart != partBlockStart)
  328. {
  329. DefaultLogger::get()->error(Formatter::format() << "Invalid material: Texture unit block start missing near index " << ss.tellg());
  330. return false;
  331. }
  332. DefaultLogger::get()->debug(" texture_unit '" + textureUnitName + "'");
  333. const string partTexture = "texture";
  334. const string partTextCoordSet = "tex_coord_set";
  335. const string partColorOp = "colour_op";
  336. aiTextureType textureType = aiTextureType_NONE;
  337. std::string textureRef;
  338. int uvCoord = 0;
  339. while(linePart != partBlockEnd)
  340. {
  341. ss >> linePart;
  342. // Skip commented lines
  343. if (linePart == partComment)
  344. {
  345. string postComment = SkipLine(ss);
  346. DefaultLogger::get()->debug(" //" + postComment + " (comment line ignored)");
  347. continue;
  348. }
  349. if (linePart == partTexture)
  350. {
  351. ss >> linePart;
  352. textureRef = linePart;
  353. // User defined Assimp config property to detect texture type from filename.
  354. if (m_detectTextureTypeFromFilename)
  355. {
  356. size_t posSuffix = textureRef.find_last_of(".");
  357. size_t posUnderscore = textureRef.find_last_of("_");
  358. if (posSuffix != string::npos && posUnderscore != string::npos && posSuffix > posUnderscore)
  359. {
  360. string identifier = Ogre::ToLower(textureRef.substr(posUnderscore, posSuffix - posUnderscore));
  361. DefaultLogger::get()->debug(Formatter::format() << "Detecting texture type from filename postfix '" << identifier << "'");
  362. if (identifier == "_n" || identifier == "_nrm" || identifier == "_nrml" || identifier == "_normal" || identifier == "_normals" || identifier == "_normalmap")
  363. textureType = aiTextureType_NORMALS;
  364. else if (identifier == "_s" || identifier == "_spec" || identifier == "_specular" || identifier == "_specularmap")
  365. textureType = aiTextureType_SPECULAR;
  366. else if (identifier == "_l" || identifier == "_light" || identifier == "_lightmap" || identifier == "_occ" || identifier == "_occlusion")
  367. textureType = aiTextureType_LIGHTMAP;
  368. else if (identifier == "_disp" || identifier == "_displacement")
  369. textureType = aiTextureType_DISPLACEMENT;
  370. else
  371. textureType = aiTextureType_DIFFUSE;
  372. }
  373. else
  374. textureType = aiTextureType_DIFFUSE;
  375. }
  376. // Detect from texture unit name. This cannot be too broad as
  377. // authors might give names like "LightSaber" or "NormalNinja".
  378. else
  379. {
  380. string unitNameLower = Ogre::ToLower(textureUnitName);
  381. if (unitNameLower.find("normalmap") != string::npos)
  382. textureType = aiTextureType_NORMALS;
  383. else if (unitNameLower.find("specularmap") != string::npos)
  384. textureType = aiTextureType_SPECULAR;
  385. else if (unitNameLower.find("lightmap") != string::npos)
  386. textureType = aiTextureType_LIGHTMAP;
  387. else if (unitNameLower.find("displacementmap") != string::npos)
  388. textureType = aiTextureType_DISPLACEMENT;
  389. else
  390. textureType = aiTextureType_DIFFUSE;
  391. }
  392. }
  393. else if (linePart == partTextCoordSet)
  394. {
  395. ss >> uvCoord;
  396. }
  397. /// @todo Implement
  398. else if(linePart == partColorOp)
  399. {
  400. /*
  401. ss >> linePart;
  402. if("replace"==linePart)//I don't think, assimp has something for this...
  403. {
  404. }
  405. else if("modulate"==linePart)
  406. {
  407. //TODO: set value
  408. //material->AddProperty(aiTextureOp_Multiply)
  409. }
  410. */
  411. }
  412. }
  413. if (textureRef.empty())
  414. {
  415. DefaultLogger::get()->warn("Texture reference is empty, ignoring texture_unit.");
  416. return false;
  417. }
  418. if (textureType == aiTextureType_NONE)
  419. {
  420. DefaultLogger::get()->warn("Failed to detect texture type for '" + textureRef + "', ignoring texture_unit.");
  421. return false;
  422. }
  423. unsigned int textureTypeIndex = m_textures[textureType];
  424. m_textures[textureType]++;
  425. DefaultLogger::get()->debug(Formatter::format() << " texture '" << textureRef << "' type " << textureType
  426. << " index " << textureTypeIndex << " UV " << uvCoord);
  427. aiString assimpTextureRef(textureRef);
  428. material->AddProperty(&assimpTextureRef, AI_MATKEY_TEXTURE(textureType, textureTypeIndex));
  429. material->AddProperty(&uvCoord, 1, AI_MATKEY_UVWSRC(textureType, textureTypeIndex));
  430. return true;
  431. }
  432. } // Ogre
  433. } // Assimp
  434. #endif // ASSIMP_BUILD_NO_OGRE_IMPORTER