FBXExporter.cpp 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2018, 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. #ifndef ASSIMP_BUILD_NO_EXPORT
  34. #ifndef ASSIMP_BUILD_NO_FBX_EXPORTER
  35. #include "FBXExporter.h"
  36. #include "FBXExportNode.h"
  37. #include "FBXExportProperty.h"
  38. #include "FBXCommon.h"
  39. #include <assimp/version.h> // aiGetVersion
  40. #include <assimp/IOSystem.hpp>
  41. #include <assimp/Exporter.hpp>
  42. #include <assimp/DefaultLogger.hpp>
  43. #include <assimp/StreamWriter.h> // StreamWriterLE
  44. #include <assimp/Exceptional.h> // DeadlyExportError
  45. #include <assimp/material.h> // aiTextureType
  46. #include <assimp/scene.h>
  47. #include <assimp/mesh.h>
  48. // Header files, standard library.
  49. #include <memory> // shared_ptr
  50. #include <string>
  51. #include <sstream> // stringstream
  52. #include <ctime> // localtime, tm_*
  53. #include <map>
  54. #include <set>
  55. #include <unordered_set>
  56. #include <iostream> // endl
  57. // RESOURCES:
  58. // https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  59. // https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  60. const double DEG = 57.29577951308232087679815481; // degrees per radian
  61. // some constants that we'll use for writing metadata
  62. namespace FBX {
  63. const std::string EXPORT_VERSION_STR = "7.4.0";
  64. const uint32_t EXPORT_VERSION_INT = 7400; // 7.4 == 2014/2015
  65. // FBX files have some hashed values that depend on the creation time field,
  66. // but for now we don't actually know how to generate these.
  67. // what we can do is set them to a known-working version.
  68. // this is the data that Blender uses in their FBX export process.
  69. const std::string GENERIC_CTIME = "1970-01-01 10:00:00:000";
  70. const std::string GENERIC_FILEID =
  71. "\x28\xb3\x2a\xeb\xb6\x24\xcc\xc2\xbf\xc8\xb0\x2a\xa9\x2b\xfc\xf1";
  72. const std::string GENERIC_FOOTID =
  73. "\xfa\xbc\xab\x09\xd0\xc8\xd4\x66\xb1\x76\xfb\x83\x1c\xf7\x26\x7e";
  74. const std::string FOOT_MAGIC =
  75. "\xf8\x5a\x8c\x6a\xde\xf5\xd9\x7e\xec\xe9\x0c\xe3\x75\x8f\x29\x0b";
  76. }
  77. using namespace Assimp;
  78. using namespace FBX;
  79. namespace Assimp {
  80. // ---------------------------------------------------------------------
  81. // Worker function for exporting a scene to binary FBX.
  82. // Prototyped and registered in Exporter.cpp
  83. void ExportSceneFBX (
  84. const char* pFile,
  85. IOSystem* pIOSystem,
  86. const aiScene* pScene,
  87. const ExportProperties* pProperties
  88. ){
  89. // initialize the exporter
  90. FBXExporter exporter(pScene, pProperties);
  91. // perform binary export
  92. exporter.ExportBinary(pFile, pIOSystem);
  93. }
  94. // ---------------------------------------------------------------------
  95. // Worker function for exporting a scene to ASCII FBX.
  96. // Prototyped and registered in Exporter.cpp
  97. /*void ExportSceneFBXA (
  98. const char* pFile,
  99. IOSystem* pIOSystem,
  100. const aiScene* pScene,
  101. const ExportProperties* pProperties
  102. ){
  103. // initialize the exporter
  104. FBXExporter exporter(pScene, pProperties);
  105. // perform ascii export
  106. exporter.ExportAscii(pFile, pIOSystem);
  107. }*/ // TODO
  108. } // end of namespace Assimp
  109. FBXExporter::FBXExporter (
  110. const aiScene* pScene,
  111. const ExportProperties* pProperties
  112. )
  113. : mScene(pScene)
  114. , mProperties(pProperties)
  115. {
  116. // will probably need to determine UIDs, connections, etc here.
  117. // basically anything that needs to be known
  118. // before we start writing sections to the stream.
  119. }
  120. void FBXExporter::ExportBinary (
  121. const char* pFile,
  122. IOSystem* pIOSystem
  123. ){
  124. // remember that we're exporting in binary mode
  125. binary = true;
  126. // we're not currently using these preferences,
  127. // but clang will cry about it if we never touch it.
  128. // TODO: some of these might be relevant to export
  129. (void)mProperties;
  130. // open the indicated file for writing (in binary mode)
  131. outfile.reset(pIOSystem->Open(pFile,"wb"));
  132. if (!outfile) {
  133. throw DeadlyExportError(
  134. "could not open output .fbx file: " + std::string(pFile)
  135. );
  136. }
  137. // first a binary-specific file header
  138. WriteBinaryHeader();
  139. // the rest of the file is in node entries.
  140. // we have to serialize each entry before we write to the output,
  141. // as the first thing we write is the byte offset of the _next_ entry.
  142. // Either that or we can skip back to write the offset when we finish.
  143. WriteAllNodes();
  144. // finally we have a binary footer to the file
  145. WriteBinaryFooter();
  146. // explicitly release file pointer,
  147. // so we don't have to rely on class destruction.
  148. outfile.reset();
  149. }
  150. void FBXExporter::ExportAscii (
  151. const char* pFile,
  152. IOSystem* pIOSystem
  153. ){
  154. // remember that we're exporting in ascii mode
  155. binary = false;
  156. // open the indicated file for writing in text mode
  157. outfile.reset(pIOSystem->Open(pFile,"wt"));
  158. if (!outfile) {
  159. throw DeadlyExportError(
  160. "could not open output .fbx file: " + std::string(pFile)
  161. );
  162. }
  163. // this isn't really necessary,
  164. // but the Autodesk FBX SDK puts a similar comment at the top of the file.
  165. // Theirs declares that the file copyright is owned by Autodesk...
  166. std::stringstream head;
  167. using std::endl;
  168. head << "; FBX " << EXPORT_VERSION_STR << " project file" << endl;
  169. head << "; Created by the Open Asset Import Library (Assimp)" << endl;
  170. head << "; http://assimp.org" << endl;
  171. head << "; -------------------------------------------------" << endl;
  172. head << endl;
  173. const std::string ascii_header = head.str();
  174. outfile->Write(ascii_header.c_str(), ascii_header.size(), 1);
  175. // write all the sections
  176. WriteAllNodes();
  177. // explicitly release file pointer,
  178. // so we don't have to rely on class destruction.
  179. outfile.reset();
  180. }
  181. void FBXExporter::WriteBinaryHeader()
  182. {
  183. // first a specific sequence of 23 bytes, always the same
  184. const char binary_header[24] = "Kaydara FBX Binary\x20\x20\x00\x1a\x00";
  185. outfile->Write(binary_header, 1, 23);
  186. // then FBX version number, "multiplied" by 1000, as little-endian uint32.
  187. // so 7.3 becomes 7300 == 0x841C0000, 7.4 becomes 7400 == 0xE81C0000, etc
  188. {
  189. StreamWriterLE outstream(outfile);
  190. outstream.PutU4(EXPORT_VERSION_INT);
  191. } // StreamWriter destructor writes the data to the file
  192. // after this the node data starts immediately
  193. // (probably with the FBXHEaderExtension node)
  194. }
  195. void FBXExporter::WriteBinaryFooter()
  196. {
  197. outfile->Write(NULL_RECORD.c_str(), NULL_RECORD.size(), 1);
  198. outfile->Write(GENERIC_FOOTID.c_str(), GENERIC_FOOTID.size(), 1);
  199. for (size_t i = 0; i < 4; ++i) {
  200. outfile->Write("\x00", 1, 1);
  201. }
  202. // here some padding is added for alignment to 16 bytes.
  203. // if already aligned, the full 16 bytes is added.
  204. size_t pos = outfile->Tell();
  205. size_t pad = 16 - (pos % 16);
  206. for (size_t i = 0; i < pad; ++i) {
  207. outfile->Write("\x00", 1, 1);
  208. }
  209. // now the file version again
  210. {
  211. StreamWriterLE outstream(outfile);
  212. outstream.PutU4(EXPORT_VERSION_INT);
  213. } // StreamWriter destructor writes the data to the file
  214. // and finally some binary footer added to all files
  215. for (size_t i = 0; i < 120; ++i) {
  216. outfile->Write("\x00", 1, 1);
  217. }
  218. outfile->Write(FOOT_MAGIC.c_str(), FOOT_MAGIC.size(), 1);
  219. }
  220. void FBXExporter::WriteAllNodes ()
  221. {
  222. // header
  223. // (and fileid, creation time, creator, if binary)
  224. WriteHeaderExtension();
  225. // global settings
  226. WriteGlobalSettings();
  227. // documents
  228. WriteDocuments();
  229. // references
  230. WriteReferences();
  231. // definitions
  232. WriteDefinitions();
  233. // objects
  234. WriteObjects();
  235. // connections
  236. WriteConnections();
  237. // WriteTakes? (deprecated since at least 2015 (fbx 7.4))
  238. }
  239. //FBXHeaderExtension top-level node
  240. void FBXExporter::WriteHeaderExtension ()
  241. {
  242. FBX::Node n("FBXHeaderExtension");
  243. StreamWriterLE outstream(outfile);
  244. // begin node
  245. n.Begin(outstream);
  246. // write properties
  247. // (none)
  248. // finish properties
  249. n.EndProperties(outstream, 0);
  250. // write child nodes
  251. FBX::Node::WritePropertyNode(
  252. "FBXHeaderVersion", int32_t(1003), outstream
  253. );
  254. FBX::Node::WritePropertyNode(
  255. "FBXVersion", int32_t(EXPORT_VERSION_INT), outstream
  256. );
  257. FBX::Node::WritePropertyNode(
  258. "EncryptionType", int32_t(0), outstream
  259. );
  260. FBX::Node CreationTimeStamp("CreationTimeStamp");
  261. time_t rawtime;
  262. time(&rawtime);
  263. struct tm * now = localtime(&rawtime);
  264. CreationTimeStamp.AddChild("Version", int32_t(1000));
  265. CreationTimeStamp.AddChild("Year", int32_t(now->tm_year + 1900));
  266. CreationTimeStamp.AddChild("Month", int32_t(now->tm_mon + 1));
  267. CreationTimeStamp.AddChild("Day", int32_t(now->tm_mday));
  268. CreationTimeStamp.AddChild("Hour", int32_t(now->tm_hour));
  269. CreationTimeStamp.AddChild("Minute", int32_t(now->tm_min));
  270. CreationTimeStamp.AddChild("Second", int32_t(now->tm_sec));
  271. CreationTimeStamp.AddChild("Millisecond", int32_t(0));
  272. CreationTimeStamp.Dump(outstream);
  273. std::stringstream creator;
  274. creator << "Open Asset Import Library (Assimp) " << aiGetVersionMajor()
  275. << "." << aiGetVersionMinor() << "." << aiGetVersionRevision();
  276. FBX::Node::WritePropertyNode("Creator", creator.str(), outstream);
  277. FBX::Node sceneinfo("SceneInfo");
  278. //sceneinfo.AddProperty("GlobalInfo" + FBX::SEPARATOR + "SceneInfo");
  279. // not sure if any of this is actually needed,
  280. // so just write an empty node for now.
  281. sceneinfo.Dump(outstream);
  282. // finish node
  283. n.End(outstream, true);
  284. // that's it for FBXHeaderExtension...
  285. // but binary files also need top-level FileID, CreationTime, Creator:
  286. std::vector<uint8_t> raw(GENERIC_FILEID.size());
  287. for (size_t i = 0; i < GENERIC_FILEID.size(); ++i) {
  288. raw[i] = uint8_t(GENERIC_FILEID[i]);
  289. }
  290. FBX::Node::WritePropertyNode("FileId", raw, outstream);
  291. FBX::Node::WritePropertyNode("CreationTime", GENERIC_CTIME, outstream);
  292. FBX::Node::WritePropertyNode("Creator", creator.str(), outstream);
  293. }
  294. void FBXExporter::WriteGlobalSettings ()
  295. {
  296. FBX::Node gs("GlobalSettings");
  297. gs.AddChild("Version", int32_t(1000));
  298. FBX::Node p("Properties70");
  299. p.AddP70int("UpAxis", 1);
  300. p.AddP70int("UpAxisSign", 1);
  301. p.AddP70int("FrontAxis", 2);
  302. p.AddP70int("FrontAxisSign", 1);
  303. p.AddP70int("CoordAxis", 0);
  304. p.AddP70int("CoordAxisSign", 1);
  305. p.AddP70int("OriginalUpAxis", 1);
  306. p.AddP70int("OriginalUpAxisSign", 1);
  307. p.AddP70double("UnitScaleFactor", 1.0);
  308. p.AddP70double("OriginalUnitScaleFactor", 1.0);
  309. p.AddP70color("AmbientColor", 0.0, 0.0, 0.0);
  310. p.AddP70string("DefaultCamera", "Producer Perspective");
  311. p.AddP70enum("TimeMode", 11);
  312. p.AddP70enum("TimeProtocol", 2);
  313. p.AddP70enum("SnapOnFrameMode", 0);
  314. p.AddP70time("TimeSpanStart", 0); // TODO: animation support
  315. p.AddP70time("TimeSpanStop", FBX::SECOND); // TODO: animation support
  316. p.AddP70double("CustomFrameRate", -1.0);
  317. p.AddP70("TimeMarker", "Compound", "", ""); // not sure what this is
  318. p.AddP70int("CurrentTimeMarker", -1);
  319. gs.AddChild(p);
  320. gs.Dump(outfile);
  321. }
  322. void FBXExporter::WriteDocuments ()
  323. {
  324. // not sure what the use of multiple documents would be,
  325. // or whether any end-application supports it
  326. FBX::Node docs("Documents");
  327. docs.AddChild("Count", int32_t(1));
  328. FBX::Node doc("Document");
  329. // generate uid
  330. int64_t uid = generate_uid();
  331. doc.AddProperties(uid, "", "Scene");
  332. FBX::Node p("Properties70");
  333. p.AddP70("SourceObject", "object", "", ""); // what is this even for?
  334. p.AddP70string("ActiveAnimStackName", ""); // should do this properly?
  335. doc.AddChild(p);
  336. // UID for root node in scene heirarchy.
  337. // always set to 0 in the case of a single document.
  338. // not sure what happens if more than one document exists,
  339. // but that won't matter to us as we're exporting a single scene.
  340. doc.AddChild("RootNode", int64_t(0));
  341. docs.AddChild(doc);
  342. docs.Dump(outfile);
  343. }
  344. void FBXExporter::WriteReferences ()
  345. {
  346. // always empty for now.
  347. // not really sure what this is for.
  348. FBX::Node n("References");
  349. n.Dump(outfile);
  350. }
  351. // ---------------------------------------------------------------
  352. // some internal helper functions used for writing the definitions
  353. // (before any actual data is written)
  354. // ---------------------------------------------------------------
  355. size_t count_nodes(const aiNode* n) {
  356. size_t count = 1;
  357. for (size_t i = 0; i < n->mNumChildren; ++i) {
  358. count += count_nodes(n->mChildren[i]);
  359. }
  360. return count;
  361. }
  362. bool has_phong_mat(const aiScene* scene)
  363. {
  364. // just search for any material with a shininess exponent
  365. for (size_t i = 0; i < scene->mNumMaterials; ++i) {
  366. aiMaterial* mat = scene->mMaterials[i];
  367. float shininess = 0;
  368. mat->Get(AI_MATKEY_SHININESS, shininess);
  369. if (shininess > 0) {
  370. return true;
  371. }
  372. }
  373. return false;
  374. }
  375. size_t count_images(const aiScene* scene) {
  376. std::unordered_set<std::string> images;
  377. aiString texpath;
  378. for (size_t i = 0; i < scene->mNumMaterials; ++i) {
  379. aiMaterial* mat = scene->mMaterials[i];
  380. for (
  381. size_t tt = aiTextureType_DIFFUSE;
  382. tt < aiTextureType_UNKNOWN;
  383. ++tt
  384. ){
  385. const aiTextureType textype = static_cast<aiTextureType>(tt);
  386. const size_t texcount = mat->GetTextureCount(textype);
  387. for (size_t j = 0; j < texcount; ++j) {
  388. mat->GetTexture(textype, j, &texpath);
  389. images.insert(std::string(texpath.C_Str()));
  390. }
  391. }
  392. }
  393. //for (auto &s : images) {
  394. // std::cout << "found image: " << s << std::endl;
  395. //}
  396. return images.size();
  397. }
  398. size_t count_textures(const aiScene* scene) {
  399. size_t count = 0;
  400. for (size_t i = 0; i < scene->mNumMaterials; ++i) {
  401. aiMaterial* mat = scene->mMaterials[i];
  402. for (
  403. size_t tt = aiTextureType_DIFFUSE;
  404. tt < aiTextureType_UNKNOWN;
  405. ++tt
  406. ){
  407. // TODO: handle layered textures
  408. if (mat->GetTextureCount(static_cast<aiTextureType>(tt)) > 0) {
  409. count += 1;
  410. }
  411. }
  412. }
  413. return count;
  414. }
  415. size_t count_deformers(const aiScene* scene) {
  416. size_t count = 0;
  417. for (size_t i = 0; i < scene->mNumMeshes; ++i) {
  418. const size_t n = scene->mMeshes[i]->mNumBones;
  419. if (n) {
  420. // 1 main deformer, 1 subdeformer per bone
  421. count += n + 1;
  422. }
  423. }
  424. return count;
  425. }
  426. void FBXExporter::WriteDefinitions ()
  427. {
  428. // basically this is just bookkeeping:
  429. // determining how many of each type of object there are
  430. // and specifying the base properties to use when otherwise unspecified.
  431. // we need to count the objects
  432. int32_t count;
  433. int32_t total_count = 0;
  434. // and store them
  435. std::vector<FBX::Node> object_nodes;
  436. FBX::Node n, pt, p;
  437. // GlobalSettings
  438. // this seems to always be here in Maya exports
  439. n = FBX::Node("ObjectType", Property("GlobalSettings"));
  440. count = 1;
  441. n.AddChild("Count", count);
  442. object_nodes.push_back(n);
  443. total_count += count;
  444. // AnimationStack / FbxAnimStack
  445. // this seems to always be here in Maya exports
  446. count = 0;
  447. if (count) {
  448. n = FBX::Node("ObjectType", Property("AnimationStack"));
  449. n.AddChild("Count", count);
  450. pt = FBX::Node("PropertyTemplate", Property("FbxAnimStack"));
  451. p = FBX::Node("Properties70");
  452. p.AddP70string("Description", "");
  453. p.AddP70time("LocalStart", 0);
  454. p.AddP70time("LocalStop", 0);
  455. p.AddP70time("ReferenceStart", 0);
  456. p.AddP70time("ReferenceStop", 0);
  457. pt.AddChild(p);
  458. n.AddChild(pt);
  459. object_nodes.push_back(n);
  460. total_count += count;
  461. }
  462. // AnimationLayer / FbxAnimLayer
  463. // this seems to always be here in Maya exports
  464. count = 0;
  465. if (count) {
  466. n = FBX::Node("ObjectType", Property("AnimationLayer"));
  467. n.AddChild("Count", count);
  468. pt = FBX::Node("PropertyTemplate", Property("FBXAnimLayer"));
  469. p = FBX::Node("Properties70");
  470. p.AddP70("Weight", "Number", "", "A", double(100));
  471. p.AddP70bool("Mute", 0);
  472. p.AddP70bool("Solo", 0);
  473. p.AddP70bool("Lock", 0);
  474. p.AddP70color("Color", 0.8, 0.8, 0.8);
  475. p.AddP70("BlendMode", "enum", "", "", int32_t(0));
  476. p.AddP70("RotationAccumulationMode", "enum", "", "", int32_t(0));
  477. p.AddP70("ScaleAccumulationMode", "enum", "", "", int32_t(0));
  478. p.AddP70("BlendModeBypass", "ULongLong", "", "", int64_t(0));
  479. pt.AddChild(p);
  480. n.AddChild(pt);
  481. object_nodes.push_back(n);
  482. total_count += count;
  483. }
  484. // NodeAttribute
  485. // this is completely absurd.
  486. // there can only be one "NodeAttribute" template,
  487. // but FbxSkeleton, FbxCamera, FbxLight all are "NodeAttributes".
  488. // so if only one exists we should set the template for that,
  489. // otherwise... we just pick one :/.
  490. // the others have to set all their properties every instance,
  491. // because there's no template.
  492. count = 1; // TODO: select properly
  493. if (count) {
  494. // FbxSkeleton
  495. n = FBX::Node("ObjectType", Property("NodeAttribute"));
  496. n.AddChild("Count", count);
  497. pt = FBX::Node("PropertyTemplate", Property("FbxSkeleton"));
  498. p = FBX::Node("Properties70");
  499. p.AddP70color("Color", 0.8, 0.8, 0.8);
  500. p.AddP70double("Size", 33.333333333333);
  501. p.AddP70("LimbLength", "double", "Number", "H", double(1));
  502. // note: not sure what the "H" flag is for - hidden?
  503. pt.AddChild(p);
  504. n.AddChild(pt);
  505. object_nodes.push_back(n);
  506. total_count += count;
  507. }
  508. // Model / FbxNode
  509. // <~~ node heirarchy
  510. count = count_nodes(mScene->mRootNode) - 1; // (not counting root node)
  511. if (count) {
  512. n = FBX::Node("ObjectType", Property("Model"));
  513. n.AddChild("Count", count);
  514. pt = FBX::Node("PropertyTemplate", Property("FbxNode"));
  515. p = FBX::Node("Properties70");
  516. p.AddP70enum("QuaternionInterpolate", 0);
  517. p.AddP70vector("RotationOffset", 0.0, 0.0, 0.0);
  518. p.AddP70vector("RotationPivot", 0.0, 0.0, 0.0);
  519. p.AddP70vector("ScalingOffset", 0.0, 0.0, 0.0);
  520. p.AddP70vector("ScalingPivot", 0.0, 0.0, 0.0);
  521. p.AddP70bool("TranslationActive", 0);
  522. p.AddP70vector("TranslationMin", 0.0, 0.0, 0.0);
  523. p.AddP70vector("TranslationMax", 0.0, 0.0, 0.0);
  524. p.AddP70bool("TranslationMinX", 0);
  525. p.AddP70bool("TranslationMinY", 0);
  526. p.AddP70bool("TranslationMinZ", 0);
  527. p.AddP70bool("TranslationMaxX", 0);
  528. p.AddP70bool("TranslationMaxY", 0);
  529. p.AddP70bool("TranslationMaxZ", 0);
  530. p.AddP70enum("RotationOrder", 0);
  531. p.AddP70bool("RotationSpaceForLimitOnly", 0);
  532. p.AddP70double("RotationStiffnessX", 0.0);
  533. p.AddP70double("RotationStiffnessY", 0.0);
  534. p.AddP70double("RotationStiffnessZ", 0.0);
  535. p.AddP70double("AxisLen", 10.0);
  536. p.AddP70vector("PreRotation", 0.0, 0.0, 0.0);
  537. p.AddP70vector("PostRotation", 0.0, 0.0, 0.0);
  538. p.AddP70bool("RotationActive", 0);
  539. p.AddP70vector("RotationMin", 0.0, 0.0, 0.0);
  540. p.AddP70vector("RotationMax", 0.0, 0.0, 0.0);
  541. p.AddP70bool("RotationMinX", 0);
  542. p.AddP70bool("RotationMinY", 0);
  543. p.AddP70bool("RotationMinZ", 0);
  544. p.AddP70bool("RotationMaxX", 0);
  545. p.AddP70bool("RotationMaxY", 0);
  546. p.AddP70bool("RotationMaxZ", 0);
  547. p.AddP70enum("InheritType", 0);
  548. p.AddP70bool("ScalingActive", 0);
  549. p.AddP70vector("ScalingMin", 0.0, 0.0, 0.0);
  550. p.AddP70vector("ScalingMax", 1.0, 1.0, 1.0);
  551. p.AddP70bool("ScalingMinX", 0);
  552. p.AddP70bool("ScalingMinY", 0);
  553. p.AddP70bool("ScalingMinZ", 0);
  554. p.AddP70bool("ScalingMaxX", 0);
  555. p.AddP70bool("ScalingMaxY", 0);
  556. p.AddP70bool("ScalingMaxZ", 0);
  557. p.AddP70vector("GeometricTranslation", 0.0, 0.0, 0.0);
  558. p.AddP70vector("GeometricRotation", 0.0, 0.0, 0.0);
  559. p.AddP70vector("GeometricScaling", 1.0, 1.0, 1.0);
  560. p.AddP70double("MinDampRangeX", 0.0);
  561. p.AddP70double("MinDampRangeY", 0.0);
  562. p.AddP70double("MinDampRangeZ", 0.0);
  563. p.AddP70double("MaxDampRangeX", 0.0);
  564. p.AddP70double("MaxDampRangeY", 0.0);
  565. p.AddP70double("MaxDampRangeZ", 0.0);
  566. p.AddP70double("MinDampStrengthX", 0.0);
  567. p.AddP70double("MinDampStrengthY", 0.0);
  568. p.AddP70double("MinDampStrengthZ", 0.0);
  569. p.AddP70double("MaxDampStrengthX", 0.0);
  570. p.AddP70double("MaxDampStrengthY", 0.0);
  571. p.AddP70double("MaxDampStrengthZ", 0.0);
  572. p.AddP70double("PreferedAngleX", 0.0);
  573. p.AddP70double("PreferedAngleY", 0.0);
  574. p.AddP70double("PreferedAngleZ", 0.0);
  575. p.AddP70("LookAtProperty", "object", "", "");
  576. p.AddP70("UpVectorProperty", "object", "", "");
  577. p.AddP70bool("Show", 1);
  578. p.AddP70bool("NegativePercentShapeSupport", 1);
  579. p.AddP70int("DefaultAttributeIndex", -1);
  580. p.AddP70bool("Freeze", 0);
  581. p.AddP70bool("LODBox", 0);
  582. p.AddP70(
  583. "Lcl Translation", "Lcl Translation", "", "A",
  584. double(0), double(0), double(0)
  585. );
  586. p.AddP70(
  587. "Lcl Rotation", "Lcl Rotation", "", "A",
  588. double(0), double(0), double(0)
  589. );
  590. p.AddP70(
  591. "Lcl Scaling", "Lcl Scaling", "", "A",
  592. double(1), double(1), double(1)
  593. );
  594. p.AddP70("Visibility", "Visibility", "", "A", double(1));
  595. p.AddP70(
  596. "Visibility Inheritance", "Visibility Inheritance", "", "",
  597. int32_t(1)
  598. );
  599. pt.AddChild(p);
  600. n.AddChild(pt);
  601. object_nodes.push_back(n);
  602. total_count += count;
  603. }
  604. // Geometry / FbxMesh
  605. // <~~ aiMesh
  606. count = mScene->mNumMeshes;
  607. if (count) {
  608. n = FBX::Node("ObjectType", Property("Geometry"));
  609. n.AddChild("Count", count);
  610. pt = FBX::Node("PropertyTemplate", Property("FbxMesh"));
  611. p = FBX::Node("Properties70");
  612. p.AddP70color("Color", 0, 0, 0);
  613. p.AddP70vector("BBoxMin", 0, 0, 0);
  614. p.AddP70vector("BBoxMax", 0, 0, 0);
  615. p.AddP70bool("Primary Visibility", 1);
  616. p.AddP70bool("Casts Shadows", 1);
  617. p.AddP70bool("Receive Shadows", 1);
  618. pt.AddChild(p);
  619. n.AddChild(pt);
  620. object_nodes.push_back(n);
  621. total_count += count;
  622. }
  623. // Material / FbxSurfacePhong, FbxSurfaceLambert, FbxSurfaceMaterial
  624. // <~~ aiMaterial
  625. // basically if there's any phong material this is defined as phong,
  626. // and otherwise lambert.
  627. // More complex materials cause a bare-bones FbxSurfaceMaterial definition
  628. // and are treated specially, as they're not really supported by FBX.
  629. // TODO: support Maya's Stingray PBS material
  630. count = mScene->mNumMaterials;
  631. if (count) {
  632. bool has_phong = has_phong_mat(mScene);
  633. n = FBX::Node("ObjectType", Property("Material"));
  634. n.AddChild("Count", count);
  635. pt = FBX::Node("PropertyTemplate");
  636. if (has_phong) {
  637. pt.AddProperty("FbxSurfacePhong");
  638. } else {
  639. pt.AddProperty("FbxSurfaceLambert");
  640. }
  641. p = FBX::Node("Properties70");
  642. if (has_phong) {
  643. p.AddP70string("ShadingModel", "Phong");
  644. } else {
  645. p.AddP70string("ShadingModel", "Lambert");
  646. }
  647. p.AddP70bool("MultiLayer", 0);
  648. p.AddP70colorA("EmissiveColor", 0.0, 0.0, 0.0);
  649. p.AddP70numberA("EmissiveFactor", 1.0);
  650. p.AddP70colorA("AmbientColor", 0.2, 0.2, 0.2);
  651. p.AddP70numberA("AmbientFactor", 1.0);
  652. p.AddP70colorA("DiffuseColor", 0.8, 0.8, 0.8);
  653. p.AddP70numberA("DiffuseFactor", 1.0);
  654. p.AddP70vector("Bump", 0.0, 0.0, 0.0);
  655. p.AddP70vector("NormalMap", 0.0, 0.0, 0.0);
  656. p.AddP70double("BumpFactor", 1.0);
  657. p.AddP70colorA("TransparentColor", 0.0, 0.0, 0.0);
  658. p.AddP70numberA("TransparencyFactor", 0.0);
  659. p.AddP70color("DisplacementColor", 0.0, 0.0, 0.0);
  660. p.AddP70double("DisplacementFactor", 1.0);
  661. p.AddP70color("VectorDisplacementColor", 0.0, 0.0, 0.0);
  662. p.AddP70double("VectorDisplacementFactor", 1.0);
  663. if (has_phong) {
  664. p.AddP70colorA("SpecularColor", 0.2, 0.2, 0.2);
  665. p.AddP70numberA("SpecularFactor", 1.0);
  666. p.AddP70numberA("ShininessExponent", 20.0);
  667. p.AddP70colorA("ReflectionColor", 0.0, 0.0, 0.0);
  668. p.AddP70numberA("ReflectionFactor", 1.0);
  669. }
  670. pt.AddChild(p);
  671. n.AddChild(pt);
  672. object_nodes.push_back(n);
  673. total_count += count;
  674. }
  675. // Video / FbxVideo
  676. // one for each image file.
  677. count = count_images(mScene);
  678. if (count) {
  679. n = FBX::Node("ObjectType", Property("Video"));
  680. n.AddChild("Count", count);
  681. pt = FBX::Node("PropertyTemplate", Property("FbxVideo"));
  682. p = FBX::Node("Properties70");
  683. p.AddP70bool("ImageSequence", 0);
  684. p.AddP70int("ImageSequenceOffset", 0);
  685. p.AddP70double("FrameRate", 0.0);
  686. p.AddP70int("LastFrame", 0);
  687. p.AddP70int("Width", 0);
  688. p.AddP70int("Height", 0);
  689. p.AddP70("Path", "KString", "XRefUrl", "", "");
  690. p.AddP70int("StartFrame", 0);
  691. p.AddP70int("StopFrame", 0);
  692. p.AddP70double("PlaySpeed", 0.0);
  693. p.AddP70time("Offset", 0);
  694. p.AddP70enum("InterlaceMode", 0);
  695. p.AddP70bool("FreeRunning", 0);
  696. p.AddP70bool("Loop", 0);
  697. p.AddP70enum("AccessMode", 0);
  698. pt.AddChild(p);
  699. n.AddChild(pt);
  700. object_nodes.push_back(n);
  701. total_count += count;
  702. }
  703. // Texture / FbxFileTexture
  704. // <~~ aiTexture
  705. count = count_textures(mScene);
  706. if (count) {
  707. n = FBX::Node("ObjectType", Property("Texture"));
  708. n.AddChild("Count", count);
  709. pt = FBX::Node("PropertyTemplate", Property("FbxFileTexture"));
  710. p = FBX::Node("Properties70");
  711. p.AddP70enum("TextureTypeUse", 0);
  712. p.AddP70numberA("Texture alpha", 1.0);
  713. p.AddP70enum("CurrentMappingType", 0);
  714. p.AddP70enum("WrapModeU", 0);
  715. p.AddP70enum("WrapModeV", 0);
  716. p.AddP70bool("UVSwap", 0);
  717. p.AddP70bool("PremultiplyAlpha", 1);
  718. p.AddP70vectorA("Translation", 0.0, 0.0, 0.0);
  719. p.AddP70vectorA("Rotation", 0.0, 0.0, 0.0);
  720. p.AddP70vectorA("Scaling", 1.0, 1.0, 1.0);
  721. p.AddP70vector("TextureRotationPivot", 0.0, 0.0, 0.0);
  722. p.AddP70vector("TextureScalingPivot", 0.0, 0.0, 0.0);
  723. p.AddP70enum("CurrentTextureBlendMode", 1);
  724. p.AddP70string("UVSet", "default");
  725. p.AddP70bool("UseMaterial", 0);
  726. p.AddP70bool("UseMipMap", 0);
  727. pt.AddChild(p);
  728. n.AddChild(pt);
  729. object_nodes.push_back(n);
  730. total_count += count;
  731. }
  732. // AnimationCurveNode / FbxAnimCurveNode
  733. count = 0;
  734. if (count) {
  735. n = FBX::Node("ObjectType", Property("AnimationCurveNode"));
  736. n.AddChild("Count", count);
  737. pt = FBX::Node("PropertyTemplate", Property("FbxAnimCurveNode"));
  738. p = FBX::Node("Properties70");
  739. p.AddP70("d", "Compound", "", "");
  740. pt.AddChild(p);
  741. n.AddChild(pt);
  742. object_nodes.push_back(n);
  743. total_count += count;
  744. }
  745. // Pose
  746. count = 0;
  747. for (size_t i = 0; i < mScene->mNumMeshes; ++i) {
  748. aiMesh* mesh = mScene->mMeshes[i];
  749. if (mesh->HasBones()) { ++count; }
  750. }
  751. if (count) {
  752. n = FBX::Node("ObjectType", Property("Pose"));
  753. n.AddChild("Count", count);
  754. object_nodes.push_back(n);
  755. total_count += count;
  756. }
  757. // Deformer
  758. count = count_deformers(mScene);
  759. if (count) {
  760. n = FBX::Node("ObjectType", Property("Deformer"));
  761. n.AddChild("Count", count);
  762. object_nodes.push_back(n);
  763. total_count += count;
  764. }
  765. // (template)
  766. count = 0;
  767. if (count) {
  768. n = FBX::Node("ObjectType", Property(""));
  769. n.AddChild("Count", count);
  770. pt = FBX::Node("PropertyTemplate", Property(""));
  771. p = FBX::Node("Properties70");
  772. pt.AddChild(p);
  773. n.AddChild(pt);
  774. object_nodes.push_back(n);
  775. total_count += count;
  776. }
  777. // now write it all
  778. FBX::Node defs("Definitions");
  779. defs.AddChild("Version", int32_t(100));
  780. defs.AddChild("Count", int32_t(total_count));
  781. for (auto &n : object_nodes) { defs.AddChild(n); }
  782. defs.Dump(outfile);
  783. }
  784. // -------------------------------------------------------------------
  785. // some internal helper functions used for writing the objects section
  786. // (which holds the actual data)
  787. // -------------------------------------------------------------------
  788. aiNode* get_node_for_mesh(unsigned int meshIndex, aiNode* node)
  789. {
  790. for (size_t i = 0; i < node->mNumMeshes; ++i) {
  791. if (node->mMeshes[i] == meshIndex) {
  792. return node;
  793. }
  794. }
  795. for (size_t i = 0; i < node->mNumChildren; ++i) {
  796. aiNode* ret = get_node_for_mesh(meshIndex, node->mChildren[i]);
  797. if (ret) { return ret; }
  798. }
  799. return nullptr;
  800. }
  801. aiMatrix4x4 get_world_transform(const aiNode* node, const aiScene* scene)
  802. {
  803. std::vector<const aiNode*> node_chain;
  804. while (node != scene->mRootNode) {
  805. node_chain.push_back(node);
  806. node = node->mParent;
  807. }
  808. aiMatrix4x4 transform;
  809. for (auto n = node_chain.rbegin(); n != node_chain.rend(); ++n) {
  810. transform *= (*n)->mTransformation;
  811. }
  812. return transform;
  813. }
  814. void FBXExporter::WriteObjects ()
  815. {
  816. // numbers should match those given in definitions! make sure to check
  817. StreamWriterLE outstream(outfile);
  818. FBX::Node object_node("Objects");
  819. object_node.Begin(outstream);
  820. object_node.EndProperties(outstream);
  821. // geometry (aiMesh)
  822. mesh_uids.clear();
  823. for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  824. // it's all about this mesh
  825. aiMesh* m = mScene->mMeshes[mi];
  826. // start the node record
  827. FBX::Node n("Geometry");
  828. int64_t uid = generate_uid();
  829. mesh_uids.push_back(uid);
  830. n.AddProperty(uid);
  831. n.AddProperty(FBX::SEPARATOR + "Geometry");
  832. n.AddProperty("Mesh");
  833. n.Begin(outstream);
  834. n.DumpProperties(outstream);
  835. n.EndProperties(outstream);
  836. // output vertex data - each vertex should be unique (probably)
  837. std::vector<double> flattened_vertices;
  838. // index of original vertex in vertex data vector
  839. std::vector<int32_t> vertex_indices;
  840. // map of vertex value to its index in the data vector
  841. std::map<aiVector3D,size_t> index_by_vertex_value;
  842. size_t index = 0;
  843. for (size_t vi = 0; vi < m->mNumVertices; ++vi) {
  844. aiVector3D vtx = m->mVertices[vi];
  845. auto elem = index_by_vertex_value.find(vtx);
  846. if (elem == index_by_vertex_value.end()) {
  847. vertex_indices.push_back(index);
  848. index_by_vertex_value[vtx] = index;
  849. flattened_vertices.push_back(vtx[0]);
  850. flattened_vertices.push_back(vtx[1]);
  851. flattened_vertices.push_back(vtx[2]);
  852. ++index;
  853. } else {
  854. vertex_indices.push_back(elem->second);
  855. }
  856. }
  857. FBX::Node::WritePropertyNode(
  858. "Vertices", flattened_vertices, outstream
  859. );
  860. // output polygon data as a flattened array of vertex indices.
  861. // the last vertex index of each polygon is negated and - 1
  862. std::vector<int32_t> polygon_data;
  863. for (size_t fi = 0; fi < m->mNumFaces; ++fi) {
  864. const aiFace &f = m->mFaces[fi];
  865. for (size_t pvi = 0; pvi < f.mNumIndices - 1; ++pvi) {
  866. polygon_data.push_back(vertex_indices[f.mIndices[pvi]]);
  867. }
  868. polygon_data.push_back(
  869. -1 - vertex_indices[f.mIndices[f.mNumIndices-1]]
  870. );
  871. }
  872. FBX::Node::WritePropertyNode(
  873. "PolygonVertexIndex", polygon_data, outstream
  874. );
  875. // here could be edges but they're insane.
  876. // it's optional anyway, so let's ignore it.
  877. FBX::Node::WritePropertyNode(
  878. "GeometryVersion", int32_t(124), outstream
  879. );
  880. // normals, if any
  881. if (m->HasNormals()) {
  882. FBX::Node normals("LayerElementNormal", Property(int32_t(0)));
  883. normals.Begin(outstream);
  884. normals.DumpProperties(outstream);
  885. normals.EndProperties(outstream);
  886. FBX::Node::WritePropertyNode("Version", int32_t(101), outstream);
  887. FBX::Node::WritePropertyNode("Name", "", outstream);
  888. FBX::Node::WritePropertyNode(
  889. "MappingInformationType", "ByPolygonVertex", outstream
  890. );
  891. // TODO: vertex-normals or indexed normals when appropriate
  892. FBX::Node::WritePropertyNode(
  893. "ReferenceInformationType", "Direct", outstream
  894. );
  895. std::vector<double> normal_data;
  896. normal_data.reserve(3 * polygon_data.size());
  897. for (size_t fi = 0; fi < m->mNumFaces; ++fi) {
  898. const aiFace &f = m->mFaces[fi];
  899. for (size_t pvi = 0; pvi < f.mNumIndices; ++pvi) {
  900. const aiVector3D &n = m->mNormals[f.mIndices[pvi]];
  901. normal_data.push_back(n.x);
  902. normal_data.push_back(n.y);
  903. normal_data.push_back(n.z);
  904. }
  905. }
  906. FBX::Node::WritePropertyNode("Normals", normal_data, outstream);
  907. // note: version 102 has a NormalsW also... not sure what it is,
  908. // so we can stick with version 101 for now.
  909. normals.End(outstream, true);
  910. }
  911. // uvs, if any
  912. for (size_t uvi = 0; uvi < m->GetNumUVChannels(); ++uvi) {
  913. if (m->mNumUVComponents[uvi] > 2) {
  914. // FBX only supports 2-channel UV maps...
  915. // or at least i'm not sure how to indicate a different number
  916. std::stringstream err;
  917. err << "Only 2-channel UV maps supported by FBX,";
  918. err << " but mesh " << mi;
  919. if (m->mName.length) {
  920. err << " (" << m->mName.C_Str() << ")";
  921. }
  922. err << " UV map " << uvi;
  923. err << " has " << m->mNumUVComponents[uvi];
  924. err << " components! Data will be preserved,";
  925. err << " but may be incorrectly interpreted on load.";
  926. DefaultLogger::get()->warn(err.str());
  927. }
  928. FBX::Node uv("LayerElementUV", Property(int32_t(uvi)));
  929. uv.Begin(outstream);
  930. uv.DumpProperties(outstream);
  931. uv.EndProperties(outstream);
  932. FBX::Node::WritePropertyNode("Version", int32_t(101), outstream);
  933. // it doesn't seem like assimp keeps the uv map name,
  934. // so just leave it blank.
  935. FBX::Node::WritePropertyNode("Name", "", outstream);
  936. FBX::Node::WritePropertyNode(
  937. "MappingInformationType", "ByPolygonVertex", outstream
  938. );
  939. FBX::Node::WritePropertyNode(
  940. "ReferenceInformationType", "IndexToDirect", outstream
  941. );
  942. std::vector<double> uv_data;
  943. std::vector<int32_t> uv_indices;
  944. std::map<aiVector3D,int32_t> index_by_uv;
  945. size_t index = 0;
  946. for (size_t fi = 0; fi < m->mNumFaces; ++fi) {
  947. const aiFace &f = m->mFaces[fi];
  948. for (size_t pvi = 0; pvi < f.mNumIndices; ++pvi) {
  949. const aiVector3D &uv =
  950. m->mTextureCoords[uvi][f.mIndices[pvi]];
  951. auto elem = index_by_uv.find(uv);
  952. if (elem == index_by_uv.end()) {
  953. index_by_uv[uv] = index;
  954. uv_indices.push_back(index);
  955. for (size_t x = 0; x < m->mNumUVComponents[uvi]; ++x) {
  956. uv_data.push_back(uv[x]);
  957. }
  958. ++index;
  959. } else {
  960. uv_indices.push_back(elem->second);
  961. }
  962. }
  963. }
  964. FBX::Node::WritePropertyNode("UV", uv_data, outstream);
  965. FBX::Node::WritePropertyNode("UVIndex", uv_indices, outstream);
  966. uv.End(outstream, true);
  967. }
  968. // i'm not really sure why this material section exists,
  969. // as the material is linked via "Connections".
  970. // it seems to always have the same "0" value.
  971. FBX::Node mat("LayerElementMaterial", Property(int32_t(0)));
  972. mat.AddChild("Version", int32_t(101));
  973. mat.AddChild("Name", "");
  974. mat.AddChild("MappingInformationType", "AllSame");
  975. mat.AddChild("ReferenceInformationType", "IndexToDirect");
  976. std::vector<int32_t> mat_indices = {0};
  977. mat.AddChild("Materials", mat_indices);
  978. mat.Dump(outstream);
  979. // finally we have the layer specifications,
  980. // which select the normals / UV set / etc to use.
  981. // TODO: handle multiple uv sets correctly?
  982. FBX::Node layer("Layer", Property(int32_t(0)));
  983. layer.AddChild("Version", int32_t(100));
  984. FBX::Node le("LayerElement");
  985. le.AddChild("Type", "LayerElementNormal");
  986. le.AddChild("TypedIndex", int32_t(0));
  987. layer.AddChild(le);
  988. le = FBX::Node("LayerElement");
  989. le.AddChild("Type", "LayerElementMaterial");
  990. le.AddChild("TypedIndex", int32_t(0));
  991. layer.AddChild(le);
  992. le = FBX::Node("LayerElement");
  993. le.AddChild("Type", "LayerElementUV");
  994. le.AddChild("TypedIndex", int32_t(0));
  995. layer.AddChild(le);
  996. layer.Dump(outstream);
  997. // finish the node record
  998. n.End(outstream, true);
  999. }
  1000. // aiMaterial
  1001. material_uids.clear();
  1002. for (size_t i = 0; i < mScene->mNumMaterials; ++i) {
  1003. // it's all about this material
  1004. aiMaterial* m = mScene->mMaterials[i];
  1005. // these are used to recieve material data
  1006. float f; aiColor3D c;
  1007. // start the node record
  1008. FBX::Node n("Material");
  1009. int64_t uid = generate_uid();
  1010. material_uids.push_back(uid);
  1011. n.AddProperty(uid);
  1012. aiString name;
  1013. m->Get(AI_MATKEY_NAME, name);
  1014. n.AddProperty(name.C_Str() + FBX::SEPARATOR + "Material");
  1015. n.AddProperty("");
  1016. n.AddChild("Version", int32_t(102));
  1017. f = 0;
  1018. m->Get(AI_MATKEY_SHININESS, f);
  1019. bool phong = (f > 0);
  1020. if (phong) {
  1021. n.AddChild("ShadingModel", "phong");
  1022. } else {
  1023. n.AddChild("ShadingModel", "lambert");
  1024. }
  1025. n.AddChild("MultiLayer", int32_t(0));
  1026. FBX::Node p("Properties70");
  1027. // materials exported using the FBX SDK have two sets of fields.
  1028. // there are the properties specified in the PropertyTemplate,
  1029. // which are those supported by the modernFBX SDK,
  1030. // and an extra set of properties with simpler names.
  1031. // The extra properties are a legacy material system from pre-2009.
  1032. //
  1033. // In the modern system, each property has "color" and "factor".
  1034. // Generally the interpretation of these seems to be
  1035. // that the colour is multiplied by the factor before use,
  1036. // but this is not always clear-cut.
  1037. //
  1038. // Usually assimp only stores the colour,
  1039. // so we can just leave the factors at the default "1.0".
  1040. // first we can export the "standard" properties
  1041. if (m->Get(AI_MATKEY_COLOR_AMBIENT, c) == aiReturn_SUCCESS) {
  1042. p.AddP70colorA("AmbientColor", c.r, c.g, c.b);
  1043. //p.AddP70numberA("AmbientFactor", 1.0);
  1044. }
  1045. if (m->Get(AI_MATKEY_COLOR_DIFFUSE, c) == aiReturn_SUCCESS) {
  1046. p.AddP70colorA("DiffuseColor", c.r, c.g, c.b);
  1047. //p.AddP70numberA("DiffuseFactor", 1.0);
  1048. }
  1049. if (m->Get(AI_MATKEY_COLOR_TRANSPARENT, c) == aiReturn_SUCCESS) {
  1050. // "TransparentColor" / "TransparencyFactor"...
  1051. // thanks FBX, for your insightful interpretation of consistency
  1052. p.AddP70colorA("TransparentColor", c.r, c.g, c.b);
  1053. // TransparencyFactor defaults to 0.0, so set it to 1.0.
  1054. // note: Maya always sets this to 1.0,
  1055. // so we can't use it sensibly as "Opacity".
  1056. // In stead we rely on the legacy "Opacity" value, below.
  1057. // Blender also relies on "Opacity" not "TransparencyFactor",
  1058. // probably for a similar reason.
  1059. p.AddP70numberA("TransparencyFactor", 1.0);
  1060. }
  1061. if (m->Get(AI_MATKEY_COLOR_REFLECTIVE, c) == aiReturn_SUCCESS) {
  1062. p.AddP70colorA("ReflectionColor", c.r, c.g, c.b);
  1063. }
  1064. if (m->Get(AI_MATKEY_REFLECTIVITY, f) == aiReturn_SUCCESS) {
  1065. p.AddP70numberA("ReflectionFactor", f);
  1066. }
  1067. if (phong) {
  1068. if (m->Get(AI_MATKEY_COLOR_SPECULAR, c) == aiReturn_SUCCESS) {
  1069. p.AddP70colorA("SpecularColor", c.r, c.g, c.b);
  1070. }
  1071. if (m->Get(AI_MATKEY_SHININESS_STRENGTH, f) == aiReturn_SUCCESS) {
  1072. p.AddP70numberA("ShininessFactor", f);
  1073. }
  1074. if (m->Get(AI_MATKEY_SHININESS, f) == aiReturn_SUCCESS) {
  1075. p.AddP70numberA("ShininessExponent", f);
  1076. }
  1077. if (m->Get(AI_MATKEY_REFLECTIVITY, f) == aiReturn_SUCCESS) {
  1078. p.AddP70numberA("ReflectionFactor", f);
  1079. }
  1080. }
  1081. // Now the legacy system.
  1082. // For safety let's include it.
  1083. // thrse values don't exist in the property template,
  1084. // and usualy are completely ignored when loading.
  1085. // One notable exception is the "Opacity" property,
  1086. // which Blender uses as (1.0 - alpha).
  1087. c.r = 0; c.g = 0; c.b = 0;
  1088. m->Get(AI_MATKEY_COLOR_EMISSIVE, c);
  1089. p.AddP70vector("Emissive", c.r, c.g, c.b);
  1090. c.r = 0.2; c.g = 0.2; c.b = 0.2;
  1091. m->Get(AI_MATKEY_COLOR_AMBIENT, c);
  1092. p.AddP70vector("Ambient", c.r, c.g, c.b);
  1093. c.r = 0.8; c.g = 0.8; c.b = 0.8;
  1094. m->Get(AI_MATKEY_COLOR_DIFFUSE, c);
  1095. p.AddP70vector("Diffuse", c.r, c.g, c.b);
  1096. // The FBX SDK determines "Opacity" from transparency colour (RGB)
  1097. // and factor (F) as: O = (1.0 - F * ((R + G + B) / 3)).
  1098. // However we actually have an opacity value,
  1099. // so we should take it from AI_MATKEY_OPACITY if possible.
  1100. // It might make more sense to use TransparencyFactor,
  1101. // but Blender actually loads "Opacity" correctly, so let's use it.
  1102. f = 1.0;
  1103. if (m->Get(AI_MATKEY_COLOR_TRANSPARENT, c) == aiReturn_SUCCESS) {
  1104. f = 1.0 - ((c.r + c.g + c.b) / 3);
  1105. }
  1106. m->Get(AI_MATKEY_OPACITY, f);
  1107. p.AddP70double("Opacity", f);
  1108. if (phong) {
  1109. // specular color is multiplied by shininess_strength
  1110. c.r = 0.2; c.g = 0.2; c.b = 0.2;
  1111. m->Get(AI_MATKEY_COLOR_SPECULAR, c);
  1112. f = 1.0;
  1113. m->Get(AI_MATKEY_SHININESS_STRENGTH, f);
  1114. p.AddP70vector("Specular", f*c.r, f*c.g, f*c.b);
  1115. f = 20.0;
  1116. m->Get(AI_MATKEY_SHININESS, f);
  1117. p.AddP70double("Shininess", f);
  1118. // Legacy "Reflectivity" is F*F*((R+G+B)/3),
  1119. // where F is the proportion of light reflected (AKA reflectivity),
  1120. // and RGB is the reflective colour of the material.
  1121. // No idea why, but we might as well set it the same way.
  1122. f = 0.0;
  1123. m->Get(AI_MATKEY_REFLECTIVITY, f);
  1124. c.r = 1.0, c.g = 1.0, c.b = 1.0;
  1125. m->Get(AI_MATKEY_COLOR_REFLECTIVE, c);
  1126. p.AddP70double("Reflectivity", f*f*((c.r+c.g+c.b)/3.0));
  1127. }
  1128. n.AddChild(p);
  1129. n.Dump(outstream);
  1130. }
  1131. // we need to look up all the images we're using,
  1132. // so we can generate uids, and eliminate duplicates.
  1133. std::map<std::string, int64_t> uid_by_image;
  1134. for (size_t i = 0; i < mScene->mNumMaterials; ++i) {
  1135. aiString texpath;
  1136. aiMaterial* mat = mScene->mMaterials[i];
  1137. for (
  1138. size_t tt = aiTextureType_DIFFUSE;
  1139. tt < aiTextureType_UNKNOWN;
  1140. ++tt
  1141. ){
  1142. const aiTextureType textype = static_cast<aiTextureType>(tt);
  1143. const size_t texcount = mat->GetTextureCount(textype);
  1144. for (size_t j = 0; j < texcount; ++j) {
  1145. mat->GetTexture(textype, j, &texpath);
  1146. const std::string texstring = texpath.C_Str();
  1147. auto elem = uid_by_image.find(texstring);
  1148. if (elem == uid_by_image.end()) {
  1149. uid_by_image[texstring] = generate_uid();
  1150. }
  1151. }
  1152. }
  1153. }
  1154. // FbxVideo - stores images used by textures.
  1155. for (const auto &it : uid_by_image) {
  1156. if (it.first.compare(0, 1, "*") == 0) {
  1157. // TODO: embedded textures
  1158. continue;
  1159. }
  1160. FBX::Node n("Video");
  1161. const int64_t& uid = it.second;
  1162. const std::string name = ""; // TODO: ... name???
  1163. n.AddProperties(uid, name + FBX::SEPARATOR + "Video", "Clip");
  1164. n.AddChild("Type", "Clip");
  1165. FBX::Node p("Properties70");
  1166. // TODO: get full path... relative path... etc... ugh...
  1167. // for now just use the same path for everything,
  1168. // and hopefully one of them will work out.
  1169. const std::string& path = it.first;
  1170. p.AddP70("Path", "KString", "XRefUrl", "", path);
  1171. n.AddChild(p);
  1172. n.AddChild("UseMipMap", int32_t(0));
  1173. n.AddChild("Filename", path);
  1174. n.AddChild("RelativeFilename", path);
  1175. n.Dump(outstream);
  1176. }
  1177. // Textures
  1178. // referenced by material_index/texture_type pairs.
  1179. std::map<std::pair<size_t,size_t>,int64_t> texture_uids;
  1180. const std::map<aiTextureType,std::string> prop_name_by_tt = {
  1181. {aiTextureType_DIFFUSE, "DiffuseColor"},
  1182. {aiTextureType_SPECULAR, "SpecularColor"},
  1183. {aiTextureType_AMBIENT, "AmbientColor"},
  1184. {aiTextureType_EMISSIVE, "EmissiveColor"},
  1185. {aiTextureType_HEIGHT, "Bump"},
  1186. {aiTextureType_NORMALS, "NormalMap"},
  1187. {aiTextureType_SHININESS, "ShininessExponent"},
  1188. {aiTextureType_OPACITY, "TransparentColor"},
  1189. {aiTextureType_DISPLACEMENT, "DisplacementColor"},
  1190. //{aiTextureType_LIGHTMAP, "???"},
  1191. {aiTextureType_REFLECTION, "ReflectionColor"}
  1192. //{aiTextureType_UNKNOWN, ""}
  1193. };
  1194. for (size_t i = 0; i < mScene->mNumMaterials; ++i) {
  1195. // textures are attached to materials
  1196. aiMaterial* mat = mScene->mMaterials[i];
  1197. int64_t material_uid = material_uids[i];
  1198. for (
  1199. size_t j = aiTextureType_DIFFUSE;
  1200. j < aiTextureType_UNKNOWN;
  1201. ++j
  1202. ) {
  1203. const aiTextureType tt = static_cast<aiTextureType>(j);
  1204. size_t n = mat->GetTextureCount(tt);
  1205. if (n < 1) { // no texture of this type
  1206. continue;
  1207. }
  1208. if (n > 1) {
  1209. // TODO: multilayer textures
  1210. std::stringstream err;
  1211. err << "Multilayer textures not supported (for now),";
  1212. err << " skipping texture type " << j;
  1213. err << " of material " << i;
  1214. DefaultLogger::get()->warn(err.str());
  1215. }
  1216. // get image path for this (single-image) texture
  1217. aiString tpath;
  1218. if (mat->GetTexture(tt, 0, &tpath) != aiReturn_SUCCESS) {
  1219. std::stringstream err;
  1220. err << "Failed to get texture 0 for texture of type " << tt;
  1221. err << " on material " << i;
  1222. err << ", however GetTextureCount returned 1.";
  1223. throw DeadlyExportError(err.str());
  1224. }
  1225. const std::string texture_path(tpath.C_Str());
  1226. // get connected image uid
  1227. auto elem = uid_by_image.find(texture_path);
  1228. if (elem == uid_by_image.end()) {
  1229. // this should never happen
  1230. std::stringstream err;
  1231. err << "Failed to find video element for texture with path";
  1232. err << " \"" << texture_path << "\"";
  1233. err << ", type " << j << ", material " << i;
  1234. throw DeadlyExportError(err.str());
  1235. }
  1236. const int64_t image_uid = elem->second;
  1237. // get the name of the material property to connect to
  1238. auto elem2 = prop_name_by_tt.find(tt);
  1239. if (elem2 == prop_name_by_tt.end()) {
  1240. // don't know how to handle this type of texture,
  1241. // so skip it.
  1242. std::stringstream err;
  1243. err << "Not sure how to handle texture of type " << j;
  1244. err << " on material " << i;
  1245. err << ", skipping...";
  1246. DefaultLogger::get()->warn(err.str());
  1247. continue;
  1248. }
  1249. const std::string& prop_name = elem2->second;
  1250. // generate a uid for this texture
  1251. const int64_t texture_uid = generate_uid();
  1252. // link the texture to the material
  1253. FBX::Node c("C");
  1254. c.AddProperties("OP", texture_uid, material_uid, prop_name);
  1255. connections.push_back(c);
  1256. // link the image data to the texture
  1257. c = FBX::Node("C");
  1258. c.AddProperties("OO", image_uid, texture_uid);
  1259. connections.push_back(c);
  1260. // now write the actual texture node
  1261. FBX::Node tnode("Texture");
  1262. // TODO: some way to determine texture name?
  1263. const std::string texture_name = "" + FBX::SEPARATOR + "Texture";
  1264. tnode.AddProperties(texture_uid, texture_name, "");
  1265. // there really doesn't seem to be a better type than this:
  1266. tnode.AddChild("Type", "TextureVideoClip");
  1267. tnode.AddChild("Version", int32_t(202));
  1268. tnode.AddChild("TextureName", texture_name);
  1269. FBX::Node p("Properties70");
  1270. p.AddP70enum("CurrentTextureBlendMode", 0); // TODO: verify
  1271. //p.AddP70string("UVSet", ""); // TODO: how should this work?
  1272. p.AddP70bool("UseMaterial", 1);
  1273. tnode.AddChild(p);
  1274. // can't easily detrmine which texture path will be correct,
  1275. // so just store what we have in every field.
  1276. // these being incorrect is a common problem with FBX anyway.
  1277. tnode.AddChild("FileName", texture_path);
  1278. tnode.AddChild("RelativeFilename", texture_path);
  1279. tnode.AddChild("ModelUVTranslation", double(0.0), double(0.0));
  1280. tnode.AddChild("ModelUVScaling", double(1.0), double(1.0));
  1281. tnode.AddChild("Texture_Alpha_Soutce", "None");
  1282. tnode.AddChild(
  1283. "Cropping", int32_t(0), int32_t(0), int32_t(0), int32_t(0)
  1284. );
  1285. tnode.Dump(outstream);
  1286. }
  1287. }
  1288. // bones.
  1289. //
  1290. // output structure:
  1291. // subset of node heirarchy that are "skeleton",
  1292. // i.e. do not have meshes but only bones.
  1293. // but.. i'm not sure how anyone could guarantee that...
  1294. //
  1295. // input...
  1296. // well, for each mesh it has "bones",
  1297. // and the bone names correspond to nodes.
  1298. // of course we also need the parent nodes,
  1299. // as they give some of the transform........
  1300. //
  1301. // well. we can assume a sane input, i suppose.
  1302. //
  1303. // so input is the bone node heirarchy,
  1304. // with an extra thing for the transformation of the MESH in BONE space.
  1305. //
  1306. // output is a set of bone nodes,
  1307. // a "bindpose" which indicates the default local transform of all bones,
  1308. // and a set of "deformers".
  1309. // each deformer is parented to a mesh geometry,
  1310. // and has one or more "subdeformer"s as children.
  1311. // each subdeformer has one bone node as a child,
  1312. // and represents the influence of that bone on the grandparent mesh.
  1313. // the subdeformer has a list of indices, and weights,
  1314. // with indices specifying vertex indices,
  1315. // and weights specifying the correspoding influence of this bone.
  1316. // it also has Transform and TransformLink elements,
  1317. // specifying the transform of the MESH in BONE space,
  1318. // and the transformation of the BONE in WORLD space,
  1319. // likely in the bindpose.
  1320. //
  1321. // the input bone structure is different but similar,
  1322. // storing the number of weights for this bone,
  1323. // and an array of (vertex index, weight) pairs.
  1324. //
  1325. // one sticky point is that the number of vertices may not match,
  1326. // because assimp splits vertices by normal, uv, etc.
  1327. // first we should mark all the skeleton nodes,
  1328. // so that they can be treated as LimbNode in stead of Mesh or Null.
  1329. // at the same time we can build up a map of bone nodes.
  1330. std::unordered_set<const aiNode*> limbnodes;
  1331. std::map<std::string,aiNode*> node_by_bone;
  1332. for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  1333. const aiMesh* m = mScene->mMeshes[mi];
  1334. for (size_t bi =0; bi < m->mNumBones; ++bi) {
  1335. const aiBone* b = m->mBones[bi];
  1336. const std::string name(b->mName.C_Str());
  1337. if (node_by_bone.count(name) > 0) {
  1338. // already processed, skip
  1339. continue;
  1340. }
  1341. aiNode* n = mScene->mRootNode->FindNode(b->mName);
  1342. if (!n) {
  1343. // this should never happen
  1344. std::stringstream err;
  1345. err << "Failed to find node for bone: \"" << name << "\"";
  1346. throw DeadlyExportError(err.str());
  1347. }
  1348. node_by_bone[name] = n;
  1349. limbnodes.insert(n);
  1350. if (n == mScene->mRootNode) { continue; }
  1351. // mark all parent nodes as skeleton as well,
  1352. // up until we find the root node,
  1353. // or else the node containing the mesh,
  1354. // or else the parent of a node containig the mesh.
  1355. for (
  1356. const aiNode* parent = n->mParent;
  1357. parent != mScene->mRootNode;
  1358. parent = parent->mParent
  1359. ) {
  1360. bool end = false;
  1361. for (size_t i = 0; i < parent->mNumMeshes; ++i) {
  1362. if (parent->mMeshes[i] == mi) {
  1363. end = true;
  1364. break;
  1365. }
  1366. }
  1367. for (size_t j = 0; j < parent->mNumChildren; ++j) {
  1368. aiNode* child = parent->mChildren[j];
  1369. for (size_t i = 0; i < child->mNumMeshes; ++i) {
  1370. if (child->mMeshes[i] == mi) {
  1371. end = true;
  1372. break;
  1373. }
  1374. }
  1375. if (end) { break; }
  1376. }
  1377. if (end) { break; }
  1378. limbnodes.insert(parent);
  1379. }
  1380. }
  1381. }
  1382. // we'll need the uids for the bone nodes, so generate them now
  1383. std::map<std::string,int64_t> bone_uids;
  1384. for (auto &bone : limbnodes) {
  1385. std::string bone_name(bone->mName.C_Str());
  1386. aiNode* bone_node = mScene->mRootNode->FindNode(bone->mName);
  1387. if (!bone_node) {
  1388. throw DeadlyExportError("Couldn't find node for bone" + bone_name);
  1389. }
  1390. auto elem = node_uids.find(bone_node);
  1391. if (elem == node_uids.end()) {
  1392. int64_t uid = generate_uid();
  1393. node_uids[bone_node] = uid;
  1394. bone_uids[bone_name] = uid;
  1395. } else {
  1396. bone_uids[bone_name] = elem->second;
  1397. }
  1398. }
  1399. // now, for each aiMesh, we need to export a deformer,
  1400. // and for each aiBone a subdeformer,
  1401. // which should have all the skinning info.
  1402. // these will need to be connected properly to the mesh,
  1403. // and we can do that all now.
  1404. for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  1405. const aiMesh* m = mScene->mMeshes[mi];
  1406. if (!m->HasBones()) {
  1407. continue;
  1408. }
  1409. // make a deformer for this mesh
  1410. int64_t deformer_uid = generate_uid();
  1411. FBX::Node dnode("Deformer");
  1412. dnode.AddProperties(deformer_uid, FBX::SEPARATOR + "Deformer", "Skin");
  1413. dnode.AddChild("Version", int32_t(101));
  1414. // "acuracy"... this is not a typo....
  1415. dnode.AddChild("Link_DeformAcuracy", double(50));
  1416. dnode.AddChild("SkinningType", "Linear"); // TODO: other modes?
  1417. dnode.Dump(outstream);
  1418. // connect it
  1419. FBX::Node c("C");
  1420. c.AddProperties("OO", deformer_uid, mesh_uids[mi]);
  1421. connections.push_back(c); // TODO: emplace_back
  1422. // we will be indexing by vertex...
  1423. // but there might be a different number of "vertices"
  1424. // between assimp and our output FBX.
  1425. // this code is cut-and-pasted from the geometry section above...
  1426. // ideally this should not be so.
  1427. // ---
  1428. // index of original vertex in vertex data vector
  1429. std::vector<int32_t> vertex_indices;
  1430. // map of vertex value to its index in the data vector
  1431. std::map<aiVector3D,size_t> index_by_vertex_value;
  1432. size_t index = 0;
  1433. for (size_t vi = 0; vi < m->mNumVertices; ++vi) {
  1434. aiVector3D vtx = m->mVertices[vi];
  1435. auto elem = index_by_vertex_value.find(vtx);
  1436. if (elem == index_by_vertex_value.end()) {
  1437. vertex_indices.push_back(index);
  1438. index_by_vertex_value[vtx] = index;
  1439. ++index;
  1440. } else {
  1441. vertex_indices.push_back(elem->second);
  1442. }
  1443. }
  1444. // first get this mesh's position in world space,
  1445. // as we'll need it for each subdeformer.
  1446. //
  1447. // ...of course taking the position of the MESH doesn't make sense,
  1448. // as it can be instanced to many nodes.
  1449. // All we can do is assume no instancing,
  1450. // and take the first node we find that contains the mesh.
  1451. //
  1452. // We could in stead take the transform from the bone's node,
  1453. // but there's no guarantee that the bone is in the bindpose,
  1454. // so this would be even less reliable.
  1455. aiNode* mesh_node = get_node_for_mesh(mi, mScene->mRootNode);
  1456. aiMatrix4x4 mesh_node_xform = get_world_transform(mesh_node, mScene);
  1457. // now make a subdeformer for each bone
  1458. for (size_t bi =0; bi < m->mNumBones; ++bi) {
  1459. const aiBone* b = m->mBones[bi];
  1460. const std::string name(b->mName.C_Str());
  1461. const int64_t subdeformer_uid = generate_uid();
  1462. FBX::Node sdnode("Deformer");
  1463. sdnode.AddProperties(
  1464. subdeformer_uid, FBX::SEPARATOR + "SubDeformer", "Cluster"
  1465. );
  1466. sdnode.AddChild("Version", int32_t(100));
  1467. sdnode.AddChild("UserData", "", "");
  1468. // get indices and weights
  1469. std::vector<int32_t> subdef_indices;
  1470. std::vector<double> subdef_weights;
  1471. int32_t last_index = -1;
  1472. for (size_t wi = 0; wi < b->mNumWeights; ++wi) {
  1473. int32_t vi = vertex_indices[b->mWeights[wi].mVertexId];
  1474. if (vi == last_index) {
  1475. // only for vertices we exported to fbx
  1476. // TODO, FIXME: this assumes identically-located vertices
  1477. // will always deform in the same way.
  1478. // as assimp doesn't store a separate list of "positions",
  1479. // there's not much that can be done about this
  1480. // other than assuming that identical position means
  1481. // identical vertex.
  1482. continue;
  1483. }
  1484. subdef_indices.push_back(vi);
  1485. subdef_weights.push_back(b->mWeights[wi].mWeight);
  1486. last_index = vi;
  1487. }
  1488. // yes, "indexes"
  1489. sdnode.AddChild("Indexes", subdef_indices);
  1490. sdnode.AddChild("Weights", subdef_weights);
  1491. // transform is the transform of the mesh, but in bone space...
  1492. // which is exactly what assimp's mOffsetMatrix is,
  1493. // no matter what the assimp docs may say.
  1494. aiMatrix4x4 tr = b->mOffsetMatrix;
  1495. sdnode.AddChild("Transform", tr);
  1496. // transformlink should be the position of the bone in world space,
  1497. // in the bind pose.
  1498. // For now let's use the inverse of mOffsetMatrix,
  1499. // and the (assumedly static) mesh position in world space.
  1500. // TODO: find a better way of doing this? there aren't many options
  1501. tr = b->mOffsetMatrix;
  1502. tr.Inverse();
  1503. tr *= mesh_node_xform;
  1504. sdnode.AddChild("TransformLink", tr);
  1505. // done
  1506. sdnode.Dump(outstream);
  1507. // lastly, connect to the parent deformer
  1508. c = FBX::Node("C");
  1509. c.AddProperties("OO", subdeformer_uid, deformer_uid);
  1510. connections.push_back(c); // TODO: emplace_back
  1511. // we also need to connect the limb node to the subdeformer.
  1512. c = FBX::Node("C");
  1513. c.AddProperties("OO", bone_uids[name], subdeformer_uid);
  1514. connections.push_back(c); // TODO: emplace_back
  1515. }
  1516. }
  1517. // BindPose
  1518. //
  1519. // This is a legacy system, which should be unnecessary.
  1520. //
  1521. // Somehow including it slows file loading by the official FBX SDK,
  1522. // and as it can reconstruct it from the deformers anyway,
  1523. // this is not currently included.
  1524. //
  1525. // The code is kept here in case it's useful in the future,
  1526. // but it's pretty much a hack anyway,
  1527. // as assimp doesn't store bindpose information for full skeletons.
  1528. //
  1529. /*for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  1530. aiMesh* mesh = mScene->mMeshes[mi];
  1531. if (! mesh->HasBones()) { continue; }
  1532. int64_t bindpose_uid = generate_uid();
  1533. FBX::Node bpnode("Pose");
  1534. bpnode.AddProperty(bindpose_uid);
  1535. // note: this uid is never linked or connected to anything.
  1536. bpnode.AddProperty(FBX::SEPARATOR + "Pose"); // blank name
  1537. bpnode.AddProperty("BindPose");
  1538. bpnode.AddChild("Type", "BindPose");
  1539. bpnode.AddChild("Version", int32_t(100));
  1540. aiNode* mesh_node = get_node_for_mesh(mi, mScene->mRootNode);
  1541. // next get the whole skeleton for this mesh.
  1542. // we need it all to define the bindpose section.
  1543. // the FBX SDK will complain if it's missing,
  1544. // and also if parents of used bones don't have a subdeformer.
  1545. // order shouldn't matter.
  1546. std::set<aiNode*> skeleton;
  1547. for (size_t bi = 0; bi < mesh->mNumBones; ++bi) {
  1548. // bone node should have already been indexed
  1549. const aiBone* b = mesh->mBones[bi];
  1550. const std::string bone_name(b->mName.C_Str());
  1551. aiNode* parent = node_by_bone[bone_name];
  1552. // insert all nodes down to the root or mesh node
  1553. while (
  1554. parent
  1555. && parent != mScene->mRootNode
  1556. && parent != mesh_node
  1557. ) {
  1558. skeleton.insert(parent);
  1559. parent = parent->mParent;
  1560. }
  1561. }
  1562. // number of pose nodes. includes one for the mesh itself.
  1563. bpnode.AddChild("NbPoseNodes", int32_t(1 + skeleton.size()));
  1564. // the first pose node is always the mesh itself
  1565. FBX::Node pose("PoseNode");
  1566. pose.AddChild("Node", mesh_uids[mi]);
  1567. aiMatrix4x4 mesh_node_xform = get_world_transform(mesh_node, mScene);
  1568. pose.AddChild("Matrix", mesh_node_xform);
  1569. bpnode.AddChild(pose);
  1570. for (aiNode* bonenode : skeleton) {
  1571. // does this node have a uid yet?
  1572. int64_t node_uid;
  1573. auto node_uid_iter = node_uids.find(bonenode);
  1574. if (node_uid_iter != node_uids.end()) {
  1575. node_uid = node_uid_iter->second;
  1576. } else {
  1577. node_uid = generate_uid();
  1578. node_uids[bonenode] = node_uid;
  1579. }
  1580. // make a pose thingy
  1581. pose = FBX::Node("PoseNode");
  1582. pose.AddChild("Node", node_uid);
  1583. aiMatrix4x4 node_xform = get_world_transform(bonenode, mScene);
  1584. pose.AddChild("Matrix", node_xform);
  1585. bpnode.AddChild(pose);
  1586. }
  1587. // now write it
  1588. bpnode.Dump(outstream);
  1589. }*/
  1590. // TODO: cameras, lights
  1591. // write nodes (i.e. model heirarchy)
  1592. // start at root node
  1593. WriteModelNodes(
  1594. outstream, mScene->mRootNode, 0, bone_uids
  1595. );
  1596. object_node.End(outstream, true);
  1597. }
  1598. // convenience map of magic node name strings to FBX properties,
  1599. // including the expected type of transform.
  1600. const std::map<std::string,std::pair<std::string,char>> transform_types = {
  1601. {"Translation", {"Lcl Translation", 't'}},
  1602. {"RotationOffset", {"RotationOffset", 't'}},
  1603. {"RotationPivot", {"RotationPivot", 't'}},
  1604. {"PreRotation", {"PreRotation", 'r'}},
  1605. {"Rotation", {"Lcl Rotation", 'r'}},
  1606. {"PostRotation", {"PostRotation", 'r'}},
  1607. {"RotationPivotInverse", {"RotationPivotInverse", 'i'}},
  1608. {"ScalingOffset", {"ScalingOffset", 't'}},
  1609. {"ScalingPivot", {"ScalingPivot", 't'}},
  1610. {"Scaling", {"Lcl Scaling", 's'}},
  1611. {"ScalingPivotInverse", {"ScalingPivotInverse", 'i'}},
  1612. {"GeometricScaling", {"GeometricScaling", 's'}},
  1613. {"GeometricRotation", {"GeometricRotation", 'r'}},
  1614. {"GeometricTranslation", {"GeometricTranslation", 't'}}
  1615. };
  1616. // write a single model node to the stream
  1617. void WriteModelNode(
  1618. StreamWriterLE& outstream,
  1619. const aiNode* node,
  1620. int64_t node_uid,
  1621. const std::string& type,
  1622. const std::vector<std::pair<std::string,aiVector3D>>& transform_chain,
  1623. TransformInheritance inherit_type=TransformInheritance_RSrs
  1624. ){
  1625. const aiVector3D zero = {0, 0, 0};
  1626. const aiVector3D one = {1, 1, 1};
  1627. FBX::Node m("Model");
  1628. std::string name = node->mName.C_Str() + FBX::SEPARATOR + "Model";
  1629. m.AddProperties(node_uid, name, type);
  1630. m.AddChild("Version", int32_t(232));
  1631. FBX::Node p("Properties70");
  1632. p.AddP70bool("RotationActive", 1);
  1633. p.AddP70int("DefaultAttributeIndex", 0);
  1634. p.AddP70enum("InheritType", inherit_type);
  1635. if (transform_chain.empty()) {
  1636. // decompose 4x4 transform matrix into TRS
  1637. aiVector3D t, r, s;
  1638. node->mTransformation.Decompose(s, r, t);
  1639. if (t != zero) {
  1640. p.AddP70(
  1641. "Lcl Translation", "Lcl Translation", "", "A",
  1642. double(t.x), double(t.y), double(t.z)
  1643. );
  1644. }
  1645. if (r != zero) {
  1646. p.AddP70(
  1647. "Lcl Rotation", "Lcl Rotation", "", "A",
  1648. double(DEG*r.x), double(DEG*r.y), double(DEG*r.z)
  1649. );
  1650. }
  1651. if (s != one) {
  1652. p.AddP70(
  1653. "Lcl Scaling", "Lcl Scaling", "", "A",
  1654. double(s.x), double(s.y), double(s.z)
  1655. );
  1656. }
  1657. } else {
  1658. // apply the transformation chain.
  1659. // these transformation elements are created when importing FBX,
  1660. // which has a complex transformation heirarchy for each node.
  1661. // as such we can bake the heirarchy back into the node on export.
  1662. for (auto &item : transform_chain) {
  1663. auto elem = transform_types.find(item.first);
  1664. if (elem == transform_types.end()) {
  1665. // then this is a bug
  1666. std::stringstream err;
  1667. err << "unrecognized FBX transformation type: ";
  1668. err << item.first;
  1669. throw DeadlyExportError(err.str());
  1670. }
  1671. const std::string &name = elem->second.first;
  1672. const aiVector3D &v = item.second;
  1673. if (name.compare(0, 4, "Lcl ") == 0) {
  1674. // special handling for animatable properties
  1675. p.AddP70(
  1676. name, name, "", "A",
  1677. double(v.x), double(v.y), double(v.z)
  1678. );
  1679. } else {
  1680. p.AddP70vector(name, v.x, v.y, v.z);
  1681. }
  1682. }
  1683. }
  1684. m.AddChild(p);
  1685. // not sure what these are for,
  1686. // but they seem to be omnipresent
  1687. m.AddChild("Shading", Property(true));
  1688. m.AddChild("Culling", Property("CullingOff"));
  1689. m.Dump(outstream);
  1690. }
  1691. // wrapper for WriteModelNodes to create and pass a blank transform chain
  1692. void FBXExporter::WriteModelNodes(
  1693. StreamWriterLE& s,
  1694. const aiNode* node,
  1695. int64_t parent_uid,
  1696. const std::map<std::string,int64_t>& bone_uids
  1697. ) {
  1698. std::vector<std::pair<std::string,aiVector3D>> chain;
  1699. WriteModelNodes(s, node, parent_uid, bone_uids, chain);
  1700. }
  1701. void FBXExporter::WriteModelNodes(
  1702. StreamWriterLE& outstream,
  1703. const aiNode* node,
  1704. int64_t parent_uid,
  1705. const std::map<std::string,int64_t>& bone_uids,
  1706. std::vector<std::pair<std::string,aiVector3D>>& transform_chain
  1707. ) {
  1708. // first collapse any expanded transformation chains created by FBX import.
  1709. std::string node_name(node->mName.C_Str());
  1710. if (node_name.find(MAGIC_NODE_TAG) != std::string::npos) {
  1711. if (node->mNumChildren != 1) {
  1712. // this should never happen
  1713. std::stringstream err;
  1714. err << "FBX transformation node should have exactly 1 child,";
  1715. err << " but " << node->mNumChildren << " found";
  1716. err << " on node \"" << node_name << "\"!";
  1717. throw DeadlyExportError(err.str());
  1718. }
  1719. aiNode* next_node = node->mChildren[0];
  1720. auto pos = node_name.find(MAGIC_NODE_TAG) + MAGIC_NODE_TAG.size() + 1;
  1721. std::string type_name = node_name.substr(pos);
  1722. auto elem = transform_types.find(type_name);
  1723. if (elem == transform_types.end()) {
  1724. // then this is a bug and should be fixed
  1725. std::stringstream err;
  1726. err << "unrecognized FBX transformation node";
  1727. err << " of type " << type_name << " in node " << node_name;
  1728. throw DeadlyExportError(err.str());
  1729. }
  1730. aiVector3D t, r, s;
  1731. node->mTransformation.Decompose(s, r, t);
  1732. switch (elem->second.second) {
  1733. case 'i': // inverse
  1734. // we don't need to worry about the inverse matrices
  1735. break;
  1736. case 't': // translation
  1737. transform_chain.emplace_back(elem->first, t);
  1738. break;
  1739. case 'r': // rotation
  1740. r *= DEG;
  1741. transform_chain.emplace_back(elem->first, r);
  1742. break;
  1743. case 's': // scale
  1744. transform_chain.emplace_back(elem->first, s);
  1745. break;
  1746. default:
  1747. // this should never happen
  1748. std::stringstream err;
  1749. err << "unrecognized FBX transformation type code: ";
  1750. err << elem->second.second;
  1751. throw DeadlyExportError(err.str());
  1752. }
  1753. // now just continue to the next node
  1754. WriteModelNodes(
  1755. outstream, next_node, parent_uid, bone_uids, transform_chain
  1756. );
  1757. return;
  1758. }
  1759. int64_t node_uid = 0;
  1760. // generate uid and connect to parent, if not the root node,
  1761. if (node != mScene->mRootNode) {
  1762. auto elem = node_uids.find(node);
  1763. if (elem != node_uids.end()) {
  1764. node_uid = elem->second;
  1765. } else {
  1766. node_uid = generate_uid();
  1767. node_uids[node] = node_uid;
  1768. }
  1769. FBX::Node c("C");
  1770. c.AddProperties("OO", node_uid, parent_uid);
  1771. connections.push_back(c);
  1772. }
  1773. // what type of node is this?
  1774. if (node == mScene->mRootNode) {
  1775. // handled later
  1776. } else if (node->mNumMeshes == 1) {
  1777. // connect to child mesh, which should have been written previously
  1778. FBX::Node c("C");
  1779. c.AddProperties("OO", mesh_uids[node->mMeshes[0]], node_uid);
  1780. connections.push_back(c);
  1781. // also connect to the material for the child mesh
  1782. c = FBX::Node("C");
  1783. c.AddProperties(
  1784. "OO",
  1785. material_uids[mScene->mMeshes[node->mMeshes[0]]->mMaterialIndex],
  1786. node_uid
  1787. );
  1788. connections.push_back(c);
  1789. // write model node
  1790. WriteModelNode(outstream, node, node_uid, "Mesh", transform_chain);
  1791. } else if (bone_uids.count(node_name)) {
  1792. WriteModelNode(outstream, node, node_uid, "LimbNode", transform_chain);
  1793. // we also need to write a nodeattribute to mark it as a skeleton
  1794. int64_t node_attribute_uid = generate_uid();
  1795. FBX::Node na("NodeAttribute");
  1796. na.AddProperties(
  1797. node_attribute_uid, FBX::SEPARATOR + "NodeAttribute", "LimbNode"
  1798. );
  1799. na.AddChild("TypeFlags", Property("Skeleton"));
  1800. na.Dump(outstream);
  1801. // and connect them
  1802. FBX::Node c("C");
  1803. c.AddProperties("OO", node_attribute_uid, node_uid);
  1804. connections.push_back(c);
  1805. } else {
  1806. // generate a null node so we can add children to it
  1807. WriteModelNode(outstream, node, node_uid, "Null", transform_chain);
  1808. }
  1809. // if more than one child mesh, make nodes for each mesh
  1810. if (node->mNumMeshes > 1 || node == mScene->mRootNode) {
  1811. for (size_t i = 0; i < node->mNumMeshes; ++i) {
  1812. // make a new model node
  1813. int64_t new_node_uid = generate_uid();
  1814. // connect to parent node
  1815. FBX::Node c("C");
  1816. c.AddProperties("OO", new_node_uid, node_uid);
  1817. connections.push_back(c);
  1818. // connect to child mesh, which should have been written previously
  1819. c = FBX::Node("C");
  1820. c.AddProperties("OO", mesh_uids[node->mMeshes[i]], new_node_uid);
  1821. connections.push_back(c);
  1822. // also connect to the material for the child mesh
  1823. c = FBX::Node("C");
  1824. c.AddProperties(
  1825. "OO",
  1826. material_uids[
  1827. mScene->mMeshes[node->mMeshes[i]]->mMaterialIndex
  1828. ],
  1829. new_node_uid
  1830. );
  1831. connections.push_back(c);
  1832. // write model node
  1833. FBX::Node m("Model");
  1834. // take name from mesh name, if it exists
  1835. std::string name = mScene->mMeshes[node->mMeshes[i]]->mName.C_Str();
  1836. name += FBX::SEPARATOR + "Model";
  1837. m.AddProperties(new_node_uid, name, "Mesh");
  1838. m.AddChild("Version", int32_t(232));
  1839. FBX::Node p("Properties70");
  1840. p.AddP70enum("InheritType", 1);
  1841. m.AddChild(p);
  1842. m.Dump(outstream);
  1843. }
  1844. }
  1845. // now recurse into children
  1846. for (size_t i = 0; i < node->mNumChildren; ++i) {
  1847. WriteModelNodes(
  1848. outstream, node->mChildren[i], node_uid, bone_uids
  1849. );
  1850. }
  1851. }
  1852. void FBXExporter::WriteConnections ()
  1853. {
  1854. // we should have completed the connection graph already,
  1855. // so basically just dump it here
  1856. FBX::Node conn("Connections");
  1857. StreamWriterLE outstream(outfile);
  1858. conn.Begin(outstream);
  1859. for (auto &n : connections) {
  1860. n.Dump(outstream);
  1861. }
  1862. conn.End(outstream, !connections.empty());
  1863. connections.clear();
  1864. }
  1865. #endif // ASSIMP_BUILD_NO_FBX_EXPORTER
  1866. #endif // ASSIMP_BUILD_NO_EXPORT