ObjExporter.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2020, 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_EXPORT
  34. #ifndef ASSIMP_BUILD_NO_OBJ_EXPORTER
  35. #include "ObjExporter.h"
  36. #include <assimp/Exceptional.h>
  37. #include <assimp/StringComparison.h>
  38. #include <assimp/version.h>
  39. #include <assimp/IOSystem.hpp>
  40. #include <assimp/Exporter.hpp>
  41. #include <assimp/material.h>
  42. #include <assimp/scene.h>
  43. #include <memory>
  44. using namespace Assimp;
  45. namespace Assimp {
  46. // ------------------------------------------------------------------------------------------------
  47. // Worker function for exporting a scene to Wavefront OBJ. Prototyped and registered in Exporter.cpp
  48. void ExportSceneObj(const char* pFile,IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* /*pProperties*/) {
  49. // invoke the exporter
  50. ObjExporter exporter(pFile, pScene);
  51. if (exporter.mOutput.fail() || exporter.mOutputMat.fail()) {
  52. throw DeadlyExportError("output data creation failed. Most likely the file became too large: " + std::string(pFile));
  53. }
  54. // we're still here - export successfully completed. Write both the main OBJ file and the material script
  55. {
  56. std::unique_ptr<IOStream> outfile (pIOSystem->Open(pFile,"wt"));
  57. if (outfile == nullptr) {
  58. throw DeadlyExportError("could not open output .obj file: " + std::string(pFile));
  59. }
  60. outfile->Write( exporter.mOutput.str().c_str(), static_cast<size_t>(exporter.mOutput.tellp()),1);
  61. }
  62. {
  63. std::unique_ptr<IOStream> outfile (pIOSystem->Open(exporter.GetMaterialLibFileName(),"wt"));
  64. if (outfile == nullptr) {
  65. throw DeadlyExportError("could not open output .mtl file: " + std::string(exporter.GetMaterialLibFileName()));
  66. }
  67. outfile->Write( exporter.mOutputMat.str().c_str(), static_cast<size_t>(exporter.mOutputMat.tellp()),1);
  68. }
  69. }
  70. // ------------------------------------------------------------------------------------------------
  71. // Worker function for exporting a scene to Wavefront OBJ without the material file. Prototyped and registered in Exporter.cpp
  72. void ExportSceneObjNoMtl(const char* pFile,IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* ) {
  73. // invoke the exporter
  74. ObjExporter exporter(pFile, pScene, true);
  75. if (exporter.mOutput.fail() || exporter.mOutputMat.fail()) {
  76. throw DeadlyExportError("output data creation failed. Most likely the file became too large: " + std::string(pFile));
  77. }
  78. // we're still here - export successfully completed. Write both the main OBJ file and the material script
  79. {
  80. std::unique_ptr<IOStream> outfile (pIOSystem->Open(pFile,"wt"));
  81. if (outfile == nullptr) {
  82. throw DeadlyExportError("could not open output .obj file: " + std::string(pFile));
  83. }
  84. outfile->Write( exporter.mOutput.str().c_str(), static_cast<size_t>(exporter.mOutput.tellp()),1);
  85. }
  86. }
  87. } // end of namespace Assimp
  88. static const std::string MaterialExt = ".mtl";
  89. // ------------------------------------------------------------------------------------------------
  90. ObjExporter::ObjExporter(const char* _filename, const aiScene* pScene, bool noMtl)
  91. : filename(_filename)
  92. , pScene(pScene)
  93. , vn()
  94. , vt()
  95. , vp()
  96. , useVc(false)
  97. , mVnMap()
  98. , mVtMap()
  99. , mVpMap()
  100. , mMeshes()
  101. , endl("\n") {
  102. // make sure that all formatting happens using the standard, C locale and not the user's current locale
  103. const std::locale& l = std::locale("C");
  104. mOutput.imbue(l);
  105. mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION);
  106. mOutputMat.imbue(l);
  107. mOutputMat.precision(ASSIMP_AI_REAL_TEXT_PRECISION);
  108. WriteGeometryFile(noMtl);
  109. if ( !noMtl ) {
  110. WriteMaterialFile();
  111. }
  112. }
  113. // ------------------------------------------------------------------------------------------------
  114. ObjExporter::~ObjExporter() {
  115. // empty
  116. }
  117. // ------------------------------------------------------------------------------------------------
  118. std::string ObjExporter::GetMaterialLibName() {
  119. // within the Obj file, we use just the relative file name with the path stripped
  120. const std::string& s = GetMaterialLibFileName();
  121. std::string::size_type il = s.find_last_of("/\\");
  122. if (il != std::string::npos) {
  123. return s.substr(il + 1);
  124. }
  125. return s;
  126. }
  127. // ------------------------------------------------------------------------------------------------
  128. std::string ObjExporter::GetMaterialLibFileName() {
  129. // Remove existing .obj file extension so that the final material file name will be fileName.mtl and not fileName.obj.mtl
  130. size_t lastdot = filename.find_last_of('.');
  131. if ( lastdot != std::string::npos ) {
  132. return filename.substr( 0, lastdot ) + MaterialExt;
  133. }
  134. return filename + MaterialExt;
  135. }
  136. // ------------------------------------------------------------------------------------------------
  137. void ObjExporter::WriteHeader(std::ostringstream& out) {
  138. out << "# File produced by Open Asset Import Library (http://www.assimp.sf.net)" << endl;
  139. out << "# (assimp v" << aiGetVersionMajor() << '.' << aiGetVersionMinor() << '.'
  140. << aiGetVersionRevision() << ")" << endl << endl;
  141. }
  142. // ------------------------------------------------------------------------------------------------
  143. std::string ObjExporter::GetMaterialName(unsigned int index) {
  144. const aiMaterial* const mat = pScene->mMaterials[index];
  145. if ( nullptr == mat ) {
  146. static const std::string EmptyStr;
  147. return EmptyStr;
  148. }
  149. aiString s;
  150. if(AI_SUCCESS == mat->Get(AI_MATKEY_NAME,s)) {
  151. return std::string(s.data,s.length);
  152. }
  153. char number[ sizeof(unsigned int) * 3 + 1 ];
  154. ASSIMP_itoa10(number,index);
  155. return "$Material_" + std::string(number);
  156. }
  157. // ------------------------------------------------------------------------------------------------
  158. void ObjExporter::WriteMaterialFile() {
  159. WriteHeader(mOutputMat);
  160. for(unsigned int i = 0; i < pScene->mNumMaterials; ++i) {
  161. const aiMaterial* const mat = pScene->mMaterials[i];
  162. int illum = 1;
  163. mOutputMat << "newmtl " << GetMaterialName(i) << endl;
  164. aiColor4D c;
  165. if(AI_SUCCESS == mat->Get(AI_MATKEY_COLOR_DIFFUSE,c)) {
  166. mOutputMat << "Kd " << c.r << " " << c.g << " " << c.b << endl;
  167. }
  168. if(AI_SUCCESS == mat->Get(AI_MATKEY_COLOR_AMBIENT,c)) {
  169. mOutputMat << "Ka " << c.r << " " << c.g << " " << c.b << endl;
  170. }
  171. if(AI_SUCCESS == mat->Get(AI_MATKEY_COLOR_SPECULAR,c)) {
  172. mOutputMat << "Ks " << c.r << " " << c.g << " " << c.b << endl;
  173. }
  174. if(AI_SUCCESS == mat->Get(AI_MATKEY_COLOR_EMISSIVE,c)) {
  175. mOutputMat << "Ke " << c.r << " " << c.g << " " << c.b << endl;
  176. }
  177. if(AI_SUCCESS == mat->Get(AI_MATKEY_COLOR_TRANSPARENT,c)) {
  178. mOutputMat << "Tf " << c.r << " " << c.g << " " << c.b << endl;
  179. }
  180. ai_real o;
  181. if(AI_SUCCESS == mat->Get(AI_MATKEY_OPACITY,o)) {
  182. mOutputMat << "d " << o << endl;
  183. }
  184. if(AI_SUCCESS == mat->Get(AI_MATKEY_REFRACTI,o)) {
  185. mOutputMat << "Ni " << o << endl;
  186. }
  187. if(AI_SUCCESS == mat->Get(AI_MATKEY_SHININESS,o) && o) {
  188. mOutputMat << "Ns " << o << endl;
  189. illum = 2;
  190. }
  191. mOutputMat << "illum " << illum << endl;
  192. aiString s;
  193. if(AI_SUCCESS == mat->Get(AI_MATKEY_TEXTURE_DIFFUSE(0),s)) {
  194. mOutputMat << "map_Kd " << s.data << endl;
  195. }
  196. if(AI_SUCCESS == mat->Get(AI_MATKEY_TEXTURE_AMBIENT(0),s)) {
  197. mOutputMat << "map_Ka " << s.data << endl;
  198. }
  199. if(AI_SUCCESS == mat->Get(AI_MATKEY_TEXTURE_SPECULAR(0),s)) {
  200. mOutputMat << "map_Ks " << s.data << endl;
  201. }
  202. if(AI_SUCCESS == mat->Get(AI_MATKEY_TEXTURE_SHININESS(0),s)) {
  203. mOutputMat << "map_Ns " << s.data << endl;
  204. }
  205. if(AI_SUCCESS == mat->Get(AI_MATKEY_TEXTURE_OPACITY(0),s)) {
  206. mOutputMat << "map_d " << s.data << endl;
  207. }
  208. if(AI_SUCCESS == mat->Get(AI_MATKEY_TEXTURE_HEIGHT(0),s) || AI_SUCCESS == mat->Get(AI_MATKEY_TEXTURE_NORMALS(0),s)) {
  209. // implementations seem to vary here, so write both variants
  210. mOutputMat << "bump " << s.data << endl;
  211. mOutputMat << "map_bump " << s.data << endl;
  212. }
  213. mOutputMat << endl;
  214. }
  215. }
  216. void ObjExporter::WriteGeometryFile(bool noMtl) {
  217. WriteHeader(mOutput);
  218. if (!noMtl)
  219. mOutput << "mtllib " << GetMaterialLibName() << endl << endl;
  220. // collect mesh geometry
  221. aiMatrix4x4 mBase;
  222. AddNode(pScene->mRootNode, mBase);
  223. // write vertex positions with colors, if any
  224. mVpMap.getKeys( vp );
  225. if ( !useVc ) {
  226. mOutput << "# " << vp.size() << " vertex positions" << endl;
  227. for ( const vertexData& v : vp ) {
  228. mOutput << "v " << v.vp.x << " " << v.vp.y << " " << v.vp.z << endl;
  229. }
  230. } else {
  231. mOutput << "# " << vp.size() << " vertex positions and colors" << endl;
  232. for ( const vertexData& v : vp ) {
  233. mOutput << "v " << v.vp.x << " " << v.vp.y << " " << v.vp.z << " " << v.vc.r << " " << v.vc.g << " " << v.vc.b << endl;
  234. }
  235. }
  236. mOutput << endl;
  237. // write uv coordinates
  238. mVtMap.getKeys(vt);
  239. mOutput << "# " << vt.size() << " UV coordinates" << endl;
  240. for(const aiVector3D& v : vt) {
  241. mOutput << "vt " << v.x << " " << v.y << " " << v.z << endl;
  242. }
  243. mOutput << endl;
  244. // write vertex normals
  245. mVnMap.getKeys(vn);
  246. mOutput << "# " << vn.size() << " vertex normals" << endl;
  247. for(const aiVector3D& v : vn) {
  248. mOutput << "vn " << v.x << " " << v.y << " " << v.z << endl;
  249. }
  250. mOutput << endl;
  251. // now write all mesh instances
  252. for(const MeshInstance& m : mMeshes) {
  253. mOutput << "# Mesh \'" << m.name << "\' with " << m.faces.size() << " faces" << endl;
  254. if (!m.name.empty()) {
  255. mOutput << "g " << m.name << endl;
  256. }
  257. if ( !noMtl ) {
  258. mOutput << "usemtl " << m.matname << endl;
  259. }
  260. for(const Face& f : m.faces) {
  261. mOutput << f.kind << ' ';
  262. for(const FaceVertex& fv : f.indices) {
  263. mOutput << ' ' << fv.vp;
  264. if (f.kind != 'p') {
  265. if (fv.vt || f.kind == 'f') {
  266. mOutput << '/';
  267. }
  268. if (fv.vt) {
  269. mOutput << fv.vt;
  270. }
  271. if (f.kind == 'f' && fv.vn) {
  272. mOutput << '/' << fv.vn;
  273. }
  274. }
  275. }
  276. mOutput << endl;
  277. }
  278. mOutput << endl;
  279. }
  280. }
  281. // ------------------------------------------------------------------------------------------------
  282. void ObjExporter::AddMesh(const aiString& name, const aiMesh* m, const aiMatrix4x4& mat) {
  283. mMeshes.push_back(MeshInstance() );
  284. MeshInstance& mesh = mMeshes.back();
  285. if ( nullptr != m->mColors[ 0 ] ) {
  286. useVc = true;
  287. }
  288. mesh.name = std::string( name.data, name.length );
  289. mesh.matname = GetMaterialName(m->mMaterialIndex);
  290. mesh.faces.resize(m->mNumFaces);
  291. for(unsigned int i = 0; i < m->mNumFaces; ++i) {
  292. const aiFace& f = m->mFaces[i];
  293. Face& face = mesh.faces[i];
  294. switch (f.mNumIndices) {
  295. case 1:
  296. face.kind = 'p';
  297. break;
  298. case 2:
  299. face.kind = 'l';
  300. break;
  301. default:
  302. face.kind = 'f';
  303. }
  304. face.indices.resize(f.mNumIndices);
  305. for(unsigned int a = 0; a < f.mNumIndices; ++a) {
  306. const unsigned int idx = f.mIndices[a];
  307. aiVector3D vert = mat * m->mVertices[idx];
  308. if ( nullptr != m->mColors[ 0 ] ) {
  309. aiColor4D col4 = m->mColors[ 0 ][ idx ];
  310. face.indices[a].vp = mVpMap.getIndex({vert, aiColor3D(col4.r, col4.g, col4.b)});
  311. } else {
  312. face.indices[a].vp = mVpMap.getIndex({vert, aiColor3D(0,0,0)});
  313. }
  314. if (m->mNormals) {
  315. aiVector3D norm = aiMatrix3x3(mat) * m->mNormals[idx];
  316. face.indices[a].vn = mVnMap.getIndex(norm);
  317. } else {
  318. face.indices[a].vn = 0;
  319. }
  320. if ( m->mTextureCoords[ 0 ] ) {
  321. face.indices[a].vt = mVtMap.getIndex(m->mTextureCoords[0][idx]);
  322. } else {
  323. face.indices[a].vt = 0;
  324. }
  325. }
  326. }
  327. }
  328. // ------------------------------------------------------------------------------------------------
  329. void ObjExporter::AddNode(const aiNode* nd, const aiMatrix4x4& mParent) {
  330. const aiMatrix4x4& mAbs = mParent * nd->mTransformation;
  331. aiMesh *cm( nullptr );
  332. for(unsigned int i = 0; i < nd->mNumMeshes; ++i) {
  333. cm = pScene->mMeshes[nd->mMeshes[i]];
  334. if (nullptr != cm) {
  335. AddMesh(cm->mName, pScene->mMeshes[nd->mMeshes[i]], mAbs);
  336. } else {
  337. AddMesh(nd->mName, pScene->mMeshes[nd->mMeshes[i]], mAbs);
  338. }
  339. }
  340. for(unsigned int i = 0; i < nd->mNumChildren; ++i) {
  341. AddNode(nd->mChildren[i], mAbs);
  342. }
  343. }
  344. // ------------------------------------------------------------------------------------------------
  345. #endif // ASSIMP_BUILD_NO_OBJ_EXPORTER
  346. #endif // ASSIMP_BUILD_NO_EXPORT