ACLoader.cpp 33 KB

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