PlyLoader.cpp 32 KB

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