PlyLoader.cpp 35 KB

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