PbrtExporter.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2022, 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. /* TODO:
  34. Material improvements:
  35. - don't export embedded textures that we're not going to use
  36. - diffuse roughness
  37. - what is with the uv mapping, uv transform not coming through??
  38. - metal? glass? mirror? detect these better?
  39. - eta/k from RGB?
  40. - emissive textures: warn at least
  41. Other:
  42. - use aiProcess_GenUVCoords if needed to handle spherical/planar uv mapping?
  43. - don't build up a big string in memory but write directly to a file
  44. - aiProcess_Triangulate meshes to get triangles only?
  45. - animation (allow specifying a time)
  46. */
  47. #ifndef ASSIMP_BUILD_NO_EXPORT
  48. #ifndef ASSIMP_BUILD_NO_PBRT_EXPORTER
  49. #include "PbrtExporter.h"
  50. #include <assimp/version.h>
  51. #include <assimp/DefaultIOSystem.h>
  52. #include <assimp/IOSystem.hpp>
  53. #include <assimp/Exporter.hpp>
  54. #include <assimp/DefaultLogger.hpp>
  55. #include <assimp/StreamWriter.h>
  56. #include <assimp/Exceptional.h>
  57. #include <assimp/material.h>
  58. #include <assimp/scene.h>
  59. #include <assimp/mesh.h>
  60. #include <algorithm>
  61. #include <cctype>
  62. #include <cmath>
  63. #include <fstream>
  64. #include <functional>
  65. #include <iostream>
  66. #include <memory>
  67. #include <sstream>
  68. #include <string>
  69. #include "Common/StbCommon.h"
  70. using namespace Assimp;
  71. namespace Assimp {
  72. void ExportScenePbrt (
  73. const char* pFile,
  74. IOSystem* pIOSystem,
  75. const aiScene* pScene,
  76. const ExportProperties* /*pProperties*/
  77. ){
  78. std::string path = DefaultIOSystem::absolutePath(std::string(pFile));
  79. std::string file = DefaultIOSystem::completeBaseName(std::string(pFile));
  80. // initialize the exporter
  81. PbrtExporter exporter(pScene, pIOSystem, path, file);
  82. }
  83. } // end of namespace Assimp
  84. // Constructor
  85. PbrtExporter::PbrtExporter(
  86. const aiScene *pScene, IOSystem *pIOSystem,
  87. const std::string &path, const std::string &file) :
  88. mScene(pScene),
  89. mIOSystem(pIOSystem),
  90. mPath(path),
  91. mFile(file) {
  92. // Export embedded textures.
  93. if (mScene->mNumTextures > 0)
  94. if (!mIOSystem->CreateDirectory("textures"))
  95. throw DeadlyExportError("Could not create textures/ directory.");
  96. for (unsigned int i = 0; i < mScene->mNumTextures; ++i) {
  97. aiTexture* tex = mScene->mTextures[i];
  98. std::string fn = CleanTextureFilename(tex->mFilename, false);
  99. std::cerr << "Writing embedded texture: " << tex->mFilename.C_Str() << " -> "
  100. << fn << "\n";
  101. std::unique_ptr<IOStream> outfile(mIOSystem->Open(fn, "wb"));
  102. if (!outfile) {
  103. throw DeadlyExportError("could not open output texture file: " + fn);
  104. }
  105. if (tex->mHeight == 0) {
  106. // It's binary data
  107. outfile->Write(tex->pcData, tex->mWidth, 1);
  108. } else {
  109. std::cerr << fn << ": TODO handle uncompressed embedded textures.\n";
  110. }
  111. }
  112. #if 0
  113. // Debugging: print the full node hierarchy
  114. std::function<void(aiNode*, int)> visitNode;
  115. visitNode = [&](aiNode* node, int depth) {
  116. for (int i = 0; i < depth; ++i) std::cerr << " ";
  117. std::cerr << node->mName.C_Str() << "\n";
  118. for (int i = 0; i < node->mNumChildren; ++i)
  119. visitNode(node->mChildren[i], depth + 1);
  120. };
  121. visitNode(mScene->mRootNode, 0);
  122. #endif
  123. mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION);
  124. // Write everything out
  125. WriteMetaData();
  126. WriteCameras();
  127. WriteWorldDefinition();
  128. // And write the file to disk...
  129. std::unique_ptr<IOStream> outfile(mIOSystem->Open(mPath,"wt"));
  130. if (!outfile) {
  131. throw DeadlyExportError("could not open output .pbrt file: " + std::string(mFile));
  132. }
  133. outfile->Write(mOutput.str().c_str(), mOutput.str().length(), 1);
  134. }
  135. // Destructor
  136. PbrtExporter::~PbrtExporter() {
  137. // Empty
  138. }
  139. void PbrtExporter::WriteMetaData() {
  140. mOutput << "#############################\n";
  141. mOutput << "# Scene metadata:\n";
  142. aiMetadata* pMetaData = mScene->mMetaData;
  143. for (unsigned int i = 0; i < pMetaData->mNumProperties; i++) {
  144. mOutput << "# - ";
  145. mOutput << pMetaData->mKeys[i].C_Str() << " :";
  146. switch(pMetaData->mValues[i].mType) {
  147. case AI_BOOL : {
  148. mOutput << " ";
  149. if (*static_cast<bool*>(pMetaData->mValues[i].mData))
  150. mOutput << "TRUE\n";
  151. else
  152. mOutput << "FALSE\n";
  153. break;
  154. }
  155. case AI_INT32 : {
  156. mOutput << " " <<
  157. *static_cast<int32_t*>(pMetaData->mValues[i].mData) <<
  158. std::endl;
  159. break;
  160. }
  161. case AI_UINT64 :
  162. mOutput << " " <<
  163. *static_cast<uint64_t*>(pMetaData->mValues[i].mData) <<
  164. std::endl;
  165. break;
  166. case AI_FLOAT :
  167. mOutput << " " <<
  168. *static_cast<float*>(pMetaData->mValues[i].mData) <<
  169. std::endl;
  170. break;
  171. case AI_DOUBLE :
  172. mOutput << " " <<
  173. *static_cast<double*>(pMetaData->mValues[i].mData) <<
  174. std::endl;
  175. break;
  176. case AI_AISTRING : {
  177. aiString* value =
  178. static_cast<aiString*>(pMetaData->mValues[i].mData);
  179. std::string svalue = value->C_Str();
  180. std::size_t found = svalue.find_first_of('\n');
  181. mOutput << "\n";
  182. while (found != std::string::npos) {
  183. mOutput << "# " << svalue.substr(0, found) << "\n";
  184. svalue = svalue.substr(found + 1);
  185. found = svalue.find_first_of('\n');
  186. }
  187. mOutput << "# " << svalue << "\n";
  188. break;
  189. }
  190. case AI_AIVECTOR3D :
  191. // TODO
  192. mOutput << " Vector3D (unable to print)\n";
  193. break;
  194. default:
  195. // AI_META_MAX and FORCE_32BIT
  196. mOutput << " META_MAX or FORCE_32Bit (unable to print)\n";
  197. break;
  198. }
  199. }
  200. }
  201. void PbrtExporter::WriteCameras() {
  202. mOutput << "\n";
  203. mOutput << "###############################\n";
  204. mOutput << "# Cameras (" << mScene->mNumCameras << ") total\n\n";
  205. if (mScene->mNumCameras == 0) {
  206. std::cerr << "Warning: No cameras found in scene file.\n";
  207. return;
  208. }
  209. if (mScene->mNumCameras > 1) {
  210. std::cerr << "Multiple cameras found in scene file; defaulting to first one specified.\n";
  211. }
  212. for (unsigned int i = 0; i < mScene->mNumCameras; i++) {
  213. WriteCamera(i);
  214. }
  215. }
  216. aiMatrix4x4 PbrtExporter::GetNodeTransform(const aiString &name) const {
  217. aiMatrix4x4 m;
  218. auto node = mScene->mRootNode->FindNode(name);
  219. if (!node) {
  220. std::cerr << '"' << name.C_Str() << "\": node not found in scene tree.\n";
  221. throw DeadlyExportError("Could not find node");
  222. }
  223. else {
  224. while (node) {
  225. m = node->mTransformation * m;
  226. node = node->mParent;
  227. }
  228. }
  229. return m;
  230. }
  231. std::string PbrtExporter::TransformAsString(const aiMatrix4x4 &m) {
  232. // Transpose on the way out to match pbrt's expected layout (sanity
  233. // check: the translation component should be the last 3 entries
  234. // before a '1' as the final entry in the matrix, assuming it's
  235. // non-projective.)
  236. std::stringstream s;
  237. s << m.a1 << " " << m.b1 << " " << m.c1 << " " << m.d1 << " "
  238. << m.a2 << " " << m.b2 << " " << m.c2 << " " << m.d2 << " "
  239. << m.a3 << " " << m.b3 << " " << m.c3 << " " << m.d3 << " "
  240. << m.a4 << " " << m.b4 << " " << m.c4 << " " << m.d4;
  241. return s.str();
  242. }
  243. void PbrtExporter::WriteCamera(int i) {
  244. auto camera = mScene->mCameras[i];
  245. bool cameraActive = i == 0;
  246. mOutput << "# - Camera " << i+1 << ": "
  247. << camera->mName.C_Str() << "\n";
  248. // Get camera aspect ratio
  249. float aspect = camera->mAspect;
  250. if (aspect == 0) {
  251. aspect = 4.f/3.f;
  252. mOutput << "# - Aspect ratio : 1.33333 (no aspect found, defaulting to 4/3)\n";
  253. } else {
  254. mOutput << "# - Aspect ratio : " << aspect << "\n";
  255. }
  256. // Get Film xres and yres
  257. int xres = 1920;
  258. int yres = (int)round(xres/aspect);
  259. // Print Film for this camera
  260. if (!cameraActive)
  261. mOutput << "# ";
  262. mOutput << "Film \"rgb\" \"string filename\" \"" << mFile << ".exr\"\n";
  263. if (!cameraActive)
  264. mOutput << "# ";
  265. mOutput << " \"integer xresolution\" [" << xres << "]\n";
  266. if (!cameraActive)
  267. mOutput << "# ";
  268. mOutput << " \"integer yresolution\" [" << yres << "]\n";
  269. // Get camera fov
  270. float hfov = AI_RAD_TO_DEG(camera->mHorizontalFOV);
  271. float fov = (aspect >= 1.0) ? hfov : (hfov * aspect);
  272. if (fov < 5) {
  273. std::cerr << fov << ": suspiciously low field of view specified by camera. Setting to 45 degrees.\n";
  274. fov = 45;
  275. }
  276. // Get camera transform
  277. aiMatrix4x4 worldFromCamera = GetNodeTransform(camera->mName);
  278. // Print Camera LookAt
  279. auto position = worldFromCamera * camera->mPosition;
  280. auto lookAt = worldFromCamera * (camera->mPosition + camera->mLookAt);
  281. aiMatrix3x3 worldFromCamera3(worldFromCamera);
  282. auto up = worldFromCamera3 * camera->mUp;
  283. up.Normalize();
  284. if (!cameraActive)
  285. mOutput << "# ";
  286. mOutput << "Scale -1 1 1\n"; // right handed -> left handed
  287. if (!cameraActive)
  288. mOutput << "# ";
  289. mOutput << "LookAt "
  290. << position.x << " " << position.y << " " << position.z << "\n";
  291. if (!cameraActive)
  292. mOutput << "# ";
  293. mOutput << " "
  294. << lookAt.x << " " << lookAt.y << " " << lookAt.z << "\n";
  295. if (!cameraActive)
  296. mOutput << "# ";
  297. mOutput << " "
  298. << up.x << " " << up.y << " " << up.z << "\n";
  299. // Print camera descriptor
  300. if (!cameraActive)
  301. mOutput << "# ";
  302. mOutput << "Camera \"perspective\" \"float fov\" " << "[" << fov << "]\n\n";
  303. }
  304. void PbrtExporter::WriteWorldDefinition() {
  305. // Figure out which meshes are referenced multiple times; those will be
  306. // emitted as object instances and the rest will be emitted directly.
  307. std::map<int, int> meshUses;
  308. std::function<void(aiNode*)> visitNode;
  309. visitNode = [&](aiNode* node) {
  310. for (unsigned int i = 0; i < node->mNumMeshes; ++i)
  311. ++meshUses[node->mMeshes[i]];
  312. for (unsigned int i = 0; i < node->mNumChildren; ++i)
  313. visitNode(node->mChildren[i]);
  314. };
  315. visitNode(mScene->mRootNode);
  316. int nInstanced = 0, nUnused = 0;
  317. for (const auto &u : meshUses) {
  318. if (u.second == 0) ++nUnused;
  319. else if (u.second > 1) ++nInstanced;
  320. }
  321. std::cerr << nInstanced << " / " << mScene->mNumMeshes << " meshes instanced.\n";
  322. if (nUnused)
  323. std::cerr << nUnused << " meshes defined but not used in scene.\n";
  324. mOutput << "WorldBegin\n";
  325. WriteLights();
  326. WriteTextures();
  327. WriteMaterials();
  328. // Object instance definitions
  329. mOutput << "# Object instance definitions\n\n";
  330. for (const auto &mu : meshUses) {
  331. if (mu.second > 1) {
  332. WriteInstanceDefinition(mu.first);
  333. }
  334. }
  335. mOutput << "# Geometry\n\n";
  336. aiMatrix4x4 worldFromObject;
  337. WriteGeometricObjects(mScene->mRootNode, worldFromObject, meshUses);
  338. }
  339. void PbrtExporter::WriteTextures() {
  340. mOutput << "###################\n";
  341. mOutput << "# Textures\n\n";
  342. C_STRUCT aiString path;
  343. aiTextureMapping mapping;
  344. unsigned int uvIndex;
  345. ai_real blend;
  346. aiTextureOp op;
  347. aiTextureMapMode mapMode[3];
  348. // For every material in the scene,
  349. for (unsigned int m = 0 ; m < mScene->mNumMaterials; m++) {
  350. auto material = mScene->mMaterials[m];
  351. // Parse through all texture types,
  352. for (int tt = 1; tt <= aiTextureType_UNKNOWN; tt++) {
  353. int ttCount = material->GetTextureCount(aiTextureType(tt));
  354. // ... and get every texture
  355. for (int t = 0; t < ttCount; t++) {
  356. // TODO write out texture specifics
  357. // TODO UV transforms may be material specific
  358. // so those may need to be baked into unique tex name
  359. if (material->GetTexture(aiTextureType(tt), t, &path, &mapping,
  360. &uvIndex, &blend, &op, mapMode) != AI_SUCCESS) {
  361. std::cerr << "Error getting texture! " << m << " " << tt << " " << t << "\n";
  362. continue;
  363. }
  364. std::string filename = CleanTextureFilename(path);
  365. if (uvIndex != 0)
  366. std::cerr << "Warning: texture \"" << filename << "\" uses uv set #" <<
  367. uvIndex << " but the pbrt converter only exports uv set 0.\n";
  368. #if 0
  369. if (op != aiTextureOp_Multiply)
  370. std::cerr << "Warning: unexpected texture op " << (int)op <<
  371. " encountered for texture \"" <<
  372. filename << "\". The resulting scene may have issues...\n";
  373. if (blend != 1)
  374. std::cerr << "Blend value of " << blend << " found for texture \"" << filename
  375. << "\" but not handled in converter.\n";
  376. #endif
  377. std::string mappingString;
  378. #if 0
  379. if (mapMode[0] != mapMode[1])
  380. std::cerr << "Different texture boundary mode for u and v for texture \"" <<
  381. filename << "\". Using u for both.\n";
  382. switch (mapMode[0]) {
  383. case aiTextureMapMode_Wrap:
  384. // pbrt's default
  385. break;
  386. case aiTextureMapMode_Clamp:
  387. mappingString = "\"string wrap\" \"clamp\"";
  388. break;
  389. case aiTextureMapMode_Decal:
  390. std::cerr << "Decal texture boundary mode not supported by pbrt for texture \"" <<
  391. filename << "\"\n";
  392. break;
  393. case aiTextureMapMode_Mirror:
  394. std::cerr << "Mirror texture boundary mode not supported by pbrt for texture \"" <<
  395. filename << "\"\n";
  396. break;
  397. default:
  398. std::cerr << "Unexpected map mode " << (int)mapMode[0] << " for texture \"" <<
  399. filename << "\"\n";
  400. //throw DeadlyExportError("Unexpected aiTextureMapMode");
  401. }
  402. #endif
  403. #if 0
  404. aiUVTransform uvTransform;
  405. if (material->Get(AI_MATKEY_TEXTURE(tt, t), uvTransform) == AI_SUCCESS) {
  406. mOutput << "# UV transform " << uvTransform.mTranslation.x << " "
  407. << uvTransform.mTranslation.y << " " << uvTransform.mScaling.x << " "
  408. << uvTransform.mScaling.y << " " << uvTransform.mRotation << "\n";
  409. }
  410. #endif
  411. std::string texName, texType, texOptions;
  412. if (aiTextureType(tt) == aiTextureType_SHININESS ||
  413. aiTextureType(tt) == aiTextureType_OPACITY ||
  414. aiTextureType(tt) == aiTextureType_HEIGHT ||
  415. aiTextureType(tt) == aiTextureType_DISPLACEMENT ||
  416. aiTextureType(tt) == aiTextureType_METALNESS ||
  417. aiTextureType(tt) == aiTextureType_DIFFUSE_ROUGHNESS) {
  418. texType = "float";
  419. texName = std::string("float:") + RemoveSuffix(filename);
  420. if (aiTextureType(tt) == aiTextureType_SHININESS) {
  421. texOptions = " \"bool invert\" true\n";
  422. texName += "_Roughness";
  423. }
  424. } else if (aiTextureType(tt) == aiTextureType_DIFFUSE ||
  425. aiTextureType(tt) == aiTextureType_BASE_COLOR) {
  426. texType = "spectrum";
  427. texName = std::string("rgb:") + RemoveSuffix(filename);
  428. }
  429. // Don't export textures we're not actually going to use...
  430. if (texName.empty())
  431. continue;
  432. if (mTextureSet.find(texName) == mTextureSet.end()) {
  433. mOutput << "Texture \"" << texName << "\" \"" << texType << "\" \"imagemap\"\n"
  434. << texOptions
  435. << " \"string filename\" \"" << filename << "\" " << mappingString << '\n';
  436. mTextureSet.insert(texName);
  437. }
  438. // Also emit a float version for use with alpha testing...
  439. if ((aiTextureType(tt) == aiTextureType_DIFFUSE ||
  440. aiTextureType(tt) == aiTextureType_BASE_COLOR) &&
  441. TextureHasAlphaMask(filename)) {
  442. texType = "float";
  443. texName = std::string("alpha:") + filename;
  444. if (mTextureSet.find(texName) == mTextureSet.end()) {
  445. mOutput << "Texture \"" << texName << "\" \"" << texType << "\" \"imagemap\"\n"
  446. << " \"string filename\" \"" << filename << "\" " << mappingString << '\n';
  447. mTextureSet.insert(texName);
  448. }
  449. }
  450. }
  451. }
  452. }
  453. }
  454. bool PbrtExporter::TextureHasAlphaMask(const std::string &filename) {
  455. // TODO: STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp);
  456. // quick return if it's 3
  457. int xSize, ySize, nComponents;
  458. unsigned char *data = stbi_load(filename.c_str(), &xSize, &ySize, &nComponents, 0);
  459. if (!data) {
  460. std::cerr << filename << ": unable to load texture and check for alpha mask in texture. "
  461. "Geometry will not be alpha masked with this texture.\n";
  462. return false;
  463. }
  464. bool hasMask = false;
  465. switch (nComponents) {
  466. case 1:
  467. for (int i = 0; i < xSize * ySize; ++i)
  468. if (data[i] != 255) {
  469. hasMask = true;
  470. break;
  471. }
  472. break;
  473. case 2:
  474. for (int y = 0; y < ySize; ++y)
  475. for (int x = 0; x < xSize; ++x)
  476. if (data[2 * (x + y * xSize) + 1] != 255) {
  477. hasMask = true;
  478. break;
  479. }
  480. break;
  481. case 3:
  482. break;
  483. case 4:
  484. for (int y = 0; y < ySize; ++y)
  485. for (int x = 0; x < xSize; ++x)
  486. if (data[4 * (x + y * xSize) + 3] != 255) {
  487. hasMask = true;
  488. break;
  489. }
  490. break;
  491. default:
  492. std::cerr << filename << ": unexpected number of image channels, " <<
  493. nComponents << ".\n";
  494. }
  495. stbi_image_free(data);
  496. return hasMask;
  497. }
  498. void PbrtExporter::WriteMaterials() {
  499. mOutput << "\n";
  500. mOutput << "####################\n";
  501. mOutput << "# Materials (" << mScene->mNumMaterials << ") total\n\n";
  502. for (unsigned int i = 0; i < mScene->mNumMaterials; i++) {
  503. WriteMaterial(i);
  504. }
  505. mOutput << "\n\n";
  506. }
  507. void PbrtExporter::WriteMaterial(int m) {
  508. aiMaterial* material = mScene->mMaterials[m];
  509. // get material name
  510. auto materialName = material->GetName();
  511. mOutput << std::endl << "# - Material " << m+1 << ": " << materialName.C_Str() << "\n";
  512. // Print out number of properties
  513. mOutput << "# - Number of Material Properties: " << material->mNumProperties << "\n";
  514. // Print out texture type counts
  515. mOutput << "# - Non-Zero Texture Type Counts: ";
  516. for (int i = 1; i <= aiTextureType_UNKNOWN; i++) {
  517. int count = material->GetTextureCount(aiTextureType(i));
  518. if (count > 0)
  519. mOutput << aiTextureTypeToString(aiTextureType(i)) << ": " << count << " ";
  520. }
  521. mOutput << "\n";
  522. auto White = [](const aiColor3D &c) { return c.r == 1 && c.g == 1 && c.b == 1; };
  523. auto Black = [](const aiColor3D &c) { return c.r == 0 && c.g == 0 && c.b == 0; };
  524. aiColor3D diffuse, specular, transparency;
  525. bool constantDiffuse = (material->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse) == AI_SUCCESS &&
  526. !White(diffuse));
  527. bool constantSpecular = (material->Get(AI_MATKEY_COLOR_SPECULAR, specular) == AI_SUCCESS &&
  528. !White(specular));
  529. bool constantTransparency = (material->Get(AI_MATKEY_COLOR_TRANSPARENT, transparency) == AI_SUCCESS &&
  530. !Black(transparency));
  531. float opacity, shininess, shininessStrength, eta;
  532. bool constantOpacity = (material->Get(AI_MATKEY_OPACITY, opacity) == AI_SUCCESS &&
  533. opacity != 0);
  534. bool constantShininess = material->Get(AI_MATKEY_SHININESS, shininess) == AI_SUCCESS;
  535. bool constantShininessStrength = material->Get(AI_MATKEY_SHININESS_STRENGTH, shininessStrength) == AI_SUCCESS;
  536. bool constantEta = (material->Get(AI_MATKEY_REFRACTI, eta) == AI_SUCCESS &&
  537. eta != 1);
  538. mOutput << "# - Constants: diffuse " << constantDiffuse << " specular " << constantSpecular <<
  539. " transparency " << constantTransparency << " opacity " << constantOpacity <<
  540. " shininess " << constantShininess << " shininess strength " << constantShininessStrength <<
  541. " eta " << constantEta << "\n";
  542. aiString roughnessMap;
  543. if (material->Get(AI_MATKEY_TEXTURE_SHININESS(0), roughnessMap) == AI_SUCCESS) {
  544. std::string roughnessTexture = std::string("float:") +
  545. RemoveSuffix(CleanTextureFilename(roughnessMap)) + "_Roughness";
  546. mOutput << "MakeNamedMaterial \"" << materialName.C_Str() << "\""
  547. << " \"string type\" \"coateddiffuse\"\n"
  548. << " \"texture roughness\" \"" << roughnessTexture << "\"\n";
  549. } else if (constantShininess) {
  550. // Assume plastic for now at least
  551. float roughness = std::max(0.f, 1.f - shininess);
  552. mOutput << "MakeNamedMaterial \"" << materialName.C_Str() << "\""
  553. << " \"string type\" \"coateddiffuse\"\n"
  554. << " \"float roughness\" " << roughness << "\n";
  555. } else
  556. // Diffuse
  557. mOutput << "MakeNamedMaterial \"" << materialName.C_Str() << "\""
  558. << " \"string type\" \"diffuse\"\n";
  559. aiString diffuseTexture;
  560. if (material->Get(AI_MATKEY_TEXTURE_DIFFUSE(0), diffuseTexture) == AI_SUCCESS)
  561. mOutput << " \"texture reflectance\" \"rgb:" << RemoveSuffix(CleanTextureFilename(diffuseTexture)) << "\"\n";
  562. else
  563. mOutput << " \"rgb reflectance\" [ " << diffuse.r << " " << diffuse.g <<
  564. " " << diffuse.b << " ]\n";
  565. aiString displacementTexture, normalMap;
  566. if (material->Get(AI_MATKEY_TEXTURE_NORMALS(0), displacementTexture) == AI_SUCCESS)
  567. mOutput << " \"string normalmap\" \"" << CleanTextureFilename(displacementTexture) << "\"\n";
  568. else if (material->Get(AI_MATKEY_TEXTURE_HEIGHT(0), displacementTexture) == AI_SUCCESS)
  569. mOutput << " \"texture displacement\" \"float:" <<
  570. RemoveSuffix(CleanTextureFilename(displacementTexture)) << "\"\n";
  571. else if (material->Get(AI_MATKEY_TEXTURE_DISPLACEMENT(0), displacementTexture) == AI_SUCCESS)
  572. mOutput << " \"texture displacement\" \"float:" <<
  573. RemoveSuffix(CleanTextureFilename(displacementTexture)) << "\"\n";
  574. }
  575. std::string PbrtExporter::CleanTextureFilename(const aiString &f, bool rewriteExtension) const {
  576. std::string fn = f.C_Str();
  577. // Remove directory name
  578. size_t offset = fn.find_last_of("/\\");
  579. if (offset != std::string::npos) {
  580. fn.erase(0, offset + 1);
  581. }
  582. // Expect all textures in textures
  583. fn = std::string("textures") + mIOSystem->getOsSeparator() + fn;
  584. // Rewrite extension for unsupported file formats.
  585. if (rewriteExtension) {
  586. offset = fn.rfind('.');
  587. if (offset != std::string::npos) {
  588. std::string extension = fn;
  589. extension.erase(0, offset + 1);
  590. std::transform(extension.begin(), extension.end(), extension.begin(),
  591. [](unsigned char c) { return (char)std::tolower(c); });
  592. if (extension != "tga" && extension != "exr" && extension != "png" &&
  593. extension != "pfm" && extension != "hdr") {
  594. std::string orig = fn;
  595. fn.erase(offset + 1);
  596. fn += "png";
  597. // Does it already exist? Warn if not.
  598. std::ifstream filestream(fn);
  599. if (!filestream.good())
  600. std::cerr << orig << ": must convert this texture to PNG.\n";
  601. }
  602. }
  603. }
  604. return fn;
  605. }
  606. std::string PbrtExporter::RemoveSuffix(std::string filename) {
  607. size_t offset = filename.rfind('.');
  608. if (offset != std::string::npos)
  609. filename.erase(offset);
  610. return filename;
  611. }
  612. void PbrtExporter::WriteLights() {
  613. mOutput << "\n";
  614. mOutput << "#################\n";
  615. mOutput << "# Lights\n\n";
  616. if (mScene->mNumLights == 0) {
  617. // Skip the default light if no cameras and this is flat up geometry
  618. if (mScene->mNumCameras > 0) {
  619. std::cerr << "No lights specified. Using default infinite light.\n";
  620. mOutput << "AttributeBegin\n";
  621. mOutput << " # default light\n";
  622. mOutput << " LightSource \"infinite\" \"blackbody L\" [6000 1]\n";
  623. mOutput << "AttributeEnd\n\n";
  624. }
  625. } else {
  626. for (unsigned int i = 0; i < mScene->mNumLights; ++i) {
  627. const aiLight *light = mScene->mLights[i];
  628. mOutput << "# Light " << light->mName.C_Str() << "\n";
  629. mOutput << "AttributeBegin\n";
  630. aiMatrix4x4 worldFromLight = GetNodeTransform(light->mName);
  631. mOutput << " Transform [ " << TransformAsString(worldFromLight) << " ]\n";
  632. aiColor3D color = light->mColorDiffuse + light->mColorSpecular;
  633. if (light->mAttenuationConstant != 0)
  634. color = color * (ai_real)(1. / light->mAttenuationConstant);
  635. switch (light->mType) {
  636. case aiLightSource_DIRECTIONAL: {
  637. mOutput << " LightSource \"distant\"\n";
  638. mOutput << " \"point3 from\" [ " << light->mPosition.x << " " <<
  639. light->mPosition.y << " " << light->mPosition.z << " ]\n";
  640. aiVector3D to = light->mPosition + light->mDirection;
  641. mOutput << " \"point3 to\" [ " << to.x << " " << to.y << " " << to.z << " ]\n";
  642. mOutput << " \"rgb L\" [ " << color.r << " " << color.g << " " << color.b << " ]\n";
  643. break;
  644. } case aiLightSource_POINT:
  645. mOutput << " LightSource \"distant\"\n";
  646. mOutput << " \"point3 from\" [ " << light->mPosition.x << " " <<
  647. light->mPosition.y << " " << light->mPosition.z << " ]\n";
  648. mOutput << " \"rgb L\" [ " << color.r << " " << color.g << " " << color.b << " ]\n";
  649. break;
  650. case aiLightSource_SPOT: {
  651. mOutput << " LightSource \"spot\"\n";
  652. mOutput << " \"point3 from\" [ " << light->mPosition.x << " " <<
  653. light->mPosition.y << " " << light->mPosition.z << " ]\n";
  654. aiVector3D to = light->mPosition + light->mDirection;
  655. mOutput << " \"point3 to\" [ " << to.x << " " << to.y << " " << to.z << " ]\n";
  656. mOutput << " \"rgb L\" [ " << color.r << " " << color.g << " " << color.b << " ]\n";
  657. mOutput << " \"float coneangle\" [ " << AI_RAD_TO_DEG(light->mAngleOuterCone) << " ]\n";
  658. mOutput << " \"float conedeltaangle\" [ " << AI_RAD_TO_DEG(light->mAngleOuterCone -
  659. light->mAngleInnerCone) << " ]\n";
  660. break;
  661. } case aiLightSource_AMBIENT:
  662. mOutput << "# ignored ambient light source\n";
  663. break;
  664. case aiLightSource_AREA: {
  665. aiVector3D left = light->mDirection ^ light->mUp;
  666. // rectangle. center at position, direction is normal vector
  667. ai_real dLeft = light->mSize.x / 2, dUp = light->mSize.y / 2;
  668. aiVector3D vertices[4] = {
  669. light->mPosition - dLeft * left - dUp * light->mUp,
  670. light->mPosition + dLeft * left - dUp * light->mUp,
  671. light->mPosition - dLeft * left + dUp * light->mUp,
  672. light->mPosition + dLeft * left + dUp * light->mUp };
  673. mOutput << " AreaLightSource \"diffuse\"\n";
  674. mOutput << " \"rgb L\" [ " << color.r << " " << color.g << " " << color.b << " ]\n";
  675. mOutput << " Shape \"bilinearmesh\"\n";
  676. mOutput << " \"point3 p\" [ ";
  677. for (int j = 0; j < 4; ++j)
  678. mOutput << vertices[j].x << " " << vertices[j].y << " " << vertices[j].z;
  679. mOutput << " ]\n";
  680. mOutput << " \"integer indices\" [ 0 1 2 3 ]\n";
  681. break;
  682. } default:
  683. mOutput << "# ignored undefined light source type\n";
  684. break;
  685. }
  686. mOutput << "AttributeEnd\n\n";
  687. }
  688. }
  689. }
  690. void PbrtExporter::WriteMesh(aiMesh* mesh) {
  691. mOutput << "# - Mesh: ";
  692. if (mesh->mName == aiString(""))
  693. mOutput << "<No Name>\n";
  694. else
  695. mOutput << mesh->mName.C_Str() << "\n";
  696. mOutput << "AttributeBegin\n";
  697. aiMaterial* material = mScene->mMaterials[mesh->mMaterialIndex];
  698. mOutput << " NamedMaterial \"" << material->GetName().C_Str() << "\"\n";
  699. // Handle area lights
  700. aiColor3D emission;
  701. if (material->Get(AI_MATKEY_COLOR_EMISSIVE, emission) == AI_SUCCESS &&
  702. (emission.r > 0 || emission.g > 0 || emission.b > 0))
  703. mOutput << " AreaLightSource \"diffuse\" \"rgb L\" [ " << emission.r <<
  704. " " << emission.g << " " << emission.b << " ]\n";
  705. // Check if any types other than tri
  706. if ( (mesh->mPrimitiveTypes & aiPrimitiveType_POINT)
  707. || (mesh->mPrimitiveTypes & aiPrimitiveType_LINE)
  708. || (mesh->mPrimitiveTypes & aiPrimitiveType_POLYGON)) {
  709. std::cerr << "Error: ignoring point / line / polygon mesh " << mesh->mName.C_Str() << ".\n";
  710. return;
  711. }
  712. // Alpha mask
  713. std::string alpha;
  714. aiString opacityTexture;
  715. if (material->Get(AI_MATKEY_TEXTURE_OPACITY(0), opacityTexture) == AI_SUCCESS ||
  716. material->Get(AI_MATKEY_TEXTURE_DIFFUSE(0), opacityTexture) == AI_SUCCESS) {
  717. // material->Get(AI_MATKEY_TEXTURE_BASE_COLOR(0), opacityTexture) == AI_SUCCESS)
  718. std::string texName = std::string("alpha:") + CleanTextureFilename(opacityTexture);
  719. if (mTextureSet.find(texName) != mTextureSet.end())
  720. alpha = std::string(" \"texture alpha\" \"") + texName + "\"\n";
  721. } else {
  722. float opacity = 1;
  723. if (material->Get(AI_MATKEY_OPACITY, opacity) == AI_SUCCESS && opacity < 1)
  724. alpha = std::string(" \"float alpha\" [ ") + std::to_string(opacity) + " ]\n";
  725. }
  726. // Output the shape specification
  727. mOutput << "Shape \"trianglemesh\"\n" <<
  728. alpha <<
  729. " \"integer indices\" [";
  730. // Start with faces (which hold indices)
  731. for (unsigned int i = 0; i < mesh->mNumFaces; i++) {
  732. auto face = mesh->mFaces[i];
  733. if (face.mNumIndices != 3) throw DeadlyExportError("oh no not a tri!");
  734. for (unsigned int j = 0; j < face.mNumIndices; j++) {
  735. mOutput << face.mIndices[j] << " ";
  736. }
  737. if ((i % 7) == 6) mOutput << "\n ";
  738. }
  739. mOutput << "]\n";
  740. // Then go to vertices
  741. mOutput << " \"point3 P\" [";
  742. for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
  743. auto vector = mesh->mVertices[i];
  744. mOutput << vector.x << " " << vector.y << " " << vector.z << " ";
  745. if ((i % 4) == 3) mOutput << "\n ";
  746. }
  747. mOutput << "]\n";
  748. // Normals (if present)
  749. if (mesh->mNormals) {
  750. mOutput << " \"normal N\" [";
  751. for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
  752. auto normal = mesh->mNormals[i];
  753. mOutput << normal.x << " " << normal.y << " " << normal.z << " ";
  754. if ((i % 4) == 3) mOutput << "\n ";
  755. }
  756. mOutput << "]\n";
  757. }
  758. // Tangents (if present)
  759. if (mesh->mTangents) {
  760. mOutput << " \"vector3 S\" [";
  761. for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
  762. auto tangent = mesh->mTangents[i];
  763. mOutput << tangent.x << " " << tangent.y << " " << tangent.z << " ";
  764. if ((i % 4) == 3) mOutput << "\n ";
  765. }
  766. mOutput << "]\n";
  767. }
  768. // Texture Coords (if present)
  769. // Find the first set of 2D texture coordinates..
  770. for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  771. if (mesh->mNumUVComponents[i] == 2) {
  772. // assert(mesh->mTextureCoords[i] != nullptr);
  773. aiVector3D* uv = mesh->mTextureCoords[i];
  774. mOutput << " \"point2 uv\" [";
  775. for (unsigned int j = 0; j < mesh->mNumVertices; ++j) {
  776. mOutput << uv[j].x << " " << uv[j].y << " ";
  777. if ((j % 6) == 5) mOutput << "\n ";
  778. }
  779. mOutput << "]\n";
  780. break;
  781. }
  782. }
  783. // TODO: issue warning if there are additional UV sets?
  784. mOutput << "AttributeEnd\n";
  785. }
  786. void PbrtExporter::WriteInstanceDefinition(int i) {
  787. aiMesh* mesh = mScene->mMeshes[i];
  788. mOutput << "ObjectBegin \"";
  789. if (mesh->mName == aiString(""))
  790. mOutput << "mesh_" << i+1 << "\"\n";
  791. else
  792. mOutput << mesh->mName.C_Str() << "_" << i+1 << "\"\n";
  793. WriteMesh(mesh);
  794. mOutput << "ObjectEnd\n";
  795. }
  796. void PbrtExporter::WriteGeometricObjects(aiNode* node, aiMatrix4x4 worldFromObject,
  797. std::map<int, int> &meshUses) {
  798. // Sometimes interior nodes have degenerate matrices??
  799. if (node->mTransformation.Determinant() != 0)
  800. worldFromObject = worldFromObject * node->mTransformation;
  801. if (node->mNumMeshes > 0) {
  802. mOutput << "AttributeBegin\n";
  803. mOutput << " Transform [ " << TransformAsString(worldFromObject) << "]\n";
  804. for (unsigned int i = 0; i < node->mNumMeshes; i++) {
  805. aiMesh* mesh = mScene->mMeshes[node->mMeshes[i]];
  806. if (meshUses[node->mMeshes[i]] == 1) {
  807. // If it's only used once in the scene, emit it directly as
  808. // a triangle mesh.
  809. mOutput << " # " << mesh->mName.C_Str();
  810. WriteMesh(mesh);
  811. } else {
  812. // If it's used multiple times, there will be an object
  813. // instance for it, so emit a reference to that.
  814. mOutput << " ObjectInstance \"";
  815. if (mesh->mName == aiString(""))
  816. mOutput << "mesh_" << node->mMeshes[i] + 1 << "\"\n";
  817. else
  818. mOutput << mesh->mName.C_Str() << "_" << node->mMeshes[i] + 1 << "\"\n";
  819. }
  820. }
  821. mOutput << "AttributeEnd\n\n";
  822. }
  823. // Recurse through children
  824. for (unsigned int i = 0; i < node->mNumChildren; i++) {
  825. WriteGeometricObjects(node->mChildren[i], worldFromObject, meshUses);
  826. }
  827. }
  828. #endif // ASSIMP_BUILD_NO_PBRT_EXPORTER
  829. #endif // ASSIMP_BUILD_NO_EXPORT