PlyLoader.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2020, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file PlyLoader.cpp
  35. * @brief Implementation of the PLY importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_PLY_IMPORTER
  38. // internal headers
  39. #include "PlyLoader.h"
  40. #include <assimp/IOStreamBuffer.h>
  41. #include <assimp/importerdesc.h>
  42. #include <assimp/scene.h>
  43. #include <assimp/IOSystem.hpp>
  44. #include <memory>
  45. using namespace ::Assimp;
  46. static const aiImporterDesc desc = {
  47. "Stanford Polygon Library (PLY) Importer",
  48. "",
  49. "",
  50. "",
  51. aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportTextFlavour,
  52. 0,
  53. 0,
  54. 0,
  55. 0,
  56. "ply"
  57. };
  58. // ------------------------------------------------------------------------------------------------
  59. // Internal stuff
  60. namespace {
  61. // ------------------------------------------------------------------------------------------------
  62. // Checks that property index is within range
  63. template <class T>
  64. inline const T &GetProperty(const std::vector<T> &props, int idx) {
  65. if (static_cast<size_t>(idx) >= props.size()) {
  66. throw DeadlyImportError("Invalid .ply file: Property index is out of range.");
  67. }
  68. return props[idx];
  69. }
  70. } // namespace
  71. // ------------------------------------------------------------------------------------------------
  72. // Constructor to be privately used by Importer
  73. PLYImporter::PLYImporter() :
  74. mBuffer(nullptr), pcDOM(nullptr), mGeneratedMesh(nullptr) {
  75. // empty
  76. }
  77. // ------------------------------------------------------------------------------------------------
  78. // Destructor, private as well
  79. PLYImporter::~PLYImporter() {
  80. // empty
  81. }
  82. // ------------------------------------------------------------------------------------------------
  83. // Returns whether the class can handle the format of the given file.
  84. bool PLYImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const {
  85. const std::string extension = GetExtension(pFile);
  86. if (extension == "ply") {
  87. return true;
  88. } else if (!extension.length() || checkSig) {
  89. if (!pIOHandler) {
  90. return true;
  91. }
  92. static const char *tokens[] = { "ply" };
  93. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, 1);
  94. }
  95. return false;
  96. }
  97. // ------------------------------------------------------------------------------------------------
  98. const aiImporterDesc *PLYImporter::GetInfo() const {
  99. return &desc;
  100. }
  101. // ------------------------------------------------------------------------------------------------
  102. static bool isBigEndian(const char *szMe) {
  103. ai_assert(nullptr != szMe);
  104. // binary_little_endian
  105. // binary_big_endian
  106. bool isBigEndian(false);
  107. #if (defined AI_BUILD_BIG_ENDIAN)
  108. if ('l' == *szMe || 'L' == *szMe) {
  109. isBigEndian = true;
  110. }
  111. #else
  112. if ('b' == *szMe || 'B' == *szMe) {
  113. isBigEndian = true;
  114. }
  115. #endif // ! AI_BUILD_BIG_ENDIAN
  116. return isBigEndian;
  117. }
  118. // ------------------------------------------------------------------------------------------------
  119. // Imports the given file into the given scene structure.
  120. void PLYImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
  121. const std::string mode = "rb";
  122. std::unique_ptr<IOStream> fileStream(pIOHandler->Open(pFile, mode));
  123. if (!fileStream.get()) {
  124. throw DeadlyImportError("Failed to open file " + pFile + ".");
  125. }
  126. // Get the file-size
  127. const size_t fileSize(fileStream->FileSize());
  128. if (0 == fileSize) {
  129. throw DeadlyImportError("File " + pFile + " is empty.");
  130. }
  131. IOStreamBuffer<char> streamedBuffer(1024 * 1024);
  132. streamedBuffer.open(fileStream.get());
  133. // the beginning of the file must be PLY - magic, magic
  134. std::vector<char> headerCheck;
  135. streamedBuffer.getNextLine(headerCheck);
  136. if ((headerCheck.size() < 3) ||
  137. (headerCheck[0] != 'P' && headerCheck[0] != 'p') ||
  138. (headerCheck[1] != 'L' && headerCheck[1] != 'l') ||
  139. (headerCheck[2] != 'Y' && headerCheck[2] != 'y')) {
  140. streamedBuffer.close();
  141. throw DeadlyImportError("Invalid .ply file: Magic number \'ply\' is no there");
  142. }
  143. std::vector<char> mBuffer2;
  144. streamedBuffer.getNextLine(mBuffer2);
  145. mBuffer = (unsigned char *)&mBuffer2[0];
  146. char *szMe = (char *)&this->mBuffer[0];
  147. SkipSpacesAndLineEnd(szMe, (const char **)&szMe);
  148. // determine the format of the file data and construct the aiMesh
  149. PLY::DOM sPlyDom;
  150. this->pcDOM = &sPlyDom;
  151. if (TokenMatch(szMe, "format", 6)) {
  152. if (TokenMatch(szMe, "ascii", 5)) {
  153. SkipLine(szMe, (const char **)&szMe);
  154. if (!PLY::DOM::ParseInstance(streamedBuffer, &sPlyDom, this)) {
  155. if (mGeneratedMesh != nullptr) {
  156. delete (mGeneratedMesh);
  157. mGeneratedMesh = nullptr;
  158. }
  159. streamedBuffer.close();
  160. throw DeadlyImportError("Invalid .ply file: Unable to build DOM (#1)");
  161. }
  162. } else if (!::strncmp(szMe, "binary_", 7)) {
  163. szMe += 7;
  164. const bool bIsBE(isBigEndian(szMe));
  165. // skip the line, parse the rest of the header and build the DOM
  166. if (!PLY::DOM::ParseInstanceBinary(streamedBuffer, &sPlyDom, this, bIsBE)) {
  167. if (mGeneratedMesh != nullptr) {
  168. delete (mGeneratedMesh);
  169. mGeneratedMesh = nullptr;
  170. }
  171. streamedBuffer.close();
  172. throw DeadlyImportError("Invalid .ply file: Unable to build DOM (#2)");
  173. }
  174. } else {
  175. if (mGeneratedMesh != nullptr) {
  176. delete (mGeneratedMesh);
  177. mGeneratedMesh = nullptr;
  178. }
  179. streamedBuffer.close();
  180. throw DeadlyImportError("Invalid .ply file: Unknown file format");
  181. }
  182. } else {
  183. AI_DEBUG_INVALIDATE_PTR(this->mBuffer);
  184. if (mGeneratedMesh != nullptr) {
  185. delete (mGeneratedMesh);
  186. mGeneratedMesh = nullptr;
  187. }
  188. streamedBuffer.close();
  189. throw DeadlyImportError("Invalid .ply file: Missing format specification");
  190. }
  191. //free the file buffer
  192. streamedBuffer.close();
  193. if (mGeneratedMesh == nullptr) {
  194. throw DeadlyImportError("Invalid .ply file: Unable to extract mesh data ");
  195. }
  196. // if no face list is existing we assume that the vertex
  197. // list is containing a list of points
  198. bool pointsOnly = mGeneratedMesh->mFaces == nullptr ? true : false;
  199. if (pointsOnly) {
  200. mGeneratedMesh->mPrimitiveTypes = aiPrimitiveType::aiPrimitiveType_POINT;
  201. }
  202. // now load a list of all materials
  203. std::vector<aiMaterial *> avMaterials;
  204. std::string defaultTexture;
  205. LoadMaterial(&avMaterials, defaultTexture, pointsOnly);
  206. // now generate the output scene object. Fill the material list
  207. pScene->mNumMaterials = (unsigned int)avMaterials.size();
  208. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  209. for (unsigned int i = 0; i < pScene->mNumMaterials; ++i) {
  210. pScene->mMaterials[i] = avMaterials[i];
  211. }
  212. // fill the mesh list
  213. pScene->mNumMeshes = 1;
  214. pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
  215. pScene->mMeshes[0] = mGeneratedMesh;
  216. mGeneratedMesh = nullptr;
  217. // generate a simple node structure
  218. pScene->mRootNode = new aiNode();
  219. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  220. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  221. for (unsigned int i = 0; i < pScene->mRootNode->mNumMeshes; ++i) {
  222. pScene->mRootNode->mMeshes[i] = i;
  223. }
  224. }
  225. void PLYImporter::LoadVertex(const PLY::Element *pcElement, const PLY::ElementInstance *instElement, unsigned int pos) {
  226. ai_assert(nullptr != pcElement);
  227. ai_assert(nullptr != instElement);
  228. ai_uint aiPositions[3] = { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF };
  229. PLY::EDataType aiTypes[3] = { EDT_Char, EDT_Char, EDT_Char };
  230. ai_uint aiNormal[3] = { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF };
  231. PLY::EDataType aiNormalTypes[3] = { EDT_Char, EDT_Char, EDT_Char };
  232. unsigned int aiColors[4] = { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF };
  233. PLY::EDataType aiColorsTypes[4] = { EDT_Char, EDT_Char, EDT_Char, EDT_Char };
  234. unsigned int aiTexcoord[2] = { 0xFFFFFFFF, 0xFFFFFFFF };
  235. PLY::EDataType aiTexcoordTypes[2] = { EDT_Char, EDT_Char };
  236. // now check whether which normal components are available
  237. unsigned int _a(0), cnt(0);
  238. for (std::vector<PLY::Property>::const_iterator a = pcElement->alProperties.begin();
  239. a != pcElement->alProperties.end(); ++a, ++_a) {
  240. if ((*a).bIsList) {
  241. continue;
  242. }
  243. // Positions
  244. if (PLY::EST_XCoord == (*a).Semantic) {
  245. ++cnt;
  246. aiPositions[0] = _a;
  247. aiTypes[0] = (*a).eType;
  248. } else if (PLY::EST_YCoord == (*a).Semantic) {
  249. ++cnt;
  250. aiPositions[1] = _a;
  251. aiTypes[1] = (*a).eType;
  252. } else if (PLY::EST_ZCoord == (*a).Semantic) {
  253. ++cnt;
  254. aiPositions[2] = _a;
  255. aiTypes[2] = (*a).eType;
  256. } else if (PLY::EST_XNormal == (*a).Semantic) {
  257. // Normals
  258. ++cnt;
  259. aiNormal[0] = _a;
  260. aiNormalTypes[0] = (*a).eType;
  261. } else if (PLY::EST_YNormal == (*a).Semantic) {
  262. ++cnt;
  263. aiNormal[1] = _a;
  264. aiNormalTypes[1] = (*a).eType;
  265. } else if (PLY::EST_ZNormal == (*a).Semantic) {
  266. ++cnt;
  267. aiNormal[2] = _a;
  268. aiNormalTypes[2] = (*a).eType;
  269. } else if (PLY::EST_Red == (*a).Semantic) {
  270. // Colors
  271. ++cnt;
  272. aiColors[0] = _a;
  273. aiColorsTypes[0] = (*a).eType;
  274. } else if (PLY::EST_Green == (*a).Semantic) {
  275. ++cnt;
  276. aiColors[1] = _a;
  277. aiColorsTypes[1] = (*a).eType;
  278. } else if (PLY::EST_Blue == (*a).Semantic) {
  279. ++cnt;
  280. aiColors[2] = _a;
  281. aiColorsTypes[2] = (*a).eType;
  282. } else if (PLY::EST_Alpha == (*a).Semantic) {
  283. ++cnt;
  284. aiColors[3] = _a;
  285. aiColorsTypes[3] = (*a).eType;
  286. } else if (PLY::EST_UTextureCoord == (*a).Semantic) {
  287. // Texture coordinates
  288. ++cnt;
  289. aiTexcoord[0] = _a;
  290. aiTexcoordTypes[0] = (*a).eType;
  291. } else if (PLY::EST_VTextureCoord == (*a).Semantic) {
  292. ++cnt;
  293. aiTexcoord[1] = _a;
  294. aiTexcoordTypes[1] = (*a).eType;
  295. }
  296. }
  297. // check whether we have a valid source for the vertex data
  298. if (0 != cnt) {
  299. // Position
  300. aiVector3D vOut;
  301. if (0xFFFFFFFF != aiPositions[0]) {
  302. vOut.x = PLY::PropertyInstance::ConvertTo<ai_real>(
  303. GetProperty(instElement->alProperties, aiPositions[0]).avList.front(), aiTypes[0]);
  304. }
  305. if (0xFFFFFFFF != aiPositions[1]) {
  306. vOut.y = PLY::PropertyInstance::ConvertTo<ai_real>(
  307. GetProperty(instElement->alProperties, aiPositions[1]).avList.front(), aiTypes[1]);
  308. }
  309. if (0xFFFFFFFF != aiPositions[2]) {
  310. vOut.z = PLY::PropertyInstance::ConvertTo<ai_real>(
  311. GetProperty(instElement->alProperties, aiPositions[2]).avList.front(), aiTypes[2]);
  312. }
  313. // Normals
  314. aiVector3D nOut;
  315. bool haveNormal = false;
  316. if (0xFFFFFFFF != aiNormal[0]) {
  317. nOut.x = PLY::PropertyInstance::ConvertTo<ai_real>(
  318. GetProperty(instElement->alProperties, aiNormal[0]).avList.front(), aiNormalTypes[0]);
  319. haveNormal = true;
  320. }
  321. if (0xFFFFFFFF != aiNormal[1]) {
  322. nOut.y = PLY::PropertyInstance::ConvertTo<ai_real>(
  323. GetProperty(instElement->alProperties, aiNormal[1]).avList.front(), aiNormalTypes[1]);
  324. haveNormal = true;
  325. }
  326. if (0xFFFFFFFF != aiNormal[2]) {
  327. nOut.z = PLY::PropertyInstance::ConvertTo<ai_real>(
  328. GetProperty(instElement->alProperties, aiNormal[2]).avList.front(), aiNormalTypes[2]);
  329. haveNormal = true;
  330. }
  331. //Colors
  332. aiColor4D cOut;
  333. bool haveColor = false;
  334. if (0xFFFFFFFF != aiColors[0]) {
  335. cOut.r = NormalizeColorValue(GetProperty(instElement->alProperties,
  336. aiColors[0])
  337. .avList.front(),
  338. aiColorsTypes[0]);
  339. haveColor = true;
  340. }
  341. if (0xFFFFFFFF != aiColors[1]) {
  342. cOut.g = NormalizeColorValue(GetProperty(instElement->alProperties,
  343. aiColors[1])
  344. .avList.front(),
  345. aiColorsTypes[1]);
  346. haveColor = true;
  347. }
  348. if (0xFFFFFFFF != aiColors[2]) {
  349. cOut.b = NormalizeColorValue(GetProperty(instElement->alProperties,
  350. aiColors[2])
  351. .avList.front(),
  352. aiColorsTypes[2]);
  353. haveColor = true;
  354. }
  355. // assume 1.0 for the alpha channel if it is not set
  356. if (0xFFFFFFFF == aiColors[3]) {
  357. cOut.a = 1.0;
  358. } else {
  359. cOut.a = NormalizeColorValue(GetProperty(instElement->alProperties,
  360. aiColors[3])
  361. .avList.front(),
  362. aiColorsTypes[3]);
  363. haveColor = true;
  364. }
  365. //Texture coordinates
  366. aiVector3D tOut;
  367. tOut.z = 0;
  368. bool haveTextureCoords = false;
  369. if (0xFFFFFFFF != aiTexcoord[0]) {
  370. tOut.x = PLY::PropertyInstance::ConvertTo<ai_real>(
  371. GetProperty(instElement->alProperties, aiTexcoord[0]).avList.front(), aiTexcoordTypes[0]);
  372. haveTextureCoords = true;
  373. }
  374. if (0xFFFFFFFF != aiTexcoord[1]) {
  375. tOut.y = PLY::PropertyInstance::ConvertTo<ai_real>(
  376. GetProperty(instElement->alProperties, aiTexcoord[1]).avList.front(), aiTexcoordTypes[1]);
  377. haveTextureCoords = true;
  378. }
  379. //create aiMesh if needed
  380. if (nullptr == mGeneratedMesh) {
  381. mGeneratedMesh = new aiMesh();
  382. mGeneratedMesh->mMaterialIndex = 0;
  383. }
  384. if (nullptr == mGeneratedMesh->mVertices) {
  385. mGeneratedMesh->mNumVertices = pcElement->NumOccur;
  386. mGeneratedMesh->mVertices = new aiVector3D[mGeneratedMesh->mNumVertices];
  387. }
  388. mGeneratedMesh->mVertices[pos] = vOut;
  389. if (haveNormal) {
  390. if (nullptr == mGeneratedMesh->mNormals)
  391. mGeneratedMesh->mNormals = new aiVector3D[mGeneratedMesh->mNumVertices];
  392. mGeneratedMesh->mNormals[pos] = nOut;
  393. }
  394. if (haveColor) {
  395. if (nullptr == mGeneratedMesh->mColors[0])
  396. mGeneratedMesh->mColors[0] = new aiColor4D[mGeneratedMesh->mNumVertices];
  397. mGeneratedMesh->mColors[0][pos] = cOut;
  398. }
  399. if (haveTextureCoords) {
  400. if (nullptr == mGeneratedMesh->mTextureCoords[0]) {
  401. mGeneratedMesh->mNumUVComponents[0] = 2;
  402. mGeneratedMesh->mTextureCoords[0] = new aiVector3D[mGeneratedMesh->mNumVertices];
  403. }
  404. mGeneratedMesh->mTextureCoords[0][pos] = tOut;
  405. }
  406. }
  407. }
  408. // ------------------------------------------------------------------------------------------------
  409. // Convert a color component to [0...1]
  410. ai_real PLYImporter::NormalizeColorValue(PLY::PropertyInstance::ValueUnion val, PLY::EDataType eType) {
  411. switch (eType) {
  412. case EDT_Float:
  413. return val.fFloat;
  414. case EDT_Double:
  415. return (ai_real)val.fDouble;
  416. case EDT_UChar:
  417. return (ai_real)val.iUInt / (ai_real)0xFF;
  418. case EDT_Char:
  419. return (ai_real)(val.iInt + (0xFF / 2)) / (ai_real)0xFF;
  420. case EDT_UShort:
  421. return (ai_real)val.iUInt / (ai_real)0xFFFF;
  422. case EDT_Short:
  423. return (ai_real)(val.iInt + (0xFFFF / 2)) / (ai_real)0xFFFF;
  424. case EDT_UInt:
  425. return (ai_real)val.iUInt / (ai_real)0xFFFF;
  426. case EDT_Int:
  427. return ((ai_real)val.iInt / (ai_real)0xFF) + 0.5f;
  428. default:
  429. break;
  430. }
  431. return 0.0f;
  432. }
  433. // ------------------------------------------------------------------------------------------------
  434. // Try to extract proper faces from the PLY DOM
  435. void PLYImporter::LoadFace(const PLY::Element *pcElement, const PLY::ElementInstance *instElement,
  436. unsigned int pos) {
  437. ai_assert(nullptr != pcElement);
  438. ai_assert(nullptr != instElement);
  439. if (mGeneratedMesh == nullptr) {
  440. throw DeadlyImportError("Invalid .ply file: Vertices should be declared before faces");
  441. }
  442. bool bOne = false;
  443. // index of the vertex index list
  444. unsigned int iProperty = 0xFFFFFFFF;
  445. PLY::EDataType eType = EDT_Char;
  446. bool bIsTriStrip = false;
  447. // index of the material index property
  448. //unsigned int iMaterialIndex = 0xFFFFFFFF;
  449. //PLY::EDataType eType2 = EDT_Char;
  450. // texture coordinates
  451. unsigned int iTextureCoord = 0xFFFFFFFF;
  452. PLY::EDataType eType3 = EDT_Char;
  453. // face = unique number of vertex indices
  454. if (PLY::EEST_Face == pcElement->eSemantic) {
  455. unsigned int _a = 0;
  456. for (std::vector<PLY::Property>::const_iterator a = pcElement->alProperties.begin();
  457. a != pcElement->alProperties.end(); ++a, ++_a) {
  458. if (PLY::EST_VertexIndex == (*a).Semantic) {
  459. // must be a dynamic list!
  460. if (!(*a).bIsList) {
  461. continue;
  462. }
  463. iProperty = _a;
  464. bOne = true;
  465. eType = (*a).eType;
  466. } else if (PLY::EST_TextureCoordinates == (*a).Semantic) {
  467. // must be a dynamic list!
  468. if (!(*a).bIsList) {
  469. continue;
  470. }
  471. iTextureCoord = _a;
  472. bOne = true;
  473. eType3 = (*a).eType;
  474. }
  475. }
  476. }
  477. // triangle strip
  478. // TODO: triangle strip and material index support???
  479. else if (PLY::EEST_TriStrip == pcElement->eSemantic) {
  480. unsigned int _a = 0;
  481. for (std::vector<PLY::Property>::const_iterator a = pcElement->alProperties.begin();
  482. a != pcElement->alProperties.end(); ++a, ++_a) {
  483. // must be a dynamic list!
  484. if (!(*a).bIsList) {
  485. continue;
  486. }
  487. iProperty = _a;
  488. bOne = true;
  489. bIsTriStrip = true;
  490. eType = (*a).eType;
  491. break;
  492. }
  493. }
  494. // check whether we have at least one per-face information set
  495. if (bOne) {
  496. if (mGeneratedMesh->mFaces == nullptr) {
  497. mGeneratedMesh->mNumFaces = pcElement->NumOccur;
  498. mGeneratedMesh->mFaces = new aiFace[mGeneratedMesh->mNumFaces];
  499. }
  500. if (!bIsTriStrip) {
  501. // parse the list of vertex indices
  502. if (0xFFFFFFFF != iProperty) {
  503. const unsigned int iNum = (unsigned int)GetProperty(instElement->alProperties, iProperty).avList.size();
  504. mGeneratedMesh->mFaces[pos].mNumIndices = iNum;
  505. mGeneratedMesh->mFaces[pos].mIndices = new unsigned int[iNum];
  506. std::vector<PLY::PropertyInstance::ValueUnion>::const_iterator p =
  507. GetProperty(instElement->alProperties, iProperty).avList.begin();
  508. for (unsigned int a = 0; a < iNum; ++a, ++p) {
  509. mGeneratedMesh->mFaces[pos].mIndices[a] = PLY::PropertyInstance::ConvertTo<unsigned int>(*p, eType);
  510. }
  511. }
  512. // parse the material index
  513. // cannot be handled without processing the whole file first
  514. /*if (0xFFFFFFFF != iMaterialIndex)
  515. {
  516. mGeneratedMesh->mFaces[pos]. = PLY::PropertyInstance::ConvertTo<unsigned int>(
  517. GetProperty(instElement->alProperties, iMaterialIndex).avList.front(), eType2);
  518. }*/
  519. if (0xFFFFFFFF != iTextureCoord) {
  520. const unsigned int iNum = (unsigned int)GetProperty(instElement->alProperties, iTextureCoord).avList.size();
  521. //should be 6 coords
  522. std::vector<PLY::PropertyInstance::ValueUnion>::const_iterator p =
  523. GetProperty(instElement->alProperties, iTextureCoord).avList.begin();
  524. if ((iNum / 3) == 2) // X Y coord
  525. {
  526. for (unsigned int a = 0; a < iNum; ++a, ++p) {
  527. unsigned int vindex = mGeneratedMesh->mFaces[pos].mIndices[a / 2];
  528. if (vindex < mGeneratedMesh->mNumVertices) {
  529. if (mGeneratedMesh->mTextureCoords[0] == nullptr) {
  530. mGeneratedMesh->mNumUVComponents[0] = 2;
  531. mGeneratedMesh->mTextureCoords[0] = new aiVector3D[mGeneratedMesh->mNumVertices];
  532. }
  533. if (a % 2 == 0) {
  534. mGeneratedMesh->mTextureCoords[0][vindex].x = PLY::PropertyInstance::ConvertTo<ai_real>(*p, eType3);
  535. } else {
  536. mGeneratedMesh->mTextureCoords[0][vindex].y = PLY::PropertyInstance::ConvertTo<ai_real>(*p, eType3);
  537. }
  538. mGeneratedMesh->mTextureCoords[0][vindex].z = 0;
  539. }
  540. }
  541. }
  542. }
  543. } else { // triangle strips
  544. // normally we have only one triangle strip instance where
  545. // a value of -1 indicates a restart of the strip
  546. bool flip = false;
  547. const std::vector<PLY::PropertyInstance::ValueUnion> &quak = GetProperty(instElement->alProperties, iProperty).avList;
  548. //pvOut->reserve(pvOut->size() + quak.size() + (quak.size()>>2u)); //Limits memory consumption
  549. int aiTable[2] = { -1, -1 };
  550. for (std::vector<PLY::PropertyInstance::ValueUnion>::const_iterator a = quak.begin(); a != quak.end(); ++a) {
  551. const int p = PLY::PropertyInstance::ConvertTo<int>(*a, eType);
  552. if (-1 == p) {
  553. // restart the strip ...
  554. aiTable[0] = aiTable[1] = -1;
  555. flip = false;
  556. continue;
  557. }
  558. if (-1 == aiTable[0]) {
  559. aiTable[0] = p;
  560. continue;
  561. }
  562. if (-1 == aiTable[1]) {
  563. aiTable[1] = p;
  564. continue;
  565. }
  566. if (mGeneratedMesh->mFaces == nullptr) {
  567. mGeneratedMesh->mNumFaces = pcElement->NumOccur;
  568. mGeneratedMesh->mFaces = new aiFace[mGeneratedMesh->mNumFaces];
  569. }
  570. mGeneratedMesh->mFaces[pos].mNumIndices = 3;
  571. mGeneratedMesh->mFaces[pos].mIndices = new unsigned int[3];
  572. mGeneratedMesh->mFaces[pos].mIndices[0] = aiTable[0];
  573. mGeneratedMesh->mFaces[pos].mIndices[1] = aiTable[1];
  574. mGeneratedMesh->mFaces[pos].mIndices[2] = p;
  575. // every second pass swap the indices.
  576. flip = !flip;
  577. if (flip) {
  578. std::swap(mGeneratedMesh->mFaces[pos].mIndices[0], mGeneratedMesh->mFaces[pos].mIndices[1]);
  579. }
  580. aiTable[0] = aiTable[1];
  581. aiTable[1] = p;
  582. }
  583. }
  584. }
  585. }
  586. // ------------------------------------------------------------------------------------------------
  587. // Get a RGBA color in [0...1] range
  588. void PLYImporter::GetMaterialColor(const std::vector<PLY::PropertyInstance> &avList,
  589. unsigned int aiPositions[4],
  590. PLY::EDataType aiTypes[4],
  591. aiColor4D *clrOut) {
  592. ai_assert(NULL != clrOut);
  593. if (0xFFFFFFFF == aiPositions[0])
  594. clrOut->r = 0.0f;
  595. else {
  596. clrOut->r = NormalizeColorValue(GetProperty(avList,
  597. aiPositions[0])
  598. .avList.front(),
  599. aiTypes[0]);
  600. }
  601. if (0xFFFFFFFF == aiPositions[1])
  602. clrOut->g = 0.0f;
  603. else {
  604. clrOut->g = NormalizeColorValue(GetProperty(avList,
  605. aiPositions[1])
  606. .avList.front(),
  607. aiTypes[1]);
  608. }
  609. if (0xFFFFFFFF == aiPositions[2])
  610. clrOut->b = 0.0f;
  611. else {
  612. clrOut->b = NormalizeColorValue(GetProperty(avList,
  613. aiPositions[2])
  614. .avList.front(),
  615. aiTypes[2]);
  616. }
  617. // assume 1.0 for the alpha channel ifit is not set
  618. if (0xFFFFFFFF == aiPositions[3])
  619. clrOut->a = 1.0f;
  620. else {
  621. clrOut->a = NormalizeColorValue(GetProperty(avList,
  622. aiPositions[3])
  623. .avList.front(),
  624. aiTypes[3]);
  625. }
  626. }
  627. // ------------------------------------------------------------------------------------------------
  628. // Extract a material from the PLY DOM
  629. void PLYImporter::LoadMaterial(std::vector<aiMaterial *> *pvOut, std::string &defaultTexture, const bool pointsOnly) {
  630. ai_assert(NULL != pvOut);
  631. // diffuse[4], specular[4], ambient[4]
  632. // rgba order
  633. unsigned int aaiPositions[3][4] = {
  634. { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF },
  635. { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF },
  636. { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF },
  637. };
  638. PLY::EDataType aaiTypes[3][4] = {
  639. { EDT_Char, EDT_Char, EDT_Char, EDT_Char },
  640. { EDT_Char, EDT_Char, EDT_Char, EDT_Char },
  641. { EDT_Char, EDT_Char, EDT_Char, EDT_Char }
  642. };
  643. PLY::ElementInstanceList *pcList = NULL;
  644. unsigned int iPhong = 0xFFFFFFFF;
  645. PLY::EDataType ePhong = EDT_Char;
  646. unsigned int iOpacity = 0xFFFFFFFF;
  647. PLY::EDataType eOpacity = EDT_Char;
  648. // search in the DOM for a vertex entry
  649. unsigned int _i = 0;
  650. for (std::vector<PLY::Element>::const_iterator i = this->pcDOM->alElements.begin();
  651. i != this->pcDOM->alElements.end(); ++i, ++_i) {
  652. if (PLY::EEST_Material == (*i).eSemantic) {
  653. pcList = &this->pcDOM->alElementData[_i];
  654. // now check whether which coordinate sets are available
  655. unsigned int _a = 0;
  656. for (std::vector<PLY::Property>::const_iterator
  657. a = (*i).alProperties.begin();
  658. a != (*i).alProperties.end(); ++a, ++_a) {
  659. if ((*a).bIsList) continue;
  660. // pohng specularity -----------------------------------
  661. if (PLY::EST_PhongPower == (*a).Semantic) {
  662. iPhong = _a;
  663. ePhong = (*a).eType;
  664. }
  665. // general opacity -----------------------------------
  666. if (PLY::EST_Opacity == (*a).Semantic) {
  667. iOpacity = _a;
  668. eOpacity = (*a).eType;
  669. }
  670. // diffuse color channels -----------------------------------
  671. if (PLY::EST_DiffuseRed == (*a).Semantic) {
  672. aaiPositions[0][0] = _a;
  673. aaiTypes[0][0] = (*a).eType;
  674. } else if (PLY::EST_DiffuseGreen == (*a).Semantic) {
  675. aaiPositions[0][1] = _a;
  676. aaiTypes[0][1] = (*a).eType;
  677. } else if (PLY::EST_DiffuseBlue == (*a).Semantic) {
  678. aaiPositions[0][2] = _a;
  679. aaiTypes[0][2] = (*a).eType;
  680. } else if (PLY::EST_DiffuseAlpha == (*a).Semantic) {
  681. aaiPositions[0][3] = _a;
  682. aaiTypes[0][3] = (*a).eType;
  683. }
  684. // specular color channels -----------------------------------
  685. else if (PLY::EST_SpecularRed == (*a).Semantic) {
  686. aaiPositions[1][0] = _a;
  687. aaiTypes[1][0] = (*a).eType;
  688. } else if (PLY::EST_SpecularGreen == (*a).Semantic) {
  689. aaiPositions[1][1] = _a;
  690. aaiTypes[1][1] = (*a).eType;
  691. } else if (PLY::EST_SpecularBlue == (*a).Semantic) {
  692. aaiPositions[1][2] = _a;
  693. aaiTypes[1][2] = (*a).eType;
  694. } else if (PLY::EST_SpecularAlpha == (*a).Semantic) {
  695. aaiPositions[1][3] = _a;
  696. aaiTypes[1][3] = (*a).eType;
  697. }
  698. // ambient color channels -----------------------------------
  699. else if (PLY::EST_AmbientRed == (*a).Semantic) {
  700. aaiPositions[2][0] = _a;
  701. aaiTypes[2][0] = (*a).eType;
  702. } else if (PLY::EST_AmbientGreen == (*a).Semantic) {
  703. aaiPositions[2][1] = _a;
  704. aaiTypes[2][1] = (*a).eType;
  705. } else if (PLY::EST_AmbientBlue == (*a).Semantic) {
  706. aaiPositions[2][2] = _a;
  707. aaiTypes[2][2] = (*a).eType;
  708. } else if (PLY::EST_AmbientAlpha == (*a).Semantic) {
  709. aaiPositions[2][3] = _a;
  710. aaiTypes[2][3] = (*a).eType;
  711. }
  712. }
  713. break;
  714. } else if (PLY::EEST_TextureFile == (*i).eSemantic) {
  715. defaultTexture = (*i).szName;
  716. }
  717. }
  718. // check whether we have a valid source for the material data
  719. if (NULL != pcList) {
  720. for (std::vector<ElementInstance>::const_iterator i = pcList->alInstances.begin(); i != pcList->alInstances.end(); ++i) {
  721. aiColor4D clrOut;
  722. aiMaterial *pcHelper = new aiMaterial();
  723. // build the diffuse material color
  724. GetMaterialColor((*i).alProperties, aaiPositions[0], aaiTypes[0], &clrOut);
  725. pcHelper->AddProperty<aiColor4D>(&clrOut, 1, AI_MATKEY_COLOR_DIFFUSE);
  726. // build the specular material color
  727. GetMaterialColor((*i).alProperties, aaiPositions[1], aaiTypes[1], &clrOut);
  728. pcHelper->AddProperty<aiColor4D>(&clrOut, 1, AI_MATKEY_COLOR_SPECULAR);
  729. // build the ambient material color
  730. GetMaterialColor((*i).alProperties, aaiPositions[2], aaiTypes[2], &clrOut);
  731. pcHelper->AddProperty<aiColor4D>(&clrOut, 1, AI_MATKEY_COLOR_AMBIENT);
  732. // handle phong power and shading mode
  733. int iMode = (int)aiShadingMode_Gouraud;
  734. if (0xFFFFFFFF != iPhong) {
  735. ai_real fSpec = PLY::PropertyInstance::ConvertTo<ai_real>(GetProperty((*i).alProperties, iPhong).avList.front(), ePhong);
  736. // if shininess is 0 (and the pow() calculation would therefore always
  737. // become 1, not depending on the angle), use gouraud lighting
  738. if (fSpec) {
  739. // scale this with 15 ... hopefully this is correct
  740. fSpec *= 15;
  741. pcHelper->AddProperty<ai_real>(&fSpec, 1, AI_MATKEY_SHININESS);
  742. iMode = (int)aiShadingMode_Phong;
  743. }
  744. }
  745. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  746. // handle opacity
  747. if (0xFFFFFFFF != iOpacity) {
  748. ai_real fOpacity = PLY::PropertyInstance::ConvertTo<ai_real>(GetProperty((*i).alProperties, iPhong).avList.front(), eOpacity);
  749. pcHelper->AddProperty<ai_real>(&fOpacity, 1, AI_MATKEY_OPACITY);
  750. }
  751. // The face order is absolutely undefined for PLY, so we have to
  752. // use two-sided rendering to be sure it's ok.
  753. const int two_sided = 1;
  754. pcHelper->AddProperty(&two_sided, 1, AI_MATKEY_TWOSIDED);
  755. //default texture
  756. if (!defaultTexture.empty()) {
  757. const aiString name(defaultTexture.c_str());
  758. pcHelper->AddProperty(&name, _AI_MATKEY_TEXTURE_BASE, aiTextureType_DIFFUSE, 0);
  759. }
  760. if (!pointsOnly) {
  761. pcHelper->AddProperty(&two_sided, 1, AI_MATKEY_TWOSIDED);
  762. }
  763. //set to wireframe, so when using this material info we can switch to points rendering
  764. if (pointsOnly) {
  765. const int wireframe = 1;
  766. pcHelper->AddProperty(&wireframe, 1, AI_MATKEY_ENABLE_WIREFRAME);
  767. }
  768. // add the newly created material instance to the list
  769. pvOut->push_back(pcHelper);
  770. }
  771. } else {
  772. // generate a default material
  773. aiMaterial *pcHelper = new aiMaterial();
  774. // fill in a default material
  775. int iMode = (int)aiShadingMode_Gouraud;
  776. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  777. //generate white material most 3D engine just multiply ambient / diffuse color with actual ambient / light color
  778. aiColor3D clr;
  779. clr.b = clr.g = clr.r = 1.0f;
  780. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_DIFFUSE);
  781. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_SPECULAR);
  782. clr.b = clr.g = clr.r = 1.0f;
  783. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_AMBIENT);
  784. // The face order is absolutely undefined for PLY, so we have to
  785. // use two-sided rendering to be sure it's ok.
  786. if (!pointsOnly) {
  787. const int two_sided = 1;
  788. pcHelper->AddProperty(&two_sided, 1, AI_MATKEY_TWOSIDED);
  789. }
  790. //default texture
  791. if (!defaultTexture.empty()) {
  792. const aiString name(defaultTexture.c_str());
  793. pcHelper->AddProperty(&name, _AI_MATKEY_TEXTURE_BASE, aiTextureType_DIFFUSE, 0);
  794. }
  795. //set to wireframe, so when using this material info we can switch to points rendering
  796. if (pointsOnly) {
  797. const int wireframe = 1;
  798. pcHelper->AddProperty(&wireframe, 1, AI_MATKEY_ENABLE_WIREFRAME);
  799. }
  800. pvOut->push_back(pcHelper);
  801. }
  802. }
  803. #endif // !! ASSIMP_BUILD_NO_PLY_IMPORTER