PlyLoader.cpp 40 KB

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