ACLoader.cpp 37 KB

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