2
0

ACLoader.cpp 36 KB

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