FBXExporter.cpp 93 KB

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