PlyLoader.cpp 34 KB

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