ACLoader.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2019, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Implementation of the AC3D importer class */
  35. #ifndef ASSIMP_BUILD_NO_AC_IMPORTER
  36. // internal headers
  37. #include "ACLoader.h"
  38. #include <assimp/ParsingUtils.h>
  39. #include <assimp/fast_atof.h>
  40. #include <assimp/Subdivision.h>
  41. #include "Importer.h"
  42. #include <assimp/BaseImporter.h>
  43. #include <assimp/Importer.hpp>
  44. #include <assimp/light.h>
  45. #include <assimp/DefaultLogger.hpp>
  46. #include <assimp/material.h>
  47. #include <assimp/scene.h>
  48. #include <assimp/config.h>
  49. #include <assimp/IOSystem.hpp>
  50. #include <assimp/importerdesc.h>
  51. #include <memory>
  52. using namespace Assimp;
  53. static const aiImporterDesc desc = {
  54. "AC3D Importer",
  55. "",
  56. "",
  57. "",
  58. aiImporterFlags_SupportTextFlavour,
  59. 0,
  60. 0,
  61. 0,
  62. 0,
  63. "ac acc ac3d"
  64. };
  65. // ------------------------------------------------------------------------------------------------
  66. // skip to the next token
  67. #define AI_AC_SKIP_TO_NEXT_TOKEN() \
  68. if (!SkipSpaces(&buffer)) \
  69. { \
  70. ASSIMP_LOG_ERROR("AC3D: Unexpected EOF/EOL"); \
  71. continue; \
  72. }
  73. // ------------------------------------------------------------------------------------------------
  74. // read a string (may be enclosed in double quotation marks). buffer must point to "
  75. #define AI_AC_GET_STRING(out) \
  76. if (*buffer == '\0') { \
  77. throw DeadlyImportError("AC3D: Unexpected EOF in string"); \
  78. } \
  79. ++buffer; \
  80. const char* sz = buffer; \
  81. while ('\"' != *buffer) \
  82. { \
  83. if (IsLineEnd( *buffer )) \
  84. { \
  85. ASSIMP_LOG_ERROR("AC3D: Unexpected EOF/EOL in string"); \
  86. out = "ERROR"; \
  87. break; \
  88. } \
  89. ++buffer; \
  90. } \
  91. if (IsLineEnd( *buffer ))continue; \
  92. out = std::string(sz,(unsigned int)(buffer-sz)); \
  93. ++buffer;
  94. // ------------------------------------------------------------------------------------------------
  95. // read 1 to n floats prefixed with an optional predefined identifier
  96. #define AI_AC_CHECKED_LOAD_FLOAT_ARRAY(name,name_length,num,out) \
  97. AI_AC_SKIP_TO_NEXT_TOKEN(); \
  98. if (name_length) \
  99. { \
  100. if (strncmp(buffer,name,name_length) || !IsSpace(buffer[name_length])) \
  101. { \
  102. ASSIMP_LOG_ERROR("AC3D: Unexpexted token. " name " was expected."); \
  103. continue; \
  104. } \
  105. buffer += name_length+1; \
  106. } \
  107. for (unsigned int i = 0; i < num;++i) \
  108. { \
  109. AI_AC_SKIP_TO_NEXT_TOKEN(); \
  110. buffer = fast_atoreal_move<float>(buffer,((float*)out)[i]); \
  111. }
  112. // ------------------------------------------------------------------------------------------------
  113. // Constructor to be privately used by Importer
  114. AC3DImporter::AC3DImporter()
  115. : buffer(),
  116. configSplitBFCull(),
  117. configEvalSubdivision(),
  118. mNumMeshes(),
  119. mLights(),
  120. lights(),
  121. groups(),
  122. polys(),
  123. worlds()
  124. {
  125. // nothing to be done here
  126. }
  127. // ------------------------------------------------------------------------------------------------
  128. // Destructor, private as well
  129. AC3DImporter::~AC3DImporter()
  130. {
  131. // nothing to be done here
  132. }
  133. // ------------------------------------------------------------------------------------------------
  134. // Returns whether the class can handle the format of the given file.
  135. bool AC3DImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  136. {
  137. std::string extension = GetExtension(pFile);
  138. // fixme: are acc and ac3d *really* used? Some sources say they are
  139. if(extension == "ac" || extension == "ac3d" || extension == "acc") {
  140. return true;
  141. }
  142. if (!extension.length() || checkSig) {
  143. uint32_t token = AI_MAKE_MAGIC("AC3D");
  144. return CheckMagicToken(pIOHandler,pFile,&token,1,0);
  145. }
  146. return false;
  147. }
  148. // ------------------------------------------------------------------------------------------------
  149. // Loader meta information
  150. const aiImporterDesc* AC3DImporter::GetInfo () const
  151. {
  152. return &desc;
  153. }
  154. // ------------------------------------------------------------------------------------------------
  155. // Get a pointer to the next line from the file
  156. bool AC3DImporter::GetNextLine( )
  157. {
  158. SkipLine(&buffer);
  159. return SkipSpaces(&buffer);
  160. }
  161. // ------------------------------------------------------------------------------------------------
  162. // Parse an object section in an AC file
  163. void AC3DImporter::LoadObjectSection(std::vector<Object>& objects)
  164. {
  165. if (!TokenMatch(buffer,"OBJECT",6))
  166. return;
  167. SkipSpaces(&buffer);
  168. ++mNumMeshes;
  169. objects.push_back(Object());
  170. Object& obj = objects.back();
  171. aiLight* light = NULL;
  172. if (!ASSIMP_strincmp(buffer,"light",5))
  173. {
  174. // This is a light source. Add it to the list
  175. mLights->push_back(light = new aiLight());
  176. // Return a point light with no attenuation
  177. light->mType = aiLightSource_POINT;
  178. light->mColorDiffuse = light->mColorSpecular = aiColor3D(1.f,1.f,1.f);
  179. light->mAttenuationConstant = 1.f;
  180. // Generate a default name for both the light source and the node
  181. // FIXME - what's the right way to print a size_t? Is 'zu' universally available? stick with the safe version.
  182. light->mName.length = ::ai_snprintf(light->mName.data, MAXLEN, "ACLight_%i",static_cast<unsigned int>(mLights->size())-1);
  183. obj.name = std::string( light->mName.data );
  184. ASSIMP_LOG_DEBUG("AC3D: Light source encountered");
  185. obj.type = Object::Light;
  186. }
  187. else if (!ASSIMP_strincmp(buffer,"group",5))
  188. {
  189. obj.type = Object::Group;
  190. }
  191. else if (!ASSIMP_strincmp(buffer,"world",5))
  192. {
  193. obj.type = Object::World;
  194. }
  195. else obj.type = Object::Poly;
  196. while (GetNextLine())
  197. {
  198. if (TokenMatch(buffer,"kids",4))
  199. {
  200. SkipSpaces(&buffer);
  201. unsigned int num = strtoul10(buffer,&buffer);
  202. GetNextLine();
  203. if (num)
  204. {
  205. // load the children of this object recursively
  206. obj.children.reserve(num);
  207. for (unsigned int i = 0; i < num; ++i)
  208. LoadObjectSection(obj.children);
  209. }
  210. return;
  211. }
  212. else if (TokenMatch(buffer,"name",4))
  213. {
  214. SkipSpaces(&buffer);
  215. AI_AC_GET_STRING(obj.name);
  216. // If this is a light source, we'll also need to store
  217. // the name of the node in it.
  218. if (light)
  219. {
  220. light->mName.Set(obj.name);
  221. }
  222. }
  223. else if (TokenMatch(buffer,"texture",7))
  224. {
  225. SkipSpaces(&buffer);
  226. AI_AC_GET_STRING(obj.texture);
  227. }
  228. else if (TokenMatch(buffer,"texrep",6))
  229. {
  230. SkipSpaces(&buffer);
  231. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,2,&obj.texRepeat);
  232. if (!obj.texRepeat.x || !obj.texRepeat.y)
  233. obj.texRepeat = aiVector2D (1.f,1.f);
  234. }
  235. else if (TokenMatch(buffer,"texoff",6))
  236. {
  237. SkipSpaces(&buffer);
  238. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,2,&obj.texOffset);
  239. }
  240. else if (TokenMatch(buffer,"rot",3))
  241. {
  242. SkipSpaces(&buffer);
  243. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,9,&obj.rotation);
  244. }
  245. else if (TokenMatch(buffer,"loc",3))
  246. {
  247. SkipSpaces(&buffer);
  248. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,3,&obj.translation);
  249. }
  250. else if (TokenMatch(buffer,"subdiv",6))
  251. {
  252. SkipSpaces(&buffer);
  253. obj.subDiv = strtoul10(buffer,&buffer);
  254. }
  255. else if (TokenMatch(buffer,"crease",6))
  256. {
  257. SkipSpaces(&buffer);
  258. obj.crease = fast_atof(buffer);
  259. }
  260. else if (TokenMatch(buffer,"numvert",7))
  261. {
  262. SkipSpaces(&buffer);
  263. unsigned int t = strtoul10(buffer,&buffer);
  264. if (t >= AI_MAX_ALLOC(aiVector3D)) {
  265. throw DeadlyImportError("AC3D: Too many vertices, would run out of memory");
  266. }
  267. obj.vertices.reserve(t);
  268. for (unsigned int i = 0; i < t;++i)
  269. {
  270. if (!GetNextLine())
  271. {
  272. ASSIMP_LOG_ERROR("AC3D: Unexpected EOF: not all vertices have been parsed yet");
  273. break;
  274. }
  275. else if (!IsNumeric(*buffer))
  276. {
  277. ASSIMP_LOG_ERROR("AC3D: Unexpected token: not all vertices have been parsed yet");
  278. --buffer; // make sure the line is processed a second time
  279. break;
  280. }
  281. obj.vertices.push_back(aiVector3D());
  282. aiVector3D& v = obj.vertices.back();
  283. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,3,&v.x);
  284. }
  285. }
  286. else if (TokenMatch(buffer,"numsurf",7))
  287. {
  288. SkipSpaces(&buffer);
  289. bool Q3DWorkAround = false;
  290. const unsigned int t = strtoul10(buffer,&buffer);
  291. obj.surfaces.reserve(t);
  292. for (unsigned int i = 0; i < t;++i)
  293. {
  294. GetNextLine();
  295. if (!TokenMatch(buffer,"SURF",4))
  296. {
  297. // FIX: this can occur for some files - Quick 3D for
  298. // example writes no surf chunks
  299. if (!Q3DWorkAround)
  300. {
  301. ASSIMP_LOG_WARN("AC3D: SURF token was expected");
  302. ASSIMP_LOG_DEBUG("Continuing with Quick3D Workaround enabled");
  303. }
  304. --buffer; // make sure the line is processed a second time
  305. // break; --- see fix notes above
  306. Q3DWorkAround = true;
  307. }
  308. SkipSpaces(&buffer);
  309. obj.surfaces.push_back(Surface());
  310. Surface& surf = obj.surfaces.back();
  311. surf.flags = strtoul_cppstyle(buffer);
  312. while (1)
  313. {
  314. if(!GetNextLine())
  315. {
  316. throw DeadlyImportError("AC3D: Unexpected EOF: surface is incomplete");
  317. }
  318. if (TokenMatch(buffer,"mat",3))
  319. {
  320. SkipSpaces(&buffer);
  321. surf.mat = strtoul10(buffer);
  322. }
  323. else if (TokenMatch(buffer,"refs",4))
  324. {
  325. // --- see fix notes above
  326. if (Q3DWorkAround)
  327. {
  328. if (!surf.entries.empty())
  329. {
  330. buffer -= 6;
  331. break;
  332. }
  333. }
  334. SkipSpaces(&buffer);
  335. const unsigned int m = strtoul10(buffer);
  336. surf.entries.reserve(m);
  337. obj.numRefs += m;
  338. for (unsigned int k = 0; k < m; ++k)
  339. {
  340. if(!GetNextLine())
  341. {
  342. ASSIMP_LOG_ERROR("AC3D: Unexpected EOF: surface references are incomplete");
  343. break;
  344. }
  345. surf.entries.push_back(Surface::SurfaceEntry());
  346. Surface::SurfaceEntry& entry = surf.entries.back();
  347. entry.first = strtoul10(buffer,&buffer);
  348. SkipSpaces(&buffer);
  349. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,2,&entry.second);
  350. }
  351. }
  352. else
  353. {
  354. --buffer; // make sure the line is processed a second time
  355. break;
  356. }
  357. }
  358. }
  359. }
  360. }
  361. ASSIMP_LOG_ERROR("AC3D: Unexpected EOF: \'kids\' line was expected");
  362. }
  363. // ------------------------------------------------------------------------------------------------
  364. // Convert a material from AC3DImporter::Material to aiMaterial
  365. void AC3DImporter::ConvertMaterial(const Object& object,
  366. const Material& matSrc,
  367. aiMaterial& matDest)
  368. {
  369. aiString s;
  370. if (matSrc.name.length())
  371. {
  372. s.Set(matSrc.name);
  373. matDest.AddProperty(&s,AI_MATKEY_NAME);
  374. }
  375. if (object.texture.length())
  376. {
  377. s.Set(object.texture);
  378. matDest.AddProperty(&s,AI_MATKEY_TEXTURE_DIFFUSE(0));
  379. // UV transformation
  380. if (1.f != object.texRepeat.x || 1.f != object.texRepeat.y ||
  381. object.texOffset.x || object.texOffset.y)
  382. {
  383. aiUVTransform transform;
  384. transform.mScaling = object.texRepeat;
  385. transform.mTranslation = object.texOffset;
  386. matDest.AddProperty(&transform,1,AI_MATKEY_UVTRANSFORM_DIFFUSE(0));
  387. }
  388. }
  389. matDest.AddProperty<aiColor3D>(&matSrc.rgb,1, AI_MATKEY_COLOR_DIFFUSE);
  390. matDest.AddProperty<aiColor3D>(&matSrc.amb,1, AI_MATKEY_COLOR_AMBIENT);
  391. matDest.AddProperty<aiColor3D>(&matSrc.emis,1,AI_MATKEY_COLOR_EMISSIVE);
  392. matDest.AddProperty<aiColor3D>(&matSrc.spec,1,AI_MATKEY_COLOR_SPECULAR);
  393. int n;
  394. if (matSrc.shin)
  395. {
  396. n = aiShadingMode_Phong;
  397. matDest.AddProperty<float>(&matSrc.shin,1,AI_MATKEY_SHININESS);
  398. }
  399. else n = aiShadingMode_Gouraud;
  400. matDest.AddProperty<int>(&n,1,AI_MATKEY_SHADING_MODEL);
  401. float f = 1.f - matSrc.trans;
  402. matDest.AddProperty<float>(&f,1,AI_MATKEY_OPACITY);
  403. }
  404. // ------------------------------------------------------------------------------------------------
  405. // Converts the loaded data to the internal verbose representation
  406. aiNode* AC3DImporter::ConvertObjectSection(Object& object,
  407. std::vector<aiMesh*>& meshes,
  408. std::vector<aiMaterial*>& outMaterials,
  409. const std::vector<Material>& materials,
  410. aiNode* parent)
  411. {
  412. aiNode* node = new aiNode();
  413. node->mParent = parent;
  414. if (object.vertices.size())
  415. {
  416. if (!object.surfaces.size() || !object.numRefs)
  417. {
  418. /* " An object with 7 vertices (no surfaces, no materials defined).
  419. This is a good way of getting point data into AC3D.
  420. The Vertex->create convex-surface/object can be used on these
  421. vertices to 'wrap' a 3d shape around them "
  422. (http://www.opencity.info/html/ac3dfileformat.html)
  423. therefore: if no surfaces are defined return point data only
  424. */
  425. ASSIMP_LOG_INFO("AC3D: No surfaces defined in object definition, "
  426. "a point list is returned");
  427. meshes.push_back(new aiMesh());
  428. aiMesh* mesh = meshes.back();
  429. mesh->mNumFaces = mesh->mNumVertices = (unsigned int)object.vertices.size();
  430. aiFace* faces = mesh->mFaces = new aiFace[mesh->mNumFaces];
  431. aiVector3D* verts = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  432. for (unsigned int i = 0; i < mesh->mNumVertices;++i,++faces,++verts)
  433. {
  434. *verts = object.vertices[i];
  435. faces->mNumIndices = 1;
  436. faces->mIndices = new unsigned int[1];
  437. faces->mIndices[0] = i;
  438. }
  439. // use the primary material in this case. this should be the
  440. // default material if all objects of the file contain points
  441. // and no faces.
  442. mesh->mMaterialIndex = 0;
  443. outMaterials.push_back(new aiMaterial());
  444. ConvertMaterial(object, materials[0], *outMaterials.back());
  445. }
  446. else
  447. {
  448. // need to generate one or more meshes for this object.
  449. // find out how many different materials we have
  450. typedef std::pair< unsigned int, unsigned int > IntPair;
  451. typedef std::vector< IntPair > MatTable;
  452. MatTable needMat(materials.size(),IntPair(0,0));
  453. std::vector<Surface>::iterator it,end = object.surfaces.end();
  454. std::vector<Surface::SurfaceEntry>::iterator it2,end2;
  455. for (it = object.surfaces.begin(); it != end; ++it)
  456. {
  457. unsigned int idx = (*it).mat;
  458. if (idx >= needMat.size())
  459. {
  460. ASSIMP_LOG_ERROR("AC3D: material index is out of range");
  461. idx = 0;
  462. }
  463. if ((*it).entries.empty())
  464. {
  465. ASSIMP_LOG_WARN("AC3D: surface her zero vertex references");
  466. }
  467. // validate all vertex indices to make sure we won't crash here
  468. for (it2 = (*it).entries.begin(),
  469. end2 = (*it).entries.end(); it2 != end2; ++it2)
  470. {
  471. if ((*it2).first >= object.vertices.size())
  472. {
  473. ASSIMP_LOG_WARN("AC3D: Invalid vertex reference");
  474. (*it2).first = 0;
  475. }
  476. }
  477. if (!needMat[idx].first)++node->mNumMeshes;
  478. switch ((*it).flags & 0xf)
  479. {
  480. // closed line
  481. case 0x1:
  482. needMat[idx].first += (unsigned int)(*it).entries.size();
  483. needMat[idx].second += (unsigned int)(*it).entries.size()<<1u;
  484. break;
  485. // unclosed line
  486. case 0x2:
  487. needMat[idx].first += (unsigned int)(*it).entries.size()-1;
  488. needMat[idx].second += ((unsigned int)(*it).entries.size()-1)<<1u;
  489. break;
  490. // 0 == polygon, else unknown
  491. default:
  492. if ((*it).flags & 0xf)
  493. {
  494. ASSIMP_LOG_WARN("AC3D: The type flag of a surface is unknown");
  495. (*it).flags &= ~(0xf);
  496. }
  497. // the number of faces increments by one, the number
  498. // of vertices by surface.numref.
  499. needMat[idx].first++;
  500. needMat[idx].second += (unsigned int)(*it).entries.size();
  501. };
  502. }
  503. unsigned int* pip = node->mMeshes = new unsigned int[node->mNumMeshes];
  504. unsigned int mat = 0;
  505. const size_t oldm = meshes.size();
  506. for (MatTable::const_iterator cit = needMat.begin(), cend = needMat.end();
  507. cit != cend; ++cit, ++mat)
  508. {
  509. if (!(*cit).first)continue;
  510. // allocate a new aiMesh object
  511. *pip++ = (unsigned int)meshes.size();
  512. aiMesh* mesh = new aiMesh();
  513. meshes.push_back(mesh);
  514. mesh->mMaterialIndex = (unsigned int)outMaterials.size();
  515. outMaterials.push_back(new aiMaterial());
  516. ConvertMaterial(object, materials[mat], *outMaterials.back());
  517. // allocate storage for vertices and normals
  518. mesh->mNumFaces = (*cit).first;
  519. if (mesh->mNumFaces == 0) {
  520. throw DeadlyImportError("AC3D: No faces");
  521. } else if (mesh->mNumFaces > AI_MAX_ALLOC(aiFace)) {
  522. throw DeadlyImportError("AC3D: Too many faces, would run out of memory");
  523. }
  524. aiFace* faces = mesh->mFaces = new aiFace[mesh->mNumFaces];
  525. mesh->mNumVertices = (*cit).second;
  526. if (mesh->mNumVertices == 0) {
  527. throw DeadlyImportError("AC3D: No vertices");
  528. } else if (mesh->mNumVertices > AI_MAX_ALLOC(aiVector3D)) {
  529. throw DeadlyImportError("AC3D: Too many vertices, would run out of memory");
  530. }
  531. aiVector3D* vertices = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  532. unsigned int cur = 0;
  533. // allocate UV coordinates, but only if the texture name for the
  534. // surface is not empty
  535. aiVector3D* uv = NULL;
  536. if(object.texture.length())
  537. {
  538. uv = mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
  539. mesh->mNumUVComponents[0] = 2;
  540. }
  541. for (it = object.surfaces.begin(); it != end; ++it)
  542. {
  543. if (mat == (*it).mat)
  544. {
  545. const Surface& src = *it;
  546. // closed polygon
  547. unsigned int type = (*it).flags & 0xf;
  548. if (!type)
  549. {
  550. aiFace& face = *faces++;
  551. if((face.mNumIndices = (unsigned int)src.entries.size()))
  552. {
  553. face.mIndices = new unsigned int[face.mNumIndices];
  554. for (unsigned int i = 0; i < face.mNumIndices;++i,++vertices)
  555. {
  556. const Surface::SurfaceEntry& entry = src.entries[i];
  557. face.mIndices[i] = cur++;
  558. // copy vertex positions
  559. if (static_cast<unsigned>(vertices - mesh->mVertices) >= mesh->mNumVertices) {
  560. throw DeadlyImportError("AC3D: Invalid number of vertices");
  561. }
  562. *vertices = object.vertices[entry.first] + object.translation;
  563. // copy texture coordinates
  564. if (uv)
  565. {
  566. uv->x = entry.second.x;
  567. uv->y = entry.second.y;
  568. ++uv;
  569. }
  570. }
  571. }
  572. }
  573. else
  574. {
  575. it2 = (*it).entries.begin();
  576. // either a closed or an unclosed line
  577. unsigned int tmp = (unsigned int)(*it).entries.size();
  578. if (0x2 == type)--tmp;
  579. for (unsigned int m = 0; m < tmp;++m)
  580. {
  581. aiFace& face = *faces++;
  582. face.mNumIndices = 2;
  583. face.mIndices = new unsigned int[2];
  584. face.mIndices[0] = cur++;
  585. face.mIndices[1] = cur++;
  586. // copy vertex positions
  587. if (it2 == (*it).entries.end() ) {
  588. throw DeadlyImportError("AC3D: Bad line");
  589. }
  590. ai_assert((*it2).first < object.vertices.size());
  591. *vertices++ = object.vertices[(*it2).first];
  592. // copy texture coordinates
  593. if (uv)
  594. {
  595. uv->x = (*it2).second.x;
  596. uv->y = (*it2).second.y;
  597. ++uv;
  598. }
  599. if (0x1 == type && tmp-1 == m)
  600. {
  601. // if this is a closed line repeat its beginning now
  602. it2 = (*it).entries.begin();
  603. }
  604. else ++it2;
  605. // second point
  606. *vertices++ = object.vertices[(*it2).first];
  607. if (uv)
  608. {
  609. uv->x = (*it2).second.x;
  610. uv->y = (*it2).second.y;
  611. ++uv;
  612. }
  613. }
  614. }
  615. }
  616. }
  617. }
  618. // Now apply catmull clark subdivision if necessary. We split meshes into
  619. // materials which is not done by AC3D during smoothing, so we need to
  620. // collect all meshes using the same material group.
  621. if (object.subDiv) {
  622. if (configEvalSubdivision) {
  623. std::unique_ptr<Subdivider> div(Subdivider::Create(Subdivider::CATMULL_CLARKE));
  624. ASSIMP_LOG_INFO("AC3D: Evaluating subdivision surface: "+object.name);
  625. std::vector<aiMesh*> cpy(meshes.size()-oldm,NULL);
  626. div->Subdivide(&meshes[oldm],cpy.size(),&cpy.front(),object.subDiv,true);
  627. std::copy(cpy.begin(),cpy.end(),meshes.begin()+oldm);
  628. // previous meshes are deleted vy Subdivide().
  629. }
  630. else {
  631. ASSIMP_LOG_INFO("AC3D: Letting the subdivision surface untouched due to my configuration: "
  632. +object.name);
  633. }
  634. }
  635. }
  636. }
  637. if (object.name.length())
  638. node->mName.Set(object.name);
  639. else
  640. {
  641. // generate a name depending on the type of the node
  642. switch (object.type)
  643. {
  644. case Object::Group:
  645. node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACGroup_%i",groups++);
  646. break;
  647. case Object::Poly:
  648. node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACPoly_%i",polys++);
  649. break;
  650. case Object::Light:
  651. node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACLight_%i",lights++);
  652. break;
  653. // there shouldn't be more than one world, but we don't care
  654. case Object::World:
  655. node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACWorld_%i",worlds++);
  656. break;
  657. }
  658. }
  659. // setup the local transformation matrix of the object
  660. // compute the transformation offset to the parent node
  661. node->mTransformation = aiMatrix4x4 ( object.rotation );
  662. if (object.type == Object::Group || !object.numRefs)
  663. {
  664. node->mTransformation.a4 = object.translation.x;
  665. node->mTransformation.b4 = object.translation.y;
  666. node->mTransformation.c4 = object.translation.z;
  667. }
  668. // add children to the object
  669. if (object.children.size())
  670. {
  671. node->mNumChildren = (unsigned int)object.children.size();
  672. node->mChildren = new aiNode*[node->mNumChildren];
  673. for (unsigned int i = 0; i < node->mNumChildren;++i)
  674. {
  675. node->mChildren[i] = ConvertObjectSection(object.children[i],meshes,outMaterials,materials,node);
  676. }
  677. }
  678. return node;
  679. }
  680. // ------------------------------------------------------------------------------------------------
  681. void AC3DImporter::SetupProperties(const Importer* pImp)
  682. {
  683. configSplitBFCull = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_AC_SEPARATE_BFCULL,1) ? true : false;
  684. configEvalSubdivision = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_AC_EVAL_SUBDIVISION,1) ? true : false;
  685. }
  686. // ------------------------------------------------------------------------------------------------
  687. // Imports the given file into the given scene structure.
  688. void AC3DImporter::InternReadFile( const std::string& pFile,
  689. aiScene* pScene, IOSystem* pIOHandler)
  690. {
  691. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  692. // Check whether we can read from the file
  693. if( file.get() == NULL)
  694. throw DeadlyImportError( "Failed to open AC3D file " + pFile + ".");
  695. // allocate storage and copy the contents of the file to a memory buffer
  696. std::vector<char> mBuffer2;
  697. TextFileToBuffer(file.get(),mBuffer2);
  698. buffer = &mBuffer2[0];
  699. mNumMeshes = 0;
  700. lights = polys = worlds = groups = 0;
  701. if (::strncmp(buffer,"AC3D",4)) {
  702. throw DeadlyImportError("AC3D: No valid AC3D file, magic sequence not found");
  703. }
  704. // print the file format version to the console
  705. unsigned int version = HexDigitToDecimal( buffer[4] );
  706. char msg[3];
  707. ASSIMP_itoa10(msg,3,version);
  708. ASSIMP_LOG_INFO_F("AC3D file format version: ", msg);
  709. std::vector<Material> materials;
  710. materials.reserve(5);
  711. std::vector<Object> rootObjects;
  712. rootObjects.reserve(5);
  713. std::vector<aiLight*> lights;
  714. mLights = & lights;
  715. while (GetNextLine())
  716. {
  717. if (TokenMatch(buffer,"MATERIAL",8))
  718. {
  719. materials.push_back(Material());
  720. Material& mat = materials.back();
  721. // manually parse the material ... sscanf would use the buldin atof ...
  722. // Format: (name) rgb %f %f %f amb %f %f %f emis %f %f %f spec %f %f %f shi %d trans %f
  723. AI_AC_SKIP_TO_NEXT_TOKEN();
  724. if ('\"' == *buffer)
  725. {
  726. AI_AC_GET_STRING(mat.name);
  727. AI_AC_SKIP_TO_NEXT_TOKEN();
  728. }
  729. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("rgb",3,3,&mat.rgb);
  730. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("amb",3,3,&mat.amb);
  731. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("emis",4,3,&mat.emis);
  732. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("spec",4,3,&mat.spec);
  733. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("shi",3,1,&mat.shin);
  734. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("trans",5,1,&mat.trans);
  735. }
  736. LoadObjectSection(rootObjects);
  737. }
  738. if (rootObjects.empty() || !mNumMeshes)
  739. {
  740. throw DeadlyImportError("AC3D: No meshes have been loaded");
  741. }
  742. if (materials.empty())
  743. {
  744. ASSIMP_LOG_WARN("AC3D: No material has been found");
  745. materials.push_back(Material());
  746. }
  747. mNumMeshes += (mNumMeshes>>2u) + 1;
  748. std::vector<aiMesh*> meshes;
  749. meshes.reserve(mNumMeshes);
  750. std::vector<aiMaterial*> omaterials;
  751. materials.reserve(mNumMeshes);
  752. // generate a dummy root if there are multiple objects on the top layer
  753. Object* root;
  754. if (1 == rootObjects.size())
  755. root = &rootObjects[0];
  756. else
  757. {
  758. root = new Object();
  759. }
  760. // now convert the imported stuff to our output data structure
  761. pScene->mRootNode = ConvertObjectSection(*root,meshes,omaterials,materials);
  762. if (1 != rootObjects.size())delete root;
  763. if (!::strncmp( pScene->mRootNode->mName.data, "Node", 4))
  764. pScene->mRootNode->mName.Set("<AC3DWorld>");
  765. // copy meshes
  766. if (meshes.empty())
  767. {
  768. throw DeadlyImportError("An unknown error occurred during converting");
  769. }
  770. pScene->mNumMeshes = (unsigned int)meshes.size();
  771. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  772. ::memcpy(pScene->mMeshes,&meshes[0],pScene->mNumMeshes*sizeof(void*));
  773. // copy materials
  774. pScene->mNumMaterials = (unsigned int)omaterials.size();
  775. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
  776. ::memcpy(pScene->mMaterials,&omaterials[0],pScene->mNumMaterials*sizeof(void*));
  777. // copy lights
  778. pScene->mNumLights = (unsigned int)lights.size();
  779. if (lights.size())
  780. {
  781. pScene->mLights = new aiLight*[lights.size()];
  782. ::memcpy(pScene->mLights,&lights[0],lights.size()*sizeof(void*));
  783. }
  784. }
  785. #endif //!defined ASSIMP_BUILD_NO_AC_IMPORTER