PlyLoader.cpp 33 KB

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