PlyLoader.cpp 39 KB

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