BlenderLoader.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2021, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file BlenderLoader.cpp
  34. * @brief Implementation of the Blender3D importer class.
  35. */
  36. //#define ASSIMP_BUILD_NO_COMPRESSED_BLEND
  37. // Uncomment this to disable support for (gzip)compressed .BLEND files
  38. #ifndef ASSIMP_BUILD_NO_BLEND_IMPORTER
  39. #include "BlenderBMesh.h"
  40. #include "BlenderCustomData.h"
  41. #include "BlenderIntermediate.h"
  42. #include "BlenderModifier.h"
  43. #include <assimp/StringUtils.h>
  44. #include <assimp/importerdesc.h>
  45. #include <assimp/scene.h>
  46. #include <assimp/MemoryIOWrapper.h>
  47. #include <assimp/StreamReader.h>
  48. #include <assimp/StringComparison.h>
  49. #include <cctype>
  50. // zlib is needed for compressed blend files
  51. #ifndef ASSIMP_BUILD_NO_COMPRESSED_BLEND
  52. # ifdef ASSIMP_BUILD_NO_OWN_ZLIB
  53. # include <zlib.h>
  54. # else
  55. # include "../contrib/zlib/zlib.h"
  56. # endif
  57. #endif
  58. namespace Assimp {
  59. template <>
  60. const char *LogFunctions<BlenderImporter>::Prefix() {
  61. static auto prefix = "BLEND: ";
  62. return prefix;
  63. }
  64. } // namespace Assimp
  65. using namespace Assimp;
  66. using namespace Assimp::Blender;
  67. using namespace Assimp::Formatter;
  68. static const aiImporterDesc blenderDesc = {
  69. "Blender 3D Importer (http://www.blender3d.org)",
  70. "",
  71. "",
  72. "No animation support yet",
  73. aiImporterFlags_SupportBinaryFlavour,
  74. 0,
  75. 0,
  76. 2,
  77. 50,
  78. "blend"
  79. };
  80. // ------------------------------------------------------------------------------------------------
  81. // Constructor to be privately used by Importer
  82. BlenderImporter::BlenderImporter() :
  83. modifier_cache(new BlenderModifierShowcase()) {
  84. // empty
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. // Destructor, private as well
  88. BlenderImporter::~BlenderImporter() {
  89. delete modifier_cache;
  90. }
  91. static const char *Tokens[] = { "BLENDER" };
  92. static const char *TokensForSearch[] = { "blender" };
  93. // ------------------------------------------------------------------------------------------------
  94. // Returns whether the class can handle the format of the given file.
  95. bool BlenderImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const {
  96. const std::string &extension = GetExtension(pFile);
  97. if (extension == "blend") {
  98. return true;
  99. }
  100. if ((!extension.length() || checkSig) && pIOHandler) {
  101. // note: this won't catch compressed files
  102. return SearchFileHeaderForToken(pIOHandler, pFile, TokensForSearch, 1);
  103. }
  104. return false;
  105. }
  106. // ------------------------------------------------------------------------------------------------
  107. // Loader registry entry
  108. const aiImporterDesc *BlenderImporter::GetInfo() const {
  109. return &blenderDesc;
  110. }
  111. // ------------------------------------------------------------------------------------------------
  112. // Setup configuration properties for the loader
  113. void BlenderImporter::SetupProperties(const Importer * /*pImp*/) {
  114. // nothing to be done for the moment
  115. }
  116. // ------------------------------------------------------------------------------------------------
  117. // Imports the given file into the given scene structure.
  118. void BlenderImporter::InternReadFile(const std::string &pFile,
  119. aiScene *pScene, IOSystem *pIOHandler) {
  120. #ifndef ASSIMP_BUILD_NO_COMPRESSED_BLEND
  121. std::vector<Bytef> uncompressed;
  122. #endif
  123. FileDatabase file;
  124. std::shared_ptr<IOStream> stream(pIOHandler->Open(pFile, "rb"));
  125. if (!stream) {
  126. ThrowException("Could not open file for reading");
  127. }
  128. char magic[8] = { 0 };
  129. stream->Read(magic, 7, 1);
  130. if (strcmp(magic, Tokens[0])) {
  131. // Check for presence of the gzip header. If yes, assume it is a
  132. // compressed blend file and try uncompressing it, else fail. This is to
  133. // avoid uncompressing random files which our loader might end up with.
  134. #ifdef ASSIMP_BUILD_NO_COMPRESSED_BLEND
  135. ThrowException("BLENDER magic bytes are missing, is this file compressed (Assimp was built without decompression support)?");
  136. #else
  137. if (magic[0] != 0x1f || static_cast<uint8_t>(magic[1]) != 0x8b) {
  138. ThrowException("BLENDER magic bytes are missing, couldn't find GZIP header either");
  139. }
  140. LogDebug("Found no BLENDER magic word but a GZIP header, might be a compressed file");
  141. if (magic[2] != 8) {
  142. ThrowException("Unsupported GZIP compression method");
  143. }
  144. // http://www.gzip.org/zlib/rfc-gzip.html#header-trailer
  145. stream->Seek(0L, aiOrigin_SET);
  146. std::shared_ptr<StreamReaderLE> reader = std::shared_ptr<StreamReaderLE>(new StreamReaderLE(stream));
  147. // build a zlib stream
  148. z_stream zstream;
  149. zstream.opaque = Z_NULL;
  150. zstream.zalloc = Z_NULL;
  151. zstream.zfree = Z_NULL;
  152. zstream.data_type = Z_BINARY;
  153. // http://hewgill.com/journal/entries/349-how-to-decompress-gzip-stream-with-zlib
  154. inflateInit2(&zstream, 16 + MAX_WBITS);
  155. zstream.next_in = reinterpret_cast<Bytef *>(reader->GetPtr());
  156. zstream.avail_in = (uInt)reader->GetRemainingSize();
  157. size_t total = 0l;
  158. // TODO: be smarter about this, decompress directly into heap buffer
  159. // and decompress the data .... do 1k chunks in the hope that we won't kill the stack
  160. #define MYBLOCK 1024
  161. Bytef block[MYBLOCK];
  162. int ret;
  163. do {
  164. zstream.avail_out = MYBLOCK;
  165. zstream.next_out = block;
  166. ret = inflate(&zstream, Z_NO_FLUSH);
  167. if (ret != Z_STREAM_END && ret != Z_OK) {
  168. ThrowException("Failure decompressing this file using gzip, seemingly it is NOT a compressed .BLEND file");
  169. }
  170. const size_t have = MYBLOCK - zstream.avail_out;
  171. total += have;
  172. uncompressed.resize(total);
  173. memcpy(uncompressed.data() + total - have, block, have);
  174. } while (ret != Z_STREAM_END);
  175. // terminate zlib
  176. inflateEnd(&zstream);
  177. // replace the input stream with a memory stream
  178. stream.reset(new MemoryIOStream(reinterpret_cast<uint8_t *>(uncompressed.data()), total));
  179. // .. and retry
  180. stream->Read(magic, 7, 1);
  181. if (strcmp(magic, "BLENDER")) {
  182. ThrowException("Found no BLENDER magic word in decompressed GZIP file");
  183. }
  184. #endif
  185. }
  186. file.i64bit = (stream->Read(magic, 1, 1), magic[0] == '-');
  187. file.little = (stream->Read(magic, 1, 1), magic[0] == 'v');
  188. stream->Read(magic, 3, 1);
  189. magic[3] = '\0';
  190. LogInfo("Blender version is ", magic[0], ".", magic + 1,
  191. " (64bit: ", file.i64bit ? "true" : "false",
  192. ", little endian: ", file.little ? "true" : "false", ")");
  193. ParseBlendFile(file, stream);
  194. Scene scene;
  195. ExtractScene(scene, file);
  196. ConvertBlendFile(pScene, scene, file);
  197. }
  198. // ------------------------------------------------------------------------------------------------
  199. void BlenderImporter::ParseBlendFile(FileDatabase &out, std::shared_ptr<IOStream> stream) {
  200. out.reader = std::make_shared<StreamReaderAny>(stream, out.little);
  201. DNAParser dna_reader(out);
  202. const DNA *dna = nullptr;
  203. out.entries.reserve(128);
  204. { // even small BLEND files tend to consist of many file blocks
  205. SectionParser parser(*out.reader.get(), out.i64bit);
  206. // first parse the file in search for the DNA and insert all other sections into the database
  207. while ((parser.Next(), 1)) {
  208. const FileBlockHead &head = parser.GetCurrent();
  209. if (head.id == "ENDB") {
  210. break; // only valid end of the file
  211. } else if (head.id == "DNA1") {
  212. dna_reader.Parse();
  213. dna = &dna_reader.GetDNA();
  214. continue;
  215. }
  216. out.entries.push_back(head);
  217. }
  218. }
  219. if (!dna) {
  220. ThrowException("SDNA not found");
  221. }
  222. std::sort(out.entries.begin(), out.entries.end());
  223. }
  224. // ------------------------------------------------------------------------------------------------
  225. void BlenderImporter::ExtractScene(Scene &out, const FileDatabase &file) {
  226. const FileBlockHead *block = nullptr;
  227. std::map<std::string, size_t>::const_iterator it = file.dna.indices.find("Scene");
  228. if (it == file.dna.indices.end()) {
  229. ThrowException("There is no `Scene` structure record");
  230. }
  231. const Structure &ss = file.dna.structures[(*it).second];
  232. // we need a scene somewhere to start with.
  233. for (const FileBlockHead &bl : file.entries) {
  234. // Fix: using the DNA index is more reliable to locate scenes
  235. //if (bl.id == "SC") {
  236. if (bl.dna_index == (*it).second) {
  237. block = &bl;
  238. break;
  239. }
  240. }
  241. if (!block) {
  242. ThrowException("There is not a single `Scene` record to load");
  243. }
  244. file.reader->SetCurrentPos(block->start);
  245. ss.Convert(out, file);
  246. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  247. ASSIMP_LOG_INFO(
  248. "(Stats) Fields read: ", file.stats().fields_read,
  249. ", pointers resolved: ", file.stats().pointers_resolved,
  250. ", cache hits: ", file.stats().cache_hits,
  251. ", cached objects: ", file.stats().cached_objects);
  252. #endif
  253. }
  254. // ------------------------------------------------------------------------------------------------
  255. void BlenderImporter::ConvertBlendFile(aiScene *out, const Scene &in, const FileDatabase &file) {
  256. ConversionData conv(file);
  257. // FIXME it must be possible to take the hierarchy directly from
  258. // the file. This is terrible. Here, we're first looking for
  259. // all objects which don't have parent objects at all -
  260. std::deque<const Object *> no_parents;
  261. for (std::shared_ptr<Base> cur = std::static_pointer_cast<Base>(in.base.first); cur; cur = cur->next) {
  262. if (cur->object) {
  263. if (!cur->object->parent) {
  264. no_parents.push_back(cur->object.get());
  265. } else {
  266. conv.objects.insert(cur->object.get());
  267. }
  268. }
  269. }
  270. for (std::shared_ptr<Base> cur = in.basact; cur; cur = cur->next) {
  271. if (cur->object) {
  272. if (cur->object->parent) {
  273. conv.objects.insert(cur->object.get());
  274. }
  275. }
  276. }
  277. if (no_parents.empty()) {
  278. ThrowException("Expected at least one object with no parent");
  279. }
  280. aiNode *root = out->mRootNode = new aiNode("<BlenderRoot>");
  281. root->mNumChildren = static_cast<unsigned int>(no_parents.size());
  282. root->mChildren = new aiNode *[root->mNumChildren]();
  283. for (unsigned int i = 0; i < root->mNumChildren; ++i) {
  284. root->mChildren[i] = ConvertNode(in, no_parents[i], conv, aiMatrix4x4());
  285. root->mChildren[i]->mParent = root;
  286. }
  287. BuildMaterials(conv);
  288. if (conv.meshes->size()) {
  289. out->mMeshes = new aiMesh *[out->mNumMeshes = static_cast<unsigned int>(conv.meshes->size())];
  290. std::copy(conv.meshes->begin(), conv.meshes->end(), out->mMeshes);
  291. conv.meshes.dismiss();
  292. }
  293. if (conv.lights->size()) {
  294. out->mLights = new aiLight *[out->mNumLights = static_cast<unsigned int>(conv.lights->size())];
  295. std::copy(conv.lights->begin(), conv.lights->end(), out->mLights);
  296. conv.lights.dismiss();
  297. }
  298. if (conv.cameras->size()) {
  299. out->mCameras = new aiCamera *[out->mNumCameras = static_cast<unsigned int>(conv.cameras->size())];
  300. std::copy(conv.cameras->begin(), conv.cameras->end(), out->mCameras);
  301. conv.cameras.dismiss();
  302. }
  303. if (conv.materials->size()) {
  304. out->mMaterials = new aiMaterial *[out->mNumMaterials = static_cast<unsigned int>(conv.materials->size())];
  305. std::copy(conv.materials->begin(), conv.materials->end(), out->mMaterials);
  306. conv.materials.dismiss();
  307. }
  308. if (conv.textures->size()) {
  309. out->mTextures = new aiTexture *[out->mNumTextures = static_cast<unsigned int>(conv.textures->size())];
  310. std::copy(conv.textures->begin(), conv.textures->end(), out->mTextures);
  311. conv.textures.dismiss();
  312. }
  313. // acknowledge that the scene might come out incomplete
  314. // by Assimp's definition of `complete`: blender scenes
  315. // can consist of thousands of cameras or lights with
  316. // not a single mesh between them.
  317. if (!out->mNumMeshes) {
  318. out->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  319. }
  320. }
  321. // ------------------------------------------------------------------------------------------------
  322. void BlenderImporter::ResolveImage(aiMaterial *out, const Material *mat, const MTex *tex, const Image *img, ConversionData &conv_data) {
  323. (void)mat;
  324. (void)tex;
  325. (void)conv_data;
  326. aiString name;
  327. // check if the file contents are bundled with the BLEND file
  328. if (img->packedfile) {
  329. name.data[0] = '*';
  330. name.length = 1 + ASSIMP_itoa10(name.data + 1, static_cast<unsigned int>(MAXLEN - 1), static_cast<int32_t>(conv_data.textures->size()));
  331. conv_data.textures->push_back(new aiTexture());
  332. aiTexture *curTex = conv_data.textures->back();
  333. // usually 'img->name' will be the original file name of the embedded textures,
  334. // so we can extract the file extension from it.
  335. const size_t nlen = strlen(img->name);
  336. const char *s = img->name + nlen, *e = s;
  337. while (s >= img->name && *s != '.') {
  338. --s;
  339. }
  340. curTex->achFormatHint[0] = s + 1 > e ? '\0' : (char)::tolower((unsigned char)s[1]);
  341. curTex->achFormatHint[1] = s + 2 > e ? '\0' : (char)::tolower((unsigned char)s[2]);
  342. curTex->achFormatHint[2] = s + 3 > e ? '\0' : (char)::tolower((unsigned char)s[3]);
  343. curTex->achFormatHint[3] = '\0';
  344. // tex->mHeight = 0;
  345. curTex->mWidth = img->packedfile->size;
  346. uint8_t *ch = new uint8_t[curTex->mWidth];
  347. conv_data.db.reader->SetCurrentPos(static_cast<size_t>(img->packedfile->data->val));
  348. conv_data.db.reader->CopyAndAdvance(ch, curTex->mWidth);
  349. curTex->pcData = reinterpret_cast<aiTexel *>(ch);
  350. LogInfo("Reading embedded texture, original file was ", img->name);
  351. } else {
  352. name = aiString(img->name);
  353. }
  354. aiTextureType texture_type = aiTextureType_UNKNOWN;
  355. MTex::MapType map_type = tex->mapto;
  356. if (map_type & MTex::MapType_COL)
  357. texture_type = aiTextureType_DIFFUSE;
  358. else if (map_type & MTex::MapType_NORM) {
  359. if (tex->tex->imaflag & Tex::ImageFlags_NORMALMAP) {
  360. texture_type = aiTextureType_NORMALS;
  361. } else {
  362. texture_type = aiTextureType_HEIGHT;
  363. }
  364. out->AddProperty(&tex->norfac, 1, AI_MATKEY_BUMPSCALING);
  365. } else if (map_type & MTex::MapType_COLSPEC)
  366. texture_type = aiTextureType_SPECULAR;
  367. else if (map_type & MTex::MapType_COLMIR)
  368. texture_type = aiTextureType_REFLECTION;
  369. //else if (map_type & MTex::MapType_REF)
  370. else if (map_type & MTex::MapType_SPEC)
  371. texture_type = aiTextureType_SHININESS;
  372. else if (map_type & MTex::MapType_EMIT)
  373. texture_type = aiTextureType_EMISSIVE;
  374. //else if (map_type & MTex::MapType_ALPHA)
  375. //else if (map_type & MTex::MapType_HAR)
  376. //else if (map_type & MTex::MapType_RAYMIRR)
  377. //else if (map_type & MTex::MapType_TRANSLU)
  378. else if (map_type & MTex::MapType_AMB)
  379. texture_type = aiTextureType_AMBIENT;
  380. else if (map_type & MTex::MapType_DISPLACE)
  381. texture_type = aiTextureType_DISPLACEMENT;
  382. //else if (map_type & MTex::MapType_WARP)
  383. out->AddProperty(&name, AI_MATKEY_TEXTURE(texture_type,
  384. conv_data.next_texture[texture_type]++));
  385. }
  386. // ------------------------------------------------------------------------------------------------
  387. void BlenderImporter::AddSentinelTexture(aiMaterial *out, const Material *mat, const MTex *tex, ConversionData &conv_data) {
  388. (void)mat;
  389. (void)tex;
  390. (void)conv_data;
  391. aiString name;
  392. name.length = ai_snprintf(name.data, MAXLEN, "Procedural,num=%i,type=%s", conv_data.sentinel_cnt++,
  393. GetTextureTypeDisplayString(tex->tex->type));
  394. out->AddProperty(&name, AI_MATKEY_TEXTURE_DIFFUSE(
  395. conv_data.next_texture[aiTextureType_DIFFUSE]++));
  396. }
  397. // ------------------------------------------------------------------------------------------------
  398. void BlenderImporter::ResolveTexture(aiMaterial *out, const Material *mat, const MTex *tex, ConversionData &conv_data) {
  399. const Tex *rtex = tex->tex.get();
  400. if (!rtex || !rtex->type) {
  401. return;
  402. }
  403. // We can't support most of the texture types because they're mostly procedural.
  404. // These are substituted by a dummy texture.
  405. const char *dispnam = "";
  406. switch (rtex->type) {
  407. // these are listed in blender's UI
  408. case Tex::Type_CLOUDS:
  409. case Tex::Type_WOOD:
  410. case Tex::Type_MARBLE:
  411. case Tex::Type_MAGIC:
  412. case Tex::Type_BLEND:
  413. case Tex::Type_STUCCI:
  414. case Tex::Type_NOISE:
  415. case Tex::Type_PLUGIN:
  416. case Tex::Type_MUSGRAVE:
  417. case Tex::Type_VORONOI:
  418. case Tex::Type_DISTNOISE:
  419. case Tex::Type_ENVMAP:
  420. // these do no appear in the UI, why?
  421. case Tex::Type_POINTDENSITY:
  422. case Tex::Type_VOXELDATA:
  423. LogWarn("Encountered a texture with an unsupported type: ", dispnam);
  424. AddSentinelTexture(out, mat, tex, conv_data);
  425. break;
  426. case Tex::Type_IMAGE:
  427. if (!rtex->ima) {
  428. LogError("A texture claims to be an Image, but no image reference is given");
  429. break;
  430. }
  431. ResolveImage(out, mat, tex, rtex->ima.get(), conv_data);
  432. break;
  433. default:
  434. ai_assert(false);
  435. };
  436. }
  437. // ------------------------------------------------------------------------------------------------
  438. void BlenderImporter::BuildDefaultMaterial(Blender::ConversionData &conv_data) {
  439. // add a default material if necessary
  440. unsigned int index = static_cast<unsigned int>(-1);
  441. for (aiMesh *mesh : conv_data.meshes.get()) {
  442. if (mesh->mMaterialIndex == static_cast<unsigned int>(-1)) {
  443. if (index == static_cast<unsigned int>(-1)) {
  444. // Setup a default material.
  445. std::shared_ptr<Material> p(new Material());
  446. ai_assert(::strlen(AI_DEFAULT_MATERIAL_NAME) < sizeof(p->id.name) - 2);
  447. strcpy(p->id.name + 2, AI_DEFAULT_MATERIAL_NAME);
  448. // Note: MSVC11 does not zero-initialize Material here, although it should.
  449. // Thus all relevant fields should be explicitly initialized. We cannot add
  450. // a default constructor to Material since the DNA codegen does not support
  451. // parsing it.
  452. p->r = p->g = p->b = 0.6f;
  453. p->specr = p->specg = p->specb = 0.6f;
  454. p->ambr = p->ambg = p->ambb = 0.0f;
  455. p->mirr = p->mirg = p->mirb = 0.0f;
  456. p->emit = 0.f;
  457. p->alpha = 0.f;
  458. p->har = 0;
  459. index = static_cast<unsigned int>(conv_data.materials_raw.size());
  460. conv_data.materials_raw.push_back(p);
  461. LogInfo("Adding default material");
  462. }
  463. mesh->mMaterialIndex = index;
  464. }
  465. }
  466. }
  467. void BlenderImporter::AddBlendParams(aiMaterial *result, const Material *source) {
  468. aiColor3D diffuseColor(source->r, source->g, source->b);
  469. result->AddProperty(&diffuseColor, 1, "$mat.blend.diffuse.color", 0, 0);
  470. float diffuseIntensity = source->ref;
  471. result->AddProperty(&diffuseIntensity, 1, "$mat.blend.diffuse.intensity", 0, 0);
  472. int diffuseShader = source->diff_shader;
  473. result->AddProperty(&diffuseShader, 1, "$mat.blend.diffuse.shader", 0, 0);
  474. int diffuseRamp = 0;
  475. result->AddProperty(&diffuseRamp, 1, "$mat.blend.diffuse.ramp", 0, 0);
  476. aiColor3D specularColor(source->specr, source->specg, source->specb);
  477. result->AddProperty(&specularColor, 1, "$mat.blend.specular.color", 0, 0);
  478. float specularIntensity = source->spec;
  479. result->AddProperty(&specularIntensity, 1, "$mat.blend.specular.intensity", 0, 0);
  480. int specularShader = source->spec_shader;
  481. result->AddProperty(&specularShader, 1, "$mat.blend.specular.shader", 0, 0);
  482. int specularRamp = 0;
  483. result->AddProperty(&specularRamp, 1, "$mat.blend.specular.ramp", 0, 0);
  484. int specularHardness = source->har;
  485. result->AddProperty(&specularHardness, 1, "$mat.blend.specular.hardness", 0, 0);
  486. int transparencyUse = source->mode & MA_TRANSPARENCY ? 1 : 0;
  487. result->AddProperty(&transparencyUse, 1, "$mat.blend.transparency.use", 0, 0);
  488. int transparencyMethod = source->mode & MA_RAYTRANSP ? 2 : (source->mode & MA_ZTRANSP ? 1 : 0);
  489. result->AddProperty(&transparencyMethod, 1, "$mat.blend.transparency.method", 0, 0);
  490. float transparencyAlpha = source->alpha;
  491. result->AddProperty(&transparencyAlpha, 1, "$mat.blend.transparency.alpha", 0, 0);
  492. float transparencySpecular = source->spectra;
  493. result->AddProperty(&transparencySpecular, 1, "$mat.blend.transparency.specular", 0, 0);
  494. float transparencyFresnel = source->fresnel_tra;
  495. result->AddProperty(&transparencyFresnel, 1, "$mat.blend.transparency.fresnel", 0, 0);
  496. float transparencyBlend = source->fresnel_tra_i;
  497. result->AddProperty(&transparencyBlend, 1, "$mat.blend.transparency.blend", 0, 0);
  498. float transparencyIor = source->ang;
  499. result->AddProperty(&transparencyIor, 1, "$mat.blend.transparency.ior", 0, 0);
  500. float transparencyFilter = source->filter;
  501. result->AddProperty(&transparencyFilter, 1, "$mat.blend.transparency.filter", 0, 0);
  502. float transparencyFalloff = source->tx_falloff;
  503. result->AddProperty(&transparencyFalloff, 1, "$mat.blend.transparency.falloff", 0, 0);
  504. float transparencyLimit = source->tx_limit;
  505. result->AddProperty(&transparencyLimit, 1, "$mat.blend.transparency.limit", 0, 0);
  506. int transparencyDepth = source->ray_depth_tra;
  507. result->AddProperty(&transparencyDepth, 1, "$mat.blend.transparency.depth", 0, 0);
  508. float transparencyGlossAmount = source->gloss_tra;
  509. result->AddProperty(&transparencyGlossAmount, 1, "$mat.blend.transparency.glossAmount", 0, 0);
  510. float transparencyGlossThreshold = source->adapt_thresh_tra;
  511. result->AddProperty(&transparencyGlossThreshold, 1, "$mat.blend.transparency.glossThreshold", 0, 0);
  512. int transparencyGlossSamples = source->samp_gloss_tra;
  513. result->AddProperty(&transparencyGlossSamples, 1, "$mat.blend.transparency.glossSamples", 0, 0);
  514. int mirrorUse = source->mode & MA_RAYMIRROR ? 1 : 0;
  515. result->AddProperty(&mirrorUse, 1, "$mat.blend.mirror.use", 0, 0);
  516. float mirrorReflectivity = source->ray_mirror;
  517. result->AddProperty(&mirrorReflectivity, 1, "$mat.blend.mirror.reflectivity", 0, 0);
  518. aiColor3D mirrorColor(source->mirr, source->mirg, source->mirb);
  519. result->AddProperty(&mirrorColor, 1, "$mat.blend.mirror.color", 0, 0);
  520. float mirrorFresnel = source->fresnel_mir;
  521. result->AddProperty(&mirrorFresnel, 1, "$mat.blend.mirror.fresnel", 0, 0);
  522. float mirrorBlend = source->fresnel_mir_i;
  523. result->AddProperty(&mirrorBlend, 1, "$mat.blend.mirror.blend", 0, 0);
  524. int mirrorDepth = source->ray_depth;
  525. result->AddProperty(&mirrorDepth, 1, "$mat.blend.mirror.depth", 0, 0);
  526. float mirrorMaxDist = source->dist_mir;
  527. result->AddProperty(&mirrorMaxDist, 1, "$mat.blend.mirror.maxDist", 0, 0);
  528. int mirrorFadeTo = source->fadeto_mir;
  529. result->AddProperty(&mirrorFadeTo, 1, "$mat.blend.mirror.fadeTo", 0, 0);
  530. float mirrorGlossAmount = source->gloss_mir;
  531. result->AddProperty(&mirrorGlossAmount, 1, "$mat.blend.mirror.glossAmount", 0, 0);
  532. float mirrorGlossThreshold = source->adapt_thresh_mir;
  533. result->AddProperty(&mirrorGlossThreshold, 1, "$mat.blend.mirror.glossThreshold", 0, 0);
  534. int mirrorGlossSamples = source->samp_gloss_mir;
  535. result->AddProperty(&mirrorGlossSamples, 1, "$mat.blend.mirror.glossSamples", 0, 0);
  536. float mirrorGlossAnisotropic = source->aniso_gloss_mir;
  537. result->AddProperty(&mirrorGlossAnisotropic, 1, "$mat.blend.mirror.glossAnisotropic", 0, 0);
  538. }
  539. void BlenderImporter::BuildMaterials(ConversionData &conv_data) {
  540. conv_data.materials->reserve(conv_data.materials_raw.size());
  541. BuildDefaultMaterial(conv_data);
  542. for (const std::shared_ptr<Material> &mat : conv_data.materials_raw) {
  543. // reset per material global counters
  544. for (size_t i = 0; i < sizeof(conv_data.next_texture) / sizeof(conv_data.next_texture[0]); ++i) {
  545. conv_data.next_texture[i] = 0;
  546. }
  547. aiMaterial *mout = new aiMaterial();
  548. conv_data.materials->push_back(mout);
  549. // For any new material field handled here, the default material above must be updated with an appropriate default value.
  550. // set material name
  551. aiString name = aiString(mat->id.name + 2); // skip over the name prefix 'MA'
  552. mout->AddProperty(&name, AI_MATKEY_NAME);
  553. // basic material colors
  554. aiColor3D col(mat->r, mat->g, mat->b);
  555. if (mat->r || mat->g || mat->b) {
  556. // Usually, zero diffuse color means no diffuse color at all in the equation.
  557. // So we omit this member to express this intent.
  558. mout->AddProperty(&col, 1, AI_MATKEY_COLOR_DIFFUSE);
  559. if (mat->emit) {
  560. aiColor3D emit_col(mat->emit * mat->r, mat->emit * mat->g, mat->emit * mat->b);
  561. mout->AddProperty(&emit_col, 1, AI_MATKEY_COLOR_EMISSIVE);
  562. }
  563. }
  564. col = aiColor3D(mat->specr, mat->specg, mat->specb);
  565. mout->AddProperty(&col, 1, AI_MATKEY_COLOR_SPECULAR);
  566. // is hardness/shininess set?
  567. if (mat->har) {
  568. const float har = mat->har;
  569. mout->AddProperty(&har, 1, AI_MATKEY_SHININESS);
  570. }
  571. col = aiColor3D(mat->ambr, mat->ambg, mat->ambb);
  572. mout->AddProperty(&col, 1, AI_MATKEY_COLOR_AMBIENT);
  573. // is mirror enabled?
  574. if (mat->mode & MA_RAYMIRROR) {
  575. const float ray_mirror = mat->ray_mirror;
  576. mout->AddProperty(&ray_mirror, 1, AI_MATKEY_REFLECTIVITY);
  577. }
  578. col = aiColor3D(mat->mirr, mat->mirg, mat->mirb);
  579. mout->AddProperty(&col, 1, AI_MATKEY_COLOR_REFLECTIVE);
  580. for (size_t i = 0; i < sizeof(mat->mtex) / sizeof(mat->mtex[0]); ++i) {
  581. if (!mat->mtex[i]) {
  582. continue;
  583. }
  584. ResolveTexture(mout, mat.get(), mat->mtex[i].get(), conv_data);
  585. }
  586. AddBlendParams(mout, mat.get());
  587. }
  588. }
  589. // ------------------------------------------------------------------------------------------------
  590. void BlenderImporter::CheckActualType(const ElemBase *dt, const char *check) {
  591. ai_assert(dt);
  592. if (strcmp(dt->dna_type, check)) {
  593. ThrowException("Expected object at ", std::hex, dt, " to be of type `", check,
  594. "`, but it claims to be a `", dt->dna_type, "`instead");
  595. }
  596. }
  597. // ------------------------------------------------------------------------------------------------
  598. void BlenderImporter::NotSupportedObjectType(const Object *obj, const char *type) {
  599. LogWarn("Object `", obj->id.name, "` - type is unsupported: `", type, "`, skipping");
  600. }
  601. // ------------------------------------------------------------------------------------------------
  602. void BlenderImporter::ConvertMesh(const Scene & /*in*/, const Object * /*obj*/, const Mesh *mesh,
  603. ConversionData &conv_data, TempArray<std::vector, aiMesh> &temp) {
  604. // TODO: Resolve various problems with BMesh triangulation before re-enabling.
  605. // See issues #400, #373, #318 #315 and #132.
  606. #if defined(TODO_FIX_BMESH_CONVERSION)
  607. BlenderBMeshConverter BMeshConverter(mesh);
  608. if (BMeshConverter.ContainsBMesh()) {
  609. mesh = BMeshConverter.TriangulateBMesh();
  610. }
  611. #endif
  612. typedef std::pair<const int, size_t> MyPair;
  613. if ((!mesh->totface && !mesh->totloop) || !mesh->totvert) {
  614. return;
  615. }
  616. // some sanity checks
  617. if (static_cast<size_t>(mesh->totface) > mesh->mface.size()) {
  618. ThrowException("Number of faces is larger than the corresponding array");
  619. }
  620. if (static_cast<size_t>(mesh->totvert) > mesh->mvert.size()) {
  621. ThrowException("Number of vertices is larger than the corresponding array");
  622. }
  623. if (static_cast<size_t>(mesh->totloop) > mesh->mloop.size()) {
  624. ThrowException("Number of vertices is larger than the corresponding array");
  625. }
  626. // collect per-submesh numbers
  627. std::map<int, size_t> per_mat;
  628. std::map<int, size_t> per_mat_verts;
  629. for (int i = 0; i < mesh->totface; ++i) {
  630. const MFace &mf = mesh->mface[i];
  631. per_mat[mf.mat_nr]++;
  632. per_mat_verts[mf.mat_nr] += mf.v4 ? 4 : 3;
  633. }
  634. for (int i = 0; i < mesh->totpoly; ++i) {
  635. const MPoly &mp = mesh->mpoly[i];
  636. per_mat[mp.mat_nr]++;
  637. per_mat_verts[mp.mat_nr] += mp.totloop;
  638. }
  639. // ... and allocate the corresponding meshes
  640. const size_t old = temp->size();
  641. temp->reserve(temp->size() + per_mat.size());
  642. std::map<size_t, size_t> mat_num_to_mesh_idx;
  643. for (MyPair &it : per_mat) {
  644. mat_num_to_mesh_idx[it.first] = temp->size();
  645. temp->push_back(new aiMesh());
  646. aiMesh *out = temp->back();
  647. out->mVertices = new aiVector3D[per_mat_verts[it.first]];
  648. out->mNormals = new aiVector3D[per_mat_verts[it.first]];
  649. //out->mNumFaces = 0
  650. //out->mNumVertices = 0
  651. out->mFaces = new aiFace[it.second]();
  652. // all sub-meshes created from this mesh are named equally. this allows
  653. // curious users to recover the original adjacency.
  654. out->mName = aiString(mesh->id.name + 2);
  655. // skip over the name prefix 'ME'
  656. // resolve the material reference and add this material to the set of
  657. // output materials. The (temporary) material index is the index
  658. // of the material entry within the list of resolved materials.
  659. if (mesh->mat) {
  660. if (static_cast<size_t>(it.first) >= mesh->mat.size()) {
  661. ThrowException("Material index is out of range");
  662. }
  663. std::shared_ptr<Material> mat = mesh->mat[it.first];
  664. const std::deque<std::shared_ptr<Material>>::iterator has = std::find(
  665. conv_data.materials_raw.begin(),
  666. conv_data.materials_raw.end(), mat);
  667. if (has != conv_data.materials_raw.end()) {
  668. out->mMaterialIndex = static_cast<unsigned int>(std::distance(conv_data.materials_raw.begin(), has));
  669. } else {
  670. out->mMaterialIndex = static_cast<unsigned int>(conv_data.materials_raw.size());
  671. conv_data.materials_raw.push_back(mat);
  672. }
  673. } else
  674. out->mMaterialIndex = static_cast<unsigned int>(-1);
  675. }
  676. for (int i = 0; i < mesh->totface; ++i) {
  677. const MFace &mf = mesh->mface[i];
  678. aiMesh *const out = temp[mat_num_to_mesh_idx[mf.mat_nr]];
  679. aiFace &f = out->mFaces[out->mNumFaces++];
  680. f.mIndices = new unsigned int[f.mNumIndices = mf.v4 ? 4 : 3];
  681. aiVector3D *vo = out->mVertices + out->mNumVertices;
  682. aiVector3D *vn = out->mNormals + out->mNumVertices;
  683. // XXX we can't fold this easily, because we are restricted
  684. // to the member names from the BLEND file (v1,v2,v3,v4)
  685. // which are assigned by the genblenddna.py script and
  686. // cannot be changed without breaking the entire
  687. // import process.
  688. if (mf.v1 >= mesh->totvert) {
  689. ThrowException("Vertex index v1 out of range");
  690. }
  691. const MVert *v = &mesh->mvert[mf.v1];
  692. vo->x = v->co[0];
  693. vo->y = v->co[1];
  694. vo->z = v->co[2];
  695. vn->x = v->no[0];
  696. vn->y = v->no[1];
  697. vn->z = v->no[2];
  698. f.mIndices[0] = out->mNumVertices++;
  699. ++vo;
  700. ++vn;
  701. // if (f.mNumIndices >= 2) {
  702. if (mf.v2 >= mesh->totvert) {
  703. ThrowException("Vertex index v2 out of range");
  704. }
  705. v = &mesh->mvert[mf.v2];
  706. vo->x = v->co[0];
  707. vo->y = v->co[1];
  708. vo->z = v->co[2];
  709. vn->x = v->no[0];
  710. vn->y = v->no[1];
  711. vn->z = v->no[2];
  712. f.mIndices[1] = out->mNumVertices++;
  713. ++vo;
  714. ++vn;
  715. if (mf.v3 >= mesh->totvert) {
  716. ThrowException("Vertex index v3 out of range");
  717. }
  718. // if (f.mNumIndices >= 3) {
  719. v = &mesh->mvert[mf.v3];
  720. vo->x = v->co[0];
  721. vo->y = v->co[1];
  722. vo->z = v->co[2];
  723. vn->x = v->no[0];
  724. vn->y = v->no[1];
  725. vn->z = v->no[2];
  726. f.mIndices[2] = out->mNumVertices++;
  727. ++vo;
  728. ++vn;
  729. if (mf.v4 >= mesh->totvert) {
  730. ThrowException("Vertex index v4 out of range");
  731. }
  732. // if (f.mNumIndices >= 4) {
  733. if (mf.v4) {
  734. v = &mesh->mvert[mf.v4];
  735. vo->x = v->co[0];
  736. vo->y = v->co[1];
  737. vo->z = v->co[2];
  738. vn->x = v->no[0];
  739. vn->y = v->no[1];
  740. vn->z = v->no[2];
  741. f.mIndices[3] = out->mNumVertices++;
  742. ++vo;
  743. ++vn;
  744. out->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  745. } else
  746. out->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  747. // }
  748. // }
  749. // }
  750. }
  751. for (int i = 0; i < mesh->totpoly; ++i) {
  752. const MPoly &mf = mesh->mpoly[i];
  753. aiMesh *const out = temp[mat_num_to_mesh_idx[mf.mat_nr]];
  754. aiFace &f = out->mFaces[out->mNumFaces++];
  755. f.mIndices = new unsigned int[f.mNumIndices = mf.totloop];
  756. aiVector3D *vo = out->mVertices + out->mNumVertices;
  757. aiVector3D *vn = out->mNormals + out->mNumVertices;
  758. // XXX we can't fold this easily, because we are restricted
  759. // to the member names from the BLEND file (v1,v2,v3,v4)
  760. // which are assigned by the genblenddna.py script and
  761. // cannot be changed without breaking the entire
  762. // import process.
  763. for (int j = 0; j < mf.totloop; ++j) {
  764. const MLoop &loop = mesh->mloop[mf.loopstart + j];
  765. if (loop.v >= mesh->totvert) {
  766. ThrowException("Vertex index out of range");
  767. }
  768. const MVert &v = mesh->mvert[loop.v];
  769. vo->x = v.co[0];
  770. vo->y = v.co[1];
  771. vo->z = v.co[2];
  772. vn->x = v.no[0];
  773. vn->y = v.no[1];
  774. vn->z = v.no[2];
  775. f.mIndices[j] = out->mNumVertices++;
  776. ++vo;
  777. ++vn;
  778. }
  779. if (mf.totloop == 3) {
  780. out->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  781. } else {
  782. out->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  783. }
  784. }
  785. // TODO should we create the TextureUVMapping map in Convert<Material> to prevent redundant processing?
  786. // create texture <-> uvname mapping for all materials
  787. // key is texture number, value is data *
  788. typedef std::map<uint32_t, const MLoopUV *> TextureUVMapping;
  789. // key is material number, value is the TextureUVMapping for the material
  790. typedef std::map<uint32_t, TextureUVMapping> MaterialTextureUVMappings;
  791. MaterialTextureUVMappings matTexUvMappings;
  792. const uint32_t maxMat = static_cast<const uint32_t>(mesh->mat.size());
  793. for (uint32_t m = 0; m < maxMat; ++m) {
  794. // get material by index
  795. const std::shared_ptr<Material> pMat = mesh->mat[m];
  796. TextureUVMapping texuv;
  797. const uint32_t maxTex = sizeof(pMat->mtex) / sizeof(pMat->mtex[0]);
  798. for (uint32_t t = 0; t < maxTex; ++t) {
  799. if (pMat->mtex[t] && pMat->mtex[t]->uvname[0]) {
  800. // get the CustomData layer for given uvname and correct type
  801. const ElemBase *pLoop = getCustomDataLayerData(mesh->ldata, CD_MLOOPUV, pMat->mtex[t]->uvname);
  802. if (pLoop) {
  803. texuv.insert(std::make_pair(t, dynamic_cast<const MLoopUV *>(pLoop)));
  804. }
  805. }
  806. }
  807. if (texuv.size()) {
  808. matTexUvMappings.insert(std::make_pair(m, texuv));
  809. }
  810. }
  811. // collect texture coordinates, they're stored in a separate per-face buffer
  812. if (mesh->mtface || mesh->mloopuv) {
  813. if (mesh->totface > static_cast<int>(mesh->mtface.size())) {
  814. ThrowException("Number of UV faces is larger than the corresponding UV face array (#1)");
  815. }
  816. for (std::vector<aiMesh *>::iterator it = temp->begin() + old; it != temp->end(); ++it) {
  817. ai_assert(0 != (*it)->mNumVertices);
  818. ai_assert(0 != (*it)->mNumFaces);
  819. const auto itMatTexUvMapping = matTexUvMappings.find((*it)->mMaterialIndex);
  820. if (itMatTexUvMapping == matTexUvMappings.end()) {
  821. // default behaviour like before
  822. (*it)->mTextureCoords[0] = new aiVector3D[(*it)->mNumVertices];
  823. } else {
  824. // create texture coords for every mapped tex
  825. for (uint32_t i = 0; i < itMatTexUvMapping->second.size(); ++i) {
  826. (*it)->mTextureCoords[i] = new aiVector3D[(*it)->mNumVertices];
  827. }
  828. }
  829. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  830. }
  831. for (int i = 0; i < mesh->totface; ++i) {
  832. const MTFace *v = &mesh->mtface[i];
  833. aiMesh *const out = temp[mat_num_to_mesh_idx[mesh->mface[i].mat_nr]];
  834. const aiFace &f = out->mFaces[out->mNumFaces++];
  835. aiVector3D *vo = &out->mTextureCoords[0][out->mNumVertices];
  836. for (unsigned int j = 0; j < f.mNumIndices; ++j, ++vo, ++out->mNumVertices) {
  837. vo->x = v->uv[j][0];
  838. vo->y = v->uv[j][1];
  839. }
  840. }
  841. for (int i = 0; i < mesh->totpoly; ++i) {
  842. const MPoly &v = mesh->mpoly[i];
  843. aiMesh *const out = temp[mat_num_to_mesh_idx[v.mat_nr]];
  844. const aiFace &f = out->mFaces[out->mNumFaces++];
  845. const auto itMatTexUvMapping = matTexUvMappings.find(v.mat_nr);
  846. if (itMatTexUvMapping == matTexUvMappings.end()) {
  847. // old behavior
  848. aiVector3D *vo = &out->mTextureCoords[0][out->mNumVertices];
  849. for (unsigned int j = 0; j < f.mNumIndices; ++j, ++vo, ++out->mNumVertices) {
  850. const MLoopUV &uv = mesh->mloopuv[v.loopstart + j];
  851. vo->x = uv.uv[0];
  852. vo->y = uv.uv[1];
  853. }
  854. } else {
  855. // create textureCoords for every mapped tex
  856. for (uint32_t m = 0; m < itMatTexUvMapping->second.size(); ++m) {
  857. const MLoopUV *tm = itMatTexUvMapping->second[m];
  858. aiVector3D *vo = &out->mTextureCoords[m][out->mNumVertices];
  859. uint32_t j = 0;
  860. for (; j < f.mNumIndices; ++j, ++vo) {
  861. const MLoopUV &uv = tm[v.loopstart + j];
  862. vo->x = uv.uv[0];
  863. vo->y = uv.uv[1];
  864. }
  865. // only update written mNumVertices in last loop
  866. // TODO why must the numVertices be incremented here?
  867. if (m == itMatTexUvMapping->second.size() - 1) {
  868. out->mNumVertices += j;
  869. }
  870. }
  871. }
  872. }
  873. }
  874. // collect texture coordinates, old-style (marked as deprecated in current blender sources)
  875. if (mesh->tface) {
  876. if (mesh->totface > static_cast<int>(mesh->tface.size())) {
  877. ThrowException("Number of faces is larger than the corresponding UV face array (#2)");
  878. }
  879. for (std::vector<aiMesh *>::iterator it = temp->begin() + old; it != temp->end(); ++it) {
  880. ai_assert(0 != (*it)->mNumVertices);
  881. ai_assert(0 != (*it)->mNumFaces);
  882. (*it)->mTextureCoords[0] = new aiVector3D[(*it)->mNumVertices];
  883. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  884. }
  885. for (int i = 0; i < mesh->totface; ++i) {
  886. const TFace *v = &mesh->tface[i];
  887. aiMesh *const out = temp[mat_num_to_mesh_idx[mesh->mface[i].mat_nr]];
  888. const aiFace &f = out->mFaces[out->mNumFaces++];
  889. aiVector3D *vo = &out->mTextureCoords[0][out->mNumVertices];
  890. for (unsigned int j = 0; j < f.mNumIndices; ++j, ++vo, ++out->mNumVertices) {
  891. vo->x = v->uv[j][0];
  892. vo->y = v->uv[j][1];
  893. }
  894. }
  895. }
  896. // collect vertex colors, stored separately as well
  897. if (mesh->mcol || mesh->mloopcol) {
  898. if (mesh->totface > static_cast<int>((mesh->mcol.size() / 4))) {
  899. ThrowException("Number of faces is larger than the corresponding color face array");
  900. }
  901. for (std::vector<aiMesh *>::iterator it = temp->begin() + old; it != temp->end(); ++it) {
  902. ai_assert(0 != (*it)->mNumVertices);
  903. ai_assert(0 != (*it)->mNumFaces);
  904. (*it)->mColors[0] = new aiColor4D[(*it)->mNumVertices];
  905. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  906. }
  907. for (int i = 0; i < mesh->totface; ++i) {
  908. aiMesh *const out = temp[mat_num_to_mesh_idx[mesh->mface[i].mat_nr]];
  909. const aiFace &f = out->mFaces[out->mNumFaces++];
  910. aiColor4D *vo = &out->mColors[0][out->mNumVertices];
  911. for (unsigned int n = 0; n < f.mNumIndices; ++n, ++vo, ++out->mNumVertices) {
  912. const MCol *col = &mesh->mcol[(i << 2) + n];
  913. vo->r = col->r;
  914. vo->g = col->g;
  915. vo->b = col->b;
  916. vo->a = col->a;
  917. }
  918. for (unsigned int n = f.mNumIndices; n < 4; ++n)
  919. ;
  920. }
  921. for (int i = 0; i < mesh->totpoly; ++i) {
  922. const MPoly &v = mesh->mpoly[i];
  923. aiMesh *const out = temp[mat_num_to_mesh_idx[v.mat_nr]];
  924. const aiFace &f = out->mFaces[out->mNumFaces++];
  925. aiColor4D *vo = &out->mColors[0][out->mNumVertices];
  926. const ai_real scaleZeroToOne = 1.f / 255.f;
  927. for (unsigned int j = 0; j < f.mNumIndices; ++j, ++vo, ++out->mNumVertices) {
  928. const MLoopCol &col = mesh->mloopcol[v.loopstart + j];
  929. vo->r = ai_real(col.r) * scaleZeroToOne;
  930. vo->g = ai_real(col.g) * scaleZeroToOne;
  931. vo->b = ai_real(col.b) * scaleZeroToOne;
  932. vo->a = ai_real(col.a) * scaleZeroToOne;
  933. }
  934. }
  935. }
  936. return;
  937. }
  938. // ------------------------------------------------------------------------------------------------
  939. aiCamera *BlenderImporter::ConvertCamera(const Scene & /*in*/, const Object *obj, const Camera *cam, ConversionData & /*conv_data*/) {
  940. std::unique_ptr<aiCamera> out(new aiCamera());
  941. out->mName = obj->id.name + 2;
  942. out->mPosition = aiVector3D(0.f, 0.f, 0.f);
  943. out->mUp = aiVector3D(0.f, 1.f, 0.f);
  944. out->mLookAt = aiVector3D(0.f, 0.f, -1.f);
  945. if (cam->sensor_x && cam->lens) {
  946. out->mHorizontalFOV = 2.f * std::atan2(cam->sensor_x, 2.f * cam->lens);
  947. }
  948. out->mClipPlaneNear = cam->clipsta;
  949. out->mClipPlaneFar = cam->clipend;
  950. return out.release();
  951. }
  952. // ------------------------------------------------------------------------------------------------
  953. aiLight *BlenderImporter::ConvertLight(const Scene & /*in*/, const Object *obj, const Lamp *lamp, ConversionData & /*conv_data*/) {
  954. std::unique_ptr<aiLight> out(new aiLight());
  955. out->mName = obj->id.name + 2;
  956. switch (lamp->type) {
  957. case Lamp::Type_Local:
  958. out->mType = aiLightSource_POINT;
  959. break;
  960. case Lamp::Type_Spot:
  961. out->mType = aiLightSource_SPOT;
  962. // blender orients directional lights as facing toward -z
  963. out->mDirection = aiVector3D(0.f, 0.f, -1.f);
  964. out->mUp = aiVector3D(0.f, 1.f, 0.f);
  965. out->mAngleInnerCone = lamp->spotsize * (1.0f - lamp->spotblend);
  966. out->mAngleOuterCone = lamp->spotsize;
  967. break;
  968. case Lamp::Type_Sun:
  969. out->mType = aiLightSource_DIRECTIONAL;
  970. // blender orients directional lights as facing toward -z
  971. out->mDirection = aiVector3D(0.f, 0.f, -1.f);
  972. out->mUp = aiVector3D(0.f, 1.f, 0.f);
  973. break;
  974. case Lamp::Type_Area:
  975. out->mType = aiLightSource_AREA;
  976. if (lamp->area_shape == 0) {
  977. out->mSize = aiVector2D(lamp->area_size, lamp->area_size);
  978. } else {
  979. out->mSize = aiVector2D(lamp->area_size, lamp->area_sizey);
  980. }
  981. // blender orients directional lights as facing toward -z
  982. out->mDirection = aiVector3D(0.f, 0.f, -1.f);
  983. out->mUp = aiVector3D(0.f, 1.f, 0.f);
  984. break;
  985. default:
  986. break;
  987. }
  988. out->mColorAmbient = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy;
  989. out->mColorSpecular = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy;
  990. out->mColorDiffuse = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy;
  991. // If default values are supplied, compute the coefficients from light's max distance
  992. // Read this: https://imdoingitwrong.wordpress.com/2011/01/31/light-attenuation/
  993. //
  994. if (lamp->constant_coefficient == 1.0f && lamp->linear_coefficient == 0.0f && lamp->quadratic_coefficient == 0.0f && lamp->dist > 0.0f) {
  995. out->mAttenuationConstant = 1.0f;
  996. out->mAttenuationLinear = 2.0f / lamp->dist;
  997. out->mAttenuationQuadratic = 1.0f / (lamp->dist * lamp->dist);
  998. } else {
  999. out->mAttenuationConstant = lamp->constant_coefficient;
  1000. out->mAttenuationLinear = lamp->linear_coefficient;
  1001. out->mAttenuationQuadratic = lamp->quadratic_coefficient;
  1002. }
  1003. return out.release();
  1004. }
  1005. // ------------------------------------------------------------------------------------------------
  1006. aiNode *BlenderImporter::ConvertNode(const Scene &in, const Object *obj, ConversionData &conv_data, const aiMatrix4x4 &parentTransform) {
  1007. std::deque<const Object *> children;
  1008. for (ObjectSet::iterator it = conv_data.objects.begin(); it != conv_data.objects.end();) {
  1009. const Object *object = *it;
  1010. if (object->parent == obj) {
  1011. children.push_back(object);
  1012. conv_data.objects.erase(it++);
  1013. continue;
  1014. }
  1015. ++it;
  1016. }
  1017. std::unique_ptr<aiNode> node(new aiNode(obj->id.name + 2)); // skip over the name prefix 'OB'
  1018. if (obj->data) {
  1019. switch (obj->type) {
  1020. case Object ::Type_EMPTY:
  1021. break; // do nothing
  1022. // supported object types
  1023. case Object ::Type_MESH: {
  1024. const size_t old = conv_data.meshes->size();
  1025. CheckActualType(obj->data.get(), "Mesh");
  1026. ConvertMesh(in, obj, static_cast<const Mesh *>(obj->data.get()), conv_data, conv_data.meshes);
  1027. if (conv_data.meshes->size() > old) {
  1028. node->mMeshes = new unsigned int[node->mNumMeshes = static_cast<unsigned int>(conv_data.meshes->size() - old)];
  1029. for (unsigned int i = 0; i < node->mNumMeshes; ++i) {
  1030. node->mMeshes[i] = static_cast<unsigned int>(i + old);
  1031. }
  1032. }
  1033. } break;
  1034. case Object ::Type_LAMP: {
  1035. CheckActualType(obj->data.get(), "Lamp");
  1036. aiLight *mesh = ConvertLight(in, obj, static_cast<const Lamp *>(obj->data.get()), conv_data);
  1037. if (mesh) {
  1038. conv_data.lights->push_back(mesh);
  1039. }
  1040. } break;
  1041. case Object ::Type_CAMERA: {
  1042. CheckActualType(obj->data.get(), "Camera");
  1043. aiCamera *mesh = ConvertCamera(in, obj, static_cast<const Camera *>(obj->data.get()), conv_data);
  1044. if (mesh) {
  1045. conv_data.cameras->push_back(mesh);
  1046. }
  1047. } break;
  1048. // unsupported object types / log, but do not break
  1049. case Object ::Type_CURVE:
  1050. NotSupportedObjectType(obj, "Curve");
  1051. break;
  1052. case Object ::Type_SURF:
  1053. NotSupportedObjectType(obj, "Surface");
  1054. break;
  1055. case Object ::Type_FONT:
  1056. NotSupportedObjectType(obj, "Font");
  1057. break;
  1058. case Object ::Type_MBALL:
  1059. NotSupportedObjectType(obj, "MetaBall");
  1060. break;
  1061. case Object ::Type_WAVE:
  1062. NotSupportedObjectType(obj, "Wave");
  1063. break;
  1064. case Object ::Type_LATTICE:
  1065. NotSupportedObjectType(obj, "Lattice");
  1066. break;
  1067. // invalid or unknown type
  1068. default:
  1069. break;
  1070. }
  1071. }
  1072. for (unsigned int x = 0; x < 4; ++x) {
  1073. for (unsigned int y = 0; y < 4; ++y) {
  1074. node->mTransformation[y][x] = obj->obmat[x][y];
  1075. }
  1076. }
  1077. aiMatrix4x4 m = parentTransform;
  1078. m = m.Inverse();
  1079. node->mTransformation = m * node->mTransformation;
  1080. if (children.size()) {
  1081. node->mNumChildren = static_cast<unsigned int>(children.size());
  1082. aiNode **nd = node->mChildren = new aiNode *[node->mNumChildren]();
  1083. for (const Object *nobj : children) {
  1084. *nd = ConvertNode(in, nobj, conv_data, node->mTransformation * parentTransform);
  1085. (*nd++)->mParent = node.get();
  1086. }
  1087. }
  1088. // apply modifiers
  1089. modifier_cache->ApplyModifiers(*node, conv_data, in, *obj);
  1090. return node.release();
  1091. }
  1092. #endif // ASSIMP_BUILD_NO_BLEND_IMPORTER