BlenderLoader.cpp 50 KB

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