2
0

ColladaExporter.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2025, 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_COLLADA_EXPORTER
  35. #include "ColladaExporter.h"
  36. #include <assimp/Bitmap.h>
  37. #include <assimp/ColladaMetaData.h>
  38. #include <assimp/DefaultIOSystem.h>
  39. #include <assimp/Exceptional.h>
  40. #include <assimp/MathFunctions.h>
  41. #include <assimp/SceneCombiner.h>
  42. #include <assimp/StringUtils.h>
  43. #include <assimp/XMLTools.h>
  44. #include <assimp/commonMetaData.h>
  45. #include <assimp/fast_atof.h>
  46. #include <assimp/scene.h>
  47. #include <assimp/Exporter.hpp>
  48. #include <assimp/IOSystem.hpp>
  49. #include <ctime>
  50. #include <memory>
  51. namespace Assimp {
  52. static const aiNode *findSkeletonRootNode(const aiScene *scene, const aiMesh *mesh) {
  53. std::set<const aiNode *> topParentBoneNodes;
  54. if (mesh && mesh->mNumBones > 0) {
  55. for (unsigned int i = 0; i < mesh->mNumBones; ++i) {
  56. aiBone *bone = mesh->mBones[i];
  57. const aiNode *node = scene->mRootNode->findBoneNode(bone);
  58. if (node) {
  59. while (node->mParent && scene->findBone(node->mParent->mName) != nullptr) {
  60. node = node->mParent;
  61. }
  62. topParentBoneNodes.insert(node);
  63. }
  64. }
  65. }
  66. if (!topParentBoneNodes.empty()) {
  67. const aiNode *parentBoneNode = *topParentBoneNodes.begin();
  68. if (topParentBoneNodes.size() == 1) {
  69. return parentBoneNode;
  70. } else {
  71. for (auto it : topParentBoneNodes) {
  72. if (it->mParent) return it->mParent;
  73. }
  74. return parentBoneNode;
  75. }
  76. }
  77. return nullptr;
  78. }
  79. // ------------------------------------------------------------------------------------------------
  80. // Worker function for exporting a scene to Collada. Prototyped and registered in Exporter.cpp
  81. void ExportSceneCollada(const char *pFile, IOSystem *pIOSystem, const aiScene *pScene, const ExportProperties * /*pProperties*/) {
  82. std::string path = DefaultIOSystem::absolutePath(std::string(pFile));
  83. std::string file = DefaultIOSystem::completeBaseName(std::string(pFile));
  84. // invoke the exporter
  85. ColladaExporter iDoTheExportThing(pScene, pIOSystem, path, file);
  86. if (iDoTheExportThing.mOutput.fail()) {
  87. throw DeadlyExportError("output data creation failed. Most likely the file became too large: " + std::string(pFile));
  88. }
  89. // we're still here - export successfully completed. Write result to the given IOSYstem
  90. std::unique_ptr<IOStream> outfile(pIOSystem->Open(pFile, "wt"));
  91. if (outfile == nullptr) {
  92. throw DeadlyExportError("could not open output .dae file: " + std::string(pFile));
  93. }
  94. // XXX maybe use a small wrapper around IOStream that behaves like std::stringstream in order to avoid the extra copy.
  95. outfile->Write(iDoTheExportThing.mOutput.str().c_str(), static_cast<size_t>(iDoTheExportThing.mOutput.tellp()), 1);
  96. }
  97. // ------------------------------------------------------------------------------------------------
  98. // Encodes a string into a valid XML ID using the xsd:ID schema qualifications.
  99. static const std::string XMLIDEncode(const std::string &name) {
  100. const char XML_ID_CHARS[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-.";
  101. const unsigned int XML_ID_CHARS_COUNT = sizeof(XML_ID_CHARS) / sizeof(char) - 1;
  102. if (name.length() == 0) {
  103. return name;
  104. }
  105. std::stringstream idEncoded;
  106. // xsd:ID must start with letter or underscore
  107. if (!((name[0] >= 'A' && name[0] <= 'z') || name[0] == '_')) {
  108. idEncoded << '_';
  109. }
  110. for (std::string::const_iterator it = name.begin(); it != name.end(); ++it) {
  111. // xsd:ID can only contain letters, digits, underscores, hyphens and periods
  112. if (strchr(XML_ID_CHARS, *it) != nullptr) {
  113. idEncoded << *it;
  114. } else {
  115. // Select placeholder character based on invalid character to reduce ID collisions
  116. idEncoded << XML_ID_CHARS[(*it) % XML_ID_CHARS_COUNT];
  117. }
  118. }
  119. return idEncoded.str();
  120. }
  121. // ------------------------------------------------------------------------------------------------
  122. // Helper functions to create unique ids
  123. inline bool IsUniqueId(const std::unordered_set<std::string> &idSet, const std::string &idStr) {
  124. return (idSet.find(idStr) == idSet.end());
  125. }
  126. inline std::string MakeUniqueId(const std::unordered_set<std::string> &idSet, const std::string &idPrefix, const std::string &postfix) {
  127. std::string result(idPrefix + postfix);
  128. if (!IsUniqueId(idSet, result)) {
  129. // Select a number to append
  130. size_t idnum = 1;
  131. do {
  132. result = idPrefix + '_' + ai_to_string(idnum) + postfix;
  133. ++idnum;
  134. } while (!IsUniqueId(idSet, result));
  135. }
  136. return result;
  137. }
  138. // ------------------------------------------------------------------------------------------------
  139. // Constructor for a specific scene to export
  140. ColladaExporter::ColladaExporter(const aiScene *pScene, IOSystem *pIOSystem, const std::string &path, const std::string &file) :
  141. mIOSystem(pIOSystem),
  142. mPath(path),
  143. mFile(file),
  144. mScene(pScene),
  145. endstr("\n") {
  146. // make sure that all formatting happens using the standard, C locale and not the user's current locale
  147. mOutput.imbue(std::locale("C"));
  148. mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION);
  149. // start writing the file
  150. WriteFile();
  151. }
  152. // ------------------------------------------------------------------------------------------------
  153. // Starts writing the contents
  154. void ColladaExporter::WriteFile() {
  155. // write the DTD
  156. mOutput << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << endstr;
  157. // COLLADA element start
  158. mOutput << "<COLLADA xmlns=\"http://www.collada.org/2005/11/COLLADASchema\" version=\"1.4.1\">" << endstr;
  159. PushTag();
  160. WriteTextures();
  161. WriteHeader();
  162. // Add node names to the unique id database first so they are most likely to use their names as unique ids
  163. CreateNodeIds(mScene->mRootNode);
  164. WriteCamerasLibrary();
  165. WriteLightsLibrary();
  166. WriteMaterials();
  167. WriteGeometryLibrary();
  168. WriteControllerLibrary();
  169. WriteSceneLibrary();
  170. // customized, Writes the animation library
  171. WriteAnimationsLibrary();
  172. // instantiate the scene(s)
  173. // For Assimp there will only ever be one
  174. mOutput << startstr << "<scene>" << endstr;
  175. PushTag();
  176. mOutput << startstr << "<instance_visual_scene url=\"#" + mSceneId + "\" />" << endstr;
  177. PopTag();
  178. mOutput << startstr << "</scene>" << endstr;
  179. PopTag();
  180. mOutput << "</COLLADA>" << endstr;
  181. }
  182. // ------------------------------------------------------------------------------------------------
  183. // Writes the asset header
  184. void ColladaExporter::WriteHeader() {
  185. static const ai_real epsilon = Math::getEpsilon<ai_real>();
  186. static const aiQuaternion x_rot(aiMatrix3x3(
  187. 0, -1, 0,
  188. 1, 0, 0,
  189. 0, 0, 1));
  190. static const aiQuaternion y_rot(aiMatrix3x3(
  191. 1, 0, 0,
  192. 0, 1, 0,
  193. 0, 0, 1));
  194. static const aiQuaternion z_rot(aiMatrix3x3(
  195. 1, 0, 0,
  196. 0, 0, 1,
  197. 0, -1, 0));
  198. static const unsigned int date_nb_chars = 20;
  199. char date_str[date_nb_chars];
  200. std::time_t date = std::time(nullptr);
  201. std::strftime(date_str, date_nb_chars, "%Y-%m-%dT%H:%M:%S", std::localtime(&date));
  202. aiVector3D scaling;
  203. aiQuaternion rotation;
  204. aiVector3D position;
  205. mScene->mRootNode->mTransformation.Decompose(scaling, rotation, position);
  206. rotation.Normalize();
  207. mAdd_root_node = false;
  208. ai_real scale = 1.0;
  209. if (std::abs(scaling.x - scaling.y) <= epsilon && std::abs(scaling.x - scaling.z) <= epsilon && std::abs(scaling.y - scaling.z) <= epsilon) {
  210. scale = (ai_real)((((double)scaling.x) + ((double)scaling.y) + ((double)scaling.z)) / 3.0);
  211. } else {
  212. mAdd_root_node = true;
  213. }
  214. std::string up_axis = "Y_UP";
  215. if (rotation.Equal(x_rot, epsilon)) {
  216. up_axis = "X_UP";
  217. } else if (rotation.Equal(y_rot, epsilon)) {
  218. up_axis = "Y_UP";
  219. } else if (rotation.Equal(z_rot, epsilon)) {
  220. up_axis = "Z_UP";
  221. } else {
  222. mAdd_root_node = true;
  223. }
  224. if (!position.Equal(aiVector3D(0, 0, 0))) {
  225. mAdd_root_node = true;
  226. }
  227. // Assimp root nodes can have meshes, Collada Scenes cannot
  228. if (mScene->mRootNode->mNumChildren == 0 || mScene->mRootNode->mMeshes != nullptr) {
  229. mAdd_root_node = true;
  230. }
  231. if (mAdd_root_node) {
  232. up_axis = "Y_UP";
  233. scale = 1.0;
  234. }
  235. mOutput << startstr << "<asset>" << endstr;
  236. PushTag();
  237. mOutput << startstr << "<contributor>" << endstr;
  238. PushTag();
  239. // If no Scene metadata, use root node metadata
  240. aiMetadata *meta = mScene->mMetaData;
  241. if (nullptr == meta) {
  242. meta = mScene->mRootNode->mMetaData;
  243. }
  244. aiString value;
  245. if (!meta || !meta->Get("Author", value)) {
  246. mOutput << startstr << "<author>"
  247. << "Assimp"
  248. << "</author>" << endstr;
  249. } else {
  250. mOutput << startstr << "<author>" << XMLEscape(value.C_Str()) << "</author>" << endstr;
  251. }
  252. if (nullptr == meta || !meta->Get(AI_METADATA_SOURCE_GENERATOR, value)) {
  253. mOutput << startstr << "<authoring_tool>"
  254. << "Assimp Exporter"
  255. << "</authoring_tool>" << endstr;
  256. } else {
  257. mOutput << startstr << "<authoring_tool>" << XMLEscape(value.C_Str()) << "</authoring_tool>" << endstr;
  258. }
  259. if (meta) {
  260. if (meta->Get("Comments", value)) {
  261. mOutput << startstr << "<comments>" << XMLEscape(value.C_Str()) << "</comments>" << endstr;
  262. }
  263. if (meta->Get(AI_METADATA_SOURCE_COPYRIGHT, value)) {
  264. mOutput << startstr << "<copyright>" << XMLEscape(value.C_Str()) << "</copyright>" << endstr;
  265. }
  266. if (meta->Get("SourceData", value)) {
  267. mOutput << startstr << "<source_data>" << XMLEscape(value.C_Str()) << "</source_data>" << endstr;
  268. }
  269. }
  270. PopTag();
  271. mOutput << startstr << "</contributor>" << endstr;
  272. if (nullptr == meta || !meta->Get("Created", value)) {
  273. mOutput << startstr << "<created>" << date_str << "</created>" << endstr;
  274. } else {
  275. mOutput << startstr << "<created>" << XMLEscape(value.C_Str()) << "</created>" << endstr;
  276. }
  277. // Modified date is always the date saved
  278. mOutput << startstr << "<modified>" << date_str << "</modified>" << endstr;
  279. if (meta) {
  280. if (meta->Get("Keywords", value)) {
  281. mOutput << startstr << "<keywords>" << XMLEscape(value.C_Str()) << "</keywords>" << endstr;
  282. }
  283. if (meta->Get("Revision", value)) {
  284. mOutput << startstr << "<revision>" << XMLEscape(value.C_Str()) << "</revision>" << endstr;
  285. }
  286. if (meta->Get("Subject", value)) {
  287. mOutput << startstr << "<subject>" << XMLEscape(value.C_Str()) << "</subject>" << endstr;
  288. }
  289. if (meta->Get("Title", value)) {
  290. mOutput << startstr << "<title>" << XMLEscape(value.C_Str()) << "</title>" << endstr;
  291. }
  292. }
  293. mOutput << startstr << "<unit name=\"meter\" meter=\"" << scale << "\" />" << endstr;
  294. mOutput << startstr << "<up_axis>" << up_axis << "</up_axis>" << endstr;
  295. PopTag();
  296. mOutput << startstr << "</asset>" << endstr;
  297. }
  298. // ------------------------------------------------------------------------------------------------
  299. // Write the embedded textures
  300. void ColladaExporter::WriteTextures() {
  301. static constexpr unsigned int buffer_size = 1024;
  302. char str[buffer_size] = {'\0'};
  303. if (!mScene->HasTextures()) {
  304. return;
  305. }
  306. for (unsigned int i = 0; i < mScene->mNumTextures; i++) {
  307. // It would be great to be able to create a directory in portable standard C++, but it's not the case,
  308. // so we just write the textures in the current directory.
  309. aiTexture *texture = mScene->mTextures[i];
  310. if (nullptr == texture) {
  311. continue;
  312. }
  313. ASSIMP_itoa10(str, buffer_size, i + 1);
  314. std::string name = mFile + "_texture_" + (i < 1000 ? "0" : "") + (i < 100 ? "0" : "") + (i < 10 ? "0" : "") + str + "." + ((const char *)texture->achFormatHint);
  315. std::unique_ptr<IOStream> outfile(mIOSystem->Open(mPath + mIOSystem->getOsSeparator() + name, "wb"));
  316. if (outfile == nullptr) {
  317. throw DeadlyExportError("could not open output texture file: " + mPath + name);
  318. }
  319. if (texture->mHeight == 0) {
  320. outfile->Write((void *)texture->pcData, texture->mWidth, 1);
  321. } else {
  322. Bitmap::Save(texture, outfile.get());
  323. }
  324. outfile->Flush();
  325. textures.insert(std::make_pair(i, name));
  326. }
  327. }
  328. // ------------------------------------------------------------------------------------------------
  329. // Write the embedded textures
  330. void ColladaExporter::WriteCamerasLibrary() {
  331. if (!mScene->HasCameras()) {
  332. return;
  333. }
  334. mOutput << startstr << "<library_cameras>" << endstr;
  335. PushTag();
  336. for (size_t a = 0; a < mScene->mNumCameras; ++a) {
  337. WriteCamera(a);
  338. }
  339. PopTag();
  340. mOutput << startstr << "</library_cameras>" << endstr;
  341. }
  342. void ColladaExporter::WriteCamera(size_t pIndex) {
  343. const aiCamera *cam = mScene->mCameras[pIndex];
  344. if (cam == nullptr) {
  345. return;
  346. }
  347. const std::string cameraId = GetObjectUniqueId(AiObjectType::Camera, pIndex);
  348. const std::string cameraName = GetObjectName(AiObjectType::Camera, pIndex);
  349. mOutput << startstr << "<camera id=\"" << cameraId << "\" name=\"" << cameraName << "\" >" << endstr;
  350. PushTag();
  351. mOutput << startstr << "<optics>" << endstr;
  352. PushTag();
  353. mOutput << startstr << "<technique_common>" << endstr;
  354. PushTag();
  355. //assimp doesn't support the import of orthographic cameras! se we write
  356. //always perspective
  357. mOutput << startstr << "<perspective>" << endstr;
  358. PushTag();
  359. mOutput << startstr << "<xfov sid=\"xfov\">" << AI_RAD_TO_DEG(cam->mHorizontalFOV)
  360. << "</xfov>" << endstr;
  361. mOutput << startstr << "<aspect_ratio>"
  362. << cam->mAspect
  363. << "</aspect_ratio>" << endstr;
  364. mOutput << startstr << "<znear sid=\"znear\">"
  365. << cam->mClipPlaneNear
  366. << "</znear>" << endstr;
  367. mOutput << startstr << "<zfar sid=\"zfar\">"
  368. << cam->mClipPlaneFar
  369. << "</zfar>" << endstr;
  370. PopTag();
  371. mOutput << startstr << "</perspective>" << endstr;
  372. PopTag();
  373. mOutput << startstr << "</technique_common>" << endstr;
  374. PopTag();
  375. mOutput << startstr << "</optics>" << endstr;
  376. PopTag();
  377. mOutput << startstr << "</camera>" << endstr;
  378. }
  379. // ------------------------------------------------------------------------------------------------
  380. // Write the embedded textures
  381. void ColladaExporter::WriteLightsLibrary() {
  382. if (!mScene->HasLights()) {
  383. return;
  384. }
  385. mOutput << startstr << "<library_lights>" << endstr;
  386. PushTag();
  387. for (size_t a = 0; a < mScene->mNumLights; ++a) {
  388. WriteLight(a);
  389. }
  390. PopTag();
  391. mOutput << startstr << "</library_lights>" << endstr;
  392. }
  393. void ColladaExporter::WriteLight(size_t pIndex) {
  394. const aiLight *light = mScene->mLights[pIndex];
  395. if (light == nullptr) {
  396. return;
  397. }
  398. const std::string lightId = GetObjectUniqueId(AiObjectType::Light, pIndex);
  399. const std::string lightName = GetObjectName(AiObjectType::Light, pIndex);
  400. mOutput << startstr << "<light id=\"" << lightId << "\" name=\""
  401. << lightName << "\" >" << endstr;
  402. PushTag();
  403. mOutput << startstr << "<technique_common>" << endstr;
  404. PushTag();
  405. switch (light->mType) {
  406. case aiLightSource_AMBIENT:
  407. WriteAmbientLight(light);
  408. break;
  409. case aiLightSource_DIRECTIONAL:
  410. WriteDirectionalLight(light);
  411. break;
  412. case aiLightSource_POINT:
  413. WritePointLight(light);
  414. break;
  415. case aiLightSource_SPOT:
  416. WriteSpotLight(light);
  417. break;
  418. case aiLightSource_AREA:
  419. case aiLightSource_UNDEFINED:
  420. case _aiLightSource_Force32Bit:
  421. default:
  422. break;
  423. }
  424. PopTag();
  425. mOutput << startstr << "</technique_common>" << endstr;
  426. PopTag();
  427. mOutput << startstr << "</light>" << endstr;
  428. }
  429. void ColladaExporter::WritePointLight(const aiLight *const light) {
  430. const aiColor3D &color = light->mColorDiffuse;
  431. mOutput << startstr << "<point>" << endstr;
  432. PushTag();
  433. mOutput << startstr << "<color sid=\"color\">"
  434. << color.r << " " << color.g << " " << color.b
  435. << "</color>" << endstr;
  436. mOutput << startstr << "<constant_attenuation>"
  437. << light->mAttenuationConstant
  438. << "</constant_attenuation>" << endstr;
  439. mOutput << startstr << "<linear_attenuation>"
  440. << light->mAttenuationLinear
  441. << "</linear_attenuation>" << endstr;
  442. mOutput << startstr << "<quadratic_attenuation>"
  443. << light->mAttenuationQuadratic
  444. << "</quadratic_attenuation>" << endstr;
  445. PopTag();
  446. mOutput << startstr << "</point>" << endstr;
  447. }
  448. void ColladaExporter::WriteDirectionalLight(const aiLight *const light) {
  449. const aiColor3D &color = light->mColorDiffuse;
  450. mOutput << startstr << "<directional>" << endstr;
  451. PushTag();
  452. mOutput << startstr << "<color sid=\"color\">"
  453. << color.r << " " << color.g << " " << color.b
  454. << "</color>" << endstr;
  455. PopTag();
  456. mOutput << startstr << "</directional>" << endstr;
  457. }
  458. void ColladaExporter::WriteSpotLight(const aiLight *const light) {
  459. const aiColor3D &color = light->mColorDiffuse;
  460. mOutput << startstr << "<spot>" << endstr;
  461. PushTag();
  462. mOutput << startstr << "<color sid=\"color\">"
  463. << color.r << " " << color.g << " " << color.b
  464. << "</color>" << endstr;
  465. mOutput << startstr << "<constant_attenuation>"
  466. << light->mAttenuationConstant
  467. << "</constant_attenuation>" << endstr;
  468. mOutput << startstr << "<linear_attenuation>"
  469. << light->mAttenuationLinear
  470. << "</linear_attenuation>" << endstr;
  471. mOutput << startstr << "<quadratic_attenuation>"
  472. << light->mAttenuationQuadratic
  473. << "</quadratic_attenuation>" << endstr;
  474. const ai_real fallOffAngle = AI_RAD_TO_DEG(light->mAngleInnerCone);
  475. mOutput << startstr << "<falloff_angle sid=\"fall_off_angle\">"
  476. << fallOffAngle
  477. << "</falloff_angle>" << endstr;
  478. double temp = light->mAngleOuterCone - light->mAngleInnerCone;
  479. temp = std::cos(temp);
  480. temp = std::log(temp) / std::log(0.1);
  481. temp = 1 / temp;
  482. mOutput << startstr << "<falloff_exponent sid=\"fall_off_exponent\">"
  483. << temp
  484. << "</falloff_exponent>" << endstr;
  485. PopTag();
  486. mOutput << startstr << "</spot>" << endstr;
  487. }
  488. void ColladaExporter::WriteAmbientLight(const aiLight *const light) {
  489. const aiColor3D &color = light->mColorAmbient;
  490. mOutput << startstr << "<ambient>" << endstr;
  491. PushTag();
  492. mOutput << startstr << "<color sid=\"color\">"
  493. << color.r << " " << color.g << " " << color.b
  494. << "</color>" << endstr;
  495. PopTag();
  496. mOutput << startstr << "</ambient>" << endstr;
  497. }
  498. // ------------------------------------------------------------------------------------------------
  499. // Reads a single surface entry from the given material keys
  500. bool ColladaExporter::ReadMaterialSurface(Surface &poSurface, const aiMaterial &pSrcMat, aiTextureType pTexture, const char *pKey, size_t pType, size_t pIndex) {
  501. if (pSrcMat.GetTextureCount(pTexture) == 0) {
  502. if (pKey)
  503. poSurface.exist = pSrcMat.Get(pKey, static_cast<unsigned int>(pType), static_cast<unsigned int>(pIndex), poSurface.color) == aiReturn_SUCCESS;
  504. return poSurface.exist;
  505. }
  506. aiString texfile;
  507. unsigned int uvChannel = 0;
  508. pSrcMat.GetTexture(pTexture, 0, &texfile, nullptr, &uvChannel);
  509. std::string index_str(texfile.C_Str());
  510. if (index_str.size() != 0 && index_str[0] == '*') {
  511. unsigned int index;
  512. index_str = index_str.substr(1, std::string::npos);
  513. try {
  514. index = (unsigned int)strtoul10_64<DeadlyExportError>(index_str.c_str());
  515. } catch (std::exception &error) {
  516. throw DeadlyExportError(error.what());
  517. }
  518. std::map<unsigned int, std::string>::const_iterator name = textures.find(index);
  519. if (name != textures.end()) {
  520. poSurface.texture = name->second;
  521. } else {
  522. throw DeadlyExportError("could not find embedded texture at index " + index_str);
  523. }
  524. } else {
  525. poSurface.texture = texfile.C_Str();
  526. }
  527. poSurface.channel = uvChannel;
  528. poSurface.exist = true;
  529. return poSurface.exist;
  530. }
  531. // ------------------------------------------------------------------------------------------------
  532. // Reimplementation of isalnum(,C locale), because AppVeyor does not see standard version.
  533. static bool isalnum_C(char c) {
  534. return (nullptr != strchr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", c));
  535. }
  536. // ------------------------------------------------------------------------------------------------
  537. // Writes an image entry for the given surface
  538. void ColladaExporter::WriteImageEntry(const Surface &pSurface, const std::string &imageId) {
  539. if (pSurface.texture.empty()) {
  540. return;
  541. }
  542. mOutput << startstr << "<image id=\"" << imageId << "\">" << endstr;
  543. PushTag();
  544. mOutput << startstr << "<init_from>";
  545. // URL encode image file name first, then XML encode on top
  546. std::stringstream imageUrlEncoded;
  547. for (std::string::const_iterator it = pSurface.texture.begin(); it != pSurface.texture.end(); ++it) {
  548. if (isalnum_C((unsigned char)*it) || *it == ':' || *it == '_' || *it == '-' || *it == '.' || *it == '/' || *it == '\\')
  549. imageUrlEncoded << *it;
  550. else
  551. imageUrlEncoded << '%' << std::hex << size_t((unsigned char)*it) << std::dec;
  552. }
  553. mOutput << XMLEscape(imageUrlEncoded.str());
  554. mOutput << "</init_from>" << endstr;
  555. PopTag();
  556. mOutput << startstr << "</image>" << endstr;
  557. }
  558. // ------------------------------------------------------------------------------------------------
  559. // Writes a color-or-texture entry into an effect definition
  560. void ColladaExporter::WriteTextureColorEntry(const Surface &pSurface, const std::string &pTypeName, const std::string &imageId) {
  561. if (!pSurface.exist) {
  562. return;
  563. }
  564. mOutput << startstr << "<" << pTypeName << ">" << endstr;
  565. PushTag();
  566. if (pSurface.texture.empty()) {
  567. mOutput << startstr << "<color sid=\"" << pTypeName << "\">" << pSurface.color.r << " " << pSurface.color.g << " " << pSurface.color.b << " " << pSurface.color.a << "</color>" << endstr;
  568. } else {
  569. mOutput << startstr << "<texture texture=\"" << imageId << "\" texcoord=\"CHANNEL" << pSurface.channel << "\" />" << endstr;
  570. }
  571. PopTag();
  572. mOutput << startstr << "</" << pTypeName << ">" << endstr;
  573. }
  574. // ------------------------------------------------------------------------------------------------
  575. // Writes the two parameters necessary for referencing a texture in an effect entry
  576. void ColladaExporter::WriteTextureParamEntry(const Surface &pSurface, const std::string &pTypeName, const std::string &materialId) {
  577. // if surface is a texture, write out the sampler and the surface parameters necessary to reference the texture
  578. if (pSurface.texture.empty()) {
  579. return;
  580. }
  581. mOutput << startstr << "<newparam sid=\"" << materialId << "-" << pTypeName << "-surface\">" << endstr;
  582. PushTag();
  583. mOutput << startstr << "<surface type=\"2D\">" << endstr;
  584. PushTag();
  585. mOutput << startstr << "<init_from>" << materialId << "-" << pTypeName << "-image</init_from>" << endstr;
  586. PopTag();
  587. mOutput << startstr << "</surface>" << endstr;
  588. PopTag();
  589. mOutput << startstr << "</newparam>" << endstr;
  590. mOutput << startstr << "<newparam sid=\"" << materialId << "-" << pTypeName << "-sampler\">" << endstr;
  591. PushTag();
  592. mOutput << startstr << "<sampler2D>" << endstr;
  593. PushTag();
  594. mOutput << startstr << "<source>" << materialId << "-" << pTypeName << "-surface</source>" << endstr;
  595. PopTag();
  596. mOutput << startstr << "</sampler2D>" << endstr;
  597. PopTag();
  598. mOutput << startstr << "</newparam>" << endstr;
  599. }
  600. // ------------------------------------------------------------------------------------------------
  601. // Writes a scalar property
  602. void ColladaExporter::WriteFloatEntry(const Property &pProperty, const std::string &pTypeName) {
  603. if (!pProperty.exist) {
  604. return;
  605. }
  606. mOutput << startstr << "<" << pTypeName << ">" << endstr;
  607. PushTag();
  608. mOutput << startstr << "<float sid=\"" << pTypeName << "\">" << pProperty.value << "</float>" << endstr;
  609. PopTag();
  610. mOutput << startstr << "</" << pTypeName << ">" << endstr;
  611. }
  612. // ------------------------------------------------------------------------------------------------
  613. // Writes the material setup
  614. void ColladaExporter::WriteMaterials() {
  615. std::vector<Material> materials;
  616. materials.resize(mScene->mNumMaterials);
  617. /// collect all materials from the scene
  618. size_t numTextures = 0;
  619. for (size_t a = 0; a < mScene->mNumMaterials; ++a) {
  620. Material &material = materials[a];
  621. material.id = GetObjectUniqueId(AiObjectType::Material, a);
  622. material.name = GetObjectName(AiObjectType::Material, a);
  623. const aiMaterial &mat = *(mScene->mMaterials[a]);
  624. aiShadingMode shading = aiShadingMode_Flat;
  625. material.shading_model = "phong";
  626. if (mat.Get(AI_MATKEY_SHADING_MODEL, shading) == aiReturn_SUCCESS) {
  627. if (shading == aiShadingMode_Phong) {
  628. material.shading_model = "phong";
  629. } else if (shading == aiShadingMode_Blinn) {
  630. material.shading_model = "blinn";
  631. } else if (shading == aiShadingMode_NoShading) {
  632. material.shading_model = "constant";
  633. } else if (shading == aiShadingMode_Gouraud) {
  634. material.shading_model = "lambert";
  635. }
  636. }
  637. if (ReadMaterialSurface(material.ambient, mat, aiTextureType_AMBIENT, AI_MATKEY_COLOR_AMBIENT))
  638. ++numTextures;
  639. if (ReadMaterialSurface(material.diffuse, mat, aiTextureType_DIFFUSE, AI_MATKEY_COLOR_DIFFUSE))
  640. ++numTextures;
  641. if (ReadMaterialSurface(material.specular, mat, aiTextureType_SPECULAR, AI_MATKEY_COLOR_SPECULAR))
  642. ++numTextures;
  643. if (ReadMaterialSurface(material.emissive, mat, aiTextureType_EMISSIVE, AI_MATKEY_COLOR_EMISSIVE))
  644. ++numTextures;
  645. if (ReadMaterialSurface(material.reflective, mat, aiTextureType_REFLECTION, AI_MATKEY_COLOR_REFLECTIVE))
  646. ++numTextures;
  647. if (ReadMaterialSurface(material.transparent, mat, aiTextureType_OPACITY, AI_MATKEY_COLOR_TRANSPARENT))
  648. ++numTextures;
  649. if (ReadMaterialSurface(material.normal, mat, aiTextureType_NORMALS, nullptr, 0, 0))
  650. ++numTextures;
  651. material.shininess.exist = mat.Get(AI_MATKEY_SHININESS, material.shininess.value) == aiReturn_SUCCESS;
  652. material.transparency.exist = mat.Get(AI_MATKEY_OPACITY, material.transparency.value) == aiReturn_SUCCESS;
  653. material.index_refraction.exist = mat.Get(AI_MATKEY_REFRACTI, material.index_refraction.value) == aiReturn_SUCCESS;
  654. }
  655. // output textures if present
  656. if (numTextures > 0) {
  657. mOutput << startstr << "<library_images>" << endstr;
  658. PushTag();
  659. for (const Material &mat : materials) {
  660. WriteImageEntry(mat.ambient, mat.id + "-ambient-image");
  661. WriteImageEntry(mat.diffuse, mat.id + "-diffuse-image");
  662. WriteImageEntry(mat.specular, mat.id + "-specular-image");
  663. WriteImageEntry(mat.emissive, mat.id + "-emission-image");
  664. WriteImageEntry(mat.reflective, mat.id + "-reflective-image");
  665. WriteImageEntry(mat.transparent, mat.id + "-transparent-image");
  666. WriteImageEntry(mat.normal, mat.id + "-normal-image");
  667. }
  668. PopTag();
  669. mOutput << startstr << "</library_images>" << endstr;
  670. }
  671. // output effects - those are the actual carriers of information
  672. if (!materials.empty()) {
  673. mOutput << startstr << "<library_effects>" << endstr;
  674. PushTag();
  675. for (const Material &mat : materials) {
  676. // this is so ridiculous it must be right
  677. mOutput << startstr << "<effect id=\"" << mat.id << "-fx\" name=\"" << mat.name << "\">" << endstr;
  678. PushTag();
  679. mOutput << startstr << "<profile_COMMON>" << endstr;
  680. PushTag();
  681. // write sampler- and surface params for the texture entries
  682. WriteTextureParamEntry(mat.emissive, "emission", mat.id);
  683. WriteTextureParamEntry(mat.ambient, "ambient", mat.id);
  684. WriteTextureParamEntry(mat.diffuse, "diffuse", mat.id);
  685. WriteTextureParamEntry(mat.specular, "specular", mat.id);
  686. WriteTextureParamEntry(mat.reflective, "reflective", mat.id);
  687. WriteTextureParamEntry(mat.transparent, "transparent", mat.id);
  688. WriteTextureParamEntry(mat.normal, "normal", mat.id);
  689. mOutput << startstr << "<technique sid=\"standard\">" << endstr;
  690. PushTag();
  691. mOutput << startstr << "<" << mat.shading_model << ">" << endstr;
  692. PushTag();
  693. WriteTextureColorEntry(mat.emissive, "emission", mat.id + "-emission-sampler");
  694. WriteTextureColorEntry(mat.ambient, "ambient", mat.id + "-ambient-sampler");
  695. WriteTextureColorEntry(mat.diffuse, "diffuse", mat.id + "-diffuse-sampler");
  696. WriteTextureColorEntry(mat.specular, "specular", mat.id + "-specular-sampler");
  697. WriteFloatEntry(mat.shininess, "shininess");
  698. WriteTextureColorEntry(mat.reflective, "reflective", mat.id + "-reflective-sampler");
  699. WriteTextureColorEntry(mat.transparent, "transparent", mat.id + "-transparent-sampler");
  700. WriteFloatEntry(mat.transparency, "transparency");
  701. WriteFloatEntry(mat.index_refraction, "index_of_refraction");
  702. if (!mat.normal.texture.empty()) {
  703. WriteTextureColorEntry(mat.normal, "bump", mat.id + "-normal-sampler");
  704. }
  705. PopTag();
  706. mOutput << startstr << "</" << mat.shading_model << ">" << endstr;
  707. PopTag();
  708. mOutput << startstr << "</technique>" << endstr;
  709. PopTag();
  710. mOutput << startstr << "</profile_COMMON>" << endstr;
  711. PopTag();
  712. mOutput << startstr << "</effect>" << endstr;
  713. }
  714. PopTag();
  715. mOutput << startstr << "</library_effects>" << endstr;
  716. // write materials - they're just effect references
  717. mOutput << startstr << "<library_materials>" << endstr;
  718. PushTag();
  719. for (std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it) {
  720. const Material &mat = *it;
  721. mOutput << startstr << "<material id=\"" << mat.id << "\" name=\"" << mat.name << "\">" << endstr;
  722. PushTag();
  723. mOutput << startstr << "<instance_effect url=\"#" << mat.id << "-fx\"/>" << endstr;
  724. PopTag();
  725. mOutput << startstr << "</material>" << endstr;
  726. }
  727. PopTag();
  728. mOutput << startstr << "</library_materials>" << endstr;
  729. }
  730. }
  731. // ------------------------------------------------------------------------------------------------
  732. // Writes the controller library
  733. void ColladaExporter::WriteControllerLibrary() {
  734. mOutput << startstr << "<library_controllers>" << endstr;
  735. PushTag();
  736. for (size_t a = 0; a < mScene->mNumMeshes; ++a) {
  737. WriteController(a);
  738. }
  739. PopTag();
  740. mOutput << startstr << "</library_controllers>" << endstr;
  741. }
  742. // ------------------------------------------------------------------------------------------------
  743. // Writes a skin controller of the given mesh
  744. void ColladaExporter::WriteController(size_t pIndex) {
  745. const aiMesh *mesh = mScene->mMeshes[pIndex];
  746. // Is there a skin controller?
  747. if (mesh->mNumBones == 0 || mesh->mNumFaces == 0 || mesh->mNumVertices == 0) {
  748. return;
  749. }
  750. const std::string idstr = GetObjectUniqueId(AiObjectType::Mesh, pIndex);
  751. const std::string namestr = GetObjectName(AiObjectType::Mesh, pIndex);
  752. mOutput << startstr << "<controller id=\"" << idstr << "-skin\" ";
  753. mOutput << "name=\"skinCluster" << pIndex << "\">" << endstr;
  754. PushTag();
  755. mOutput << startstr << "<skin source=\"#" << idstr << "\">" << endstr;
  756. PushTag();
  757. // bind pose matrix
  758. mOutput << startstr << "<bind_shape_matrix>" << endstr;
  759. PushTag();
  760. // I think it is identity in general cases.
  761. aiMatrix4x4 mat;
  762. mOutput << startstr << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << endstr;
  763. mOutput << startstr << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << endstr;
  764. mOutput << startstr << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << endstr;
  765. mOutput << startstr << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4 << endstr;
  766. PopTag();
  767. mOutput << startstr << "</bind_shape_matrix>" << endstr;
  768. mOutput << startstr << "<source id=\"" << idstr << "-skin-joints\" name=\"" << namestr << "-skin-joints\">" << endstr;
  769. PushTag();
  770. mOutput << startstr << "<Name_array id=\"" << idstr << "-skin-joints-array\" count=\"" << mesh->mNumBones << "\">";
  771. for (size_t i = 0; i < mesh->mNumBones; ++i) {
  772. mOutput << GetBoneUniqueId(mesh->mBones[i]) << ' ';
  773. }
  774. mOutput << "</Name_array>" << endstr;
  775. mOutput << startstr << "<technique_common>" << endstr;
  776. PushTag();
  777. mOutput << startstr << "<accessor source=\"#" << idstr << "-skin-joints-array\" count=\"" << mesh->mNumBones << "\" stride=\"" << 1 << "\">" << endstr;
  778. PushTag();
  779. mOutput << startstr << "<param name=\"JOINT\" type=\"Name\"></param>" << endstr;
  780. PopTag();
  781. mOutput << startstr << "</accessor>" << endstr;
  782. PopTag();
  783. mOutput << startstr << "</technique_common>" << endstr;
  784. PopTag();
  785. mOutput << startstr << "</source>" << endstr;
  786. std::vector<ai_real> bind_poses;
  787. bind_poses.reserve(mesh->mNumBones * 16);
  788. for (unsigned int i = 0; i < mesh->mNumBones; ++i) {
  789. for (unsigned int j = 0; j < 4; ++j) {
  790. bind_poses.insert(bind_poses.end(), mesh->mBones[i]->mOffsetMatrix[j], mesh->mBones[i]->mOffsetMatrix[j] + 4);
  791. }
  792. }
  793. WriteFloatArray(idstr + "-skin-bind_poses", FloatType_Mat4x4, (const ai_real *)bind_poses.data(), bind_poses.size() / 16);
  794. bind_poses.clear();
  795. std::vector<ai_real> skin_weights;
  796. skin_weights.reserve(mesh->mNumVertices * mesh->mNumBones);
  797. for (size_t i = 0; i < mesh->mNumBones; ++i) {
  798. for (size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j) {
  799. skin_weights.push_back(mesh->mBones[i]->mWeights[j].mWeight);
  800. }
  801. }
  802. WriteFloatArray(idstr + "-skin-weights", FloatType_Weight, (const ai_real *)skin_weights.data(), skin_weights.size());
  803. skin_weights.clear();
  804. mOutput << startstr << "<joints>" << endstr;
  805. PushTag();
  806. mOutput << startstr << "<input semantic=\"JOINT\" source=\"#" << idstr << "-skin-joints\"></input>" << endstr;
  807. mOutput << startstr << "<input semantic=\"INV_BIND_MATRIX\" source=\"#" << idstr << "-skin-bind_poses\"></input>" << endstr;
  808. PopTag();
  809. mOutput << startstr << "</joints>" << endstr;
  810. mOutput << startstr << "<vertex_weights count=\"" << mesh->mNumVertices << "\">" << endstr;
  811. PushTag();
  812. mOutput << startstr << "<input semantic=\"JOINT\" source=\"#" << idstr << "-skin-joints\" offset=\"0\"></input>" << endstr;
  813. mOutput << startstr << "<input semantic=\"WEIGHT\" source=\"#" << idstr << "-skin-weights\" offset=\"1\"></input>" << endstr;
  814. mOutput << startstr << "<vcount>";
  815. std::vector<ai_uint> num_influences(mesh->mNumVertices, (ai_uint)0);
  816. for (size_t i = 0; i < mesh->mNumBones; ++i) {
  817. for (size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j) {
  818. ++num_influences[mesh->mBones[i]->mWeights[j].mVertexId];
  819. }
  820. }
  821. for (size_t i = 0; i < mesh->mNumVertices; ++i) {
  822. mOutput << num_influences[i] << " ";
  823. }
  824. mOutput << "</vcount>" << endstr;
  825. mOutput << startstr << "<v>";
  826. ai_uint joint_weight_indices_length = 0;
  827. std::vector<ai_uint> accum_influences;
  828. accum_influences.reserve(num_influences.size());
  829. for (size_t i = 0; i < num_influences.size(); ++i) {
  830. accum_influences.push_back(joint_weight_indices_length);
  831. joint_weight_indices_length += num_influences[i];
  832. }
  833. ai_uint weight_index = 0;
  834. std::vector<ai_int> joint_weight_indices(2 * joint_weight_indices_length, (ai_int)-1);
  835. for (unsigned int i = 0; i < mesh->mNumBones; ++i) {
  836. for (unsigned j = 0; j < mesh->mBones[i]->mNumWeights; ++j) {
  837. unsigned int vId = mesh->mBones[i]->mWeights[j].mVertexId;
  838. for (ai_uint k = 0; k < num_influences[vId]; ++k) {
  839. if (joint_weight_indices[2 * (accum_influences[vId] + k)] == -1) {
  840. joint_weight_indices[2 * (accum_influences[vId] + k)] = i;
  841. joint_weight_indices[2 * (accum_influences[vId] + k) + 1] = weight_index;
  842. break;
  843. }
  844. }
  845. ++weight_index;
  846. }
  847. }
  848. for (size_t i = 0; i < joint_weight_indices.size(); ++i) {
  849. mOutput << joint_weight_indices[i] << " ";
  850. }
  851. num_influences.clear();
  852. accum_influences.clear();
  853. joint_weight_indices.clear();
  854. mOutput << "</v>" << endstr;
  855. PopTag();
  856. mOutput << startstr << "</vertex_weights>" << endstr;
  857. PopTag();
  858. mOutput << startstr << "</skin>" << endstr;
  859. PopTag();
  860. mOutput << startstr << "</controller>" << endstr;
  861. }
  862. // ------------------------------------------------------------------------------------------------
  863. // Writes the geometry library
  864. void ColladaExporter::WriteGeometryLibrary() {
  865. mOutput << startstr << "<library_geometries>" << endstr;
  866. PushTag();
  867. for (size_t a = 0; a < mScene->mNumMeshes; ++a) {
  868. WriteGeometry(a);
  869. }
  870. PopTag();
  871. mOutput << startstr << "</library_geometries>" << endstr;
  872. }
  873. // ------------------------------------------------------------------------------------------------
  874. // Writes the given mesh
  875. void ColladaExporter::WriteGeometry(size_t pIndex) {
  876. const aiMesh *mesh = mScene->mMeshes[pIndex];
  877. const std::string geometryId = GetObjectUniqueId(AiObjectType::Mesh, pIndex);
  878. const std::string geometryName = GetObjectName(AiObjectType::Mesh, pIndex);
  879. if (mesh->mNumFaces == 0 || mesh->mNumVertices == 0) {
  880. return;
  881. }
  882. // opening tag
  883. mOutput << startstr << "<geometry id=\"" << geometryId << "\" name=\"" << geometryName << "\" >" << endstr;
  884. PushTag();
  885. mOutput << startstr << "<mesh>" << endstr;
  886. PushTag();
  887. // Positions
  888. WriteFloatArray(geometryId + "-positions", FloatType_Vector, (ai_real *)mesh->mVertices, mesh->mNumVertices);
  889. // Normals, if any
  890. if (mesh->HasNormals()) {
  891. WriteFloatArray(geometryId + "-normals", FloatType_Vector, (ai_real *)mesh->mNormals, mesh->mNumVertices);
  892. }
  893. // texture coords
  894. for (size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) {
  895. if (mesh->HasTextureCoords(static_cast<unsigned int>(a))) {
  896. WriteFloatArray(geometryId + "-tex" + ai_to_string(a), mesh->mNumUVComponents[a] == 3 ? FloatType_TexCoord3 : FloatType_TexCoord2,
  897. (ai_real *)mesh->mTextureCoords[a], mesh->mNumVertices);
  898. }
  899. }
  900. // vertex colors
  901. for (size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) {
  902. if (mesh->HasVertexColors(static_cast<unsigned int>(a)))
  903. WriteFloatArray(geometryId + "-color" + ai_to_string(a), FloatType_Color, (ai_real *)mesh->mColors[a], mesh->mNumVertices);
  904. }
  905. // assemble vertex structure
  906. // Only write input for POSITION since we will write other as shared inputs in polygon definition
  907. mOutput << startstr << "<vertices id=\"" << geometryId << "-vertices"
  908. << "\">" << endstr;
  909. PushTag();
  910. mOutput << startstr << "<input semantic=\"POSITION\" source=\"#" << geometryId << "-positions\" />" << endstr;
  911. PopTag();
  912. mOutput << startstr << "</vertices>" << endstr;
  913. // count the number of lines, triangles and polygon meshes
  914. int countLines = 0;
  915. int countPoly = 0;
  916. for (size_t a = 0; a < mesh->mNumFaces; ++a) {
  917. if (mesh->mFaces[a].mNumIndices == 2) {
  918. countLines++;
  919. } else if (mesh->mFaces[a].mNumIndices >= 3) {
  920. countPoly++;
  921. }
  922. }
  923. // lines
  924. if (countLines) {
  925. mOutput << startstr << "<lines count=\"" << countLines << "\" material=\"defaultMaterial\">" << endstr;
  926. PushTag();
  927. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << geometryId << "-vertices\" />" << endstr;
  928. if (mesh->HasNormals()) {
  929. mOutput << startstr << "<input semantic=\"NORMAL\" source=\"#" << geometryId << "-normals\" />" << endstr;
  930. }
  931. for (size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) {
  932. if (mesh->HasTextureCoords(static_cast<unsigned int>(a))) {
  933. mOutput << startstr
  934. << "<input semantic=\"TEXCOORD\" source=\"#"
  935. << geometryId
  936. << "-tex" << a << "\" "
  937. << "set=\"" << a << "\""
  938. << " />" << endstr;
  939. }
  940. }
  941. for (size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a) {
  942. if (mesh->HasVertexColors(static_cast<unsigned int>(a)))
  943. mOutput << startstr << "<input semantic=\"COLOR\" source=\"#" << geometryId << "-color" << a << "\" "
  944. << "set=\"" << a << "\""
  945. << " />" << endstr;
  946. }
  947. mOutput << startstr << "<p>";
  948. for (size_t a = 0; a < mesh->mNumFaces; ++a) {
  949. const aiFace &face = mesh->mFaces[a];
  950. if (face.mNumIndices != 2) continue;
  951. for (size_t b = 0; b < face.mNumIndices; ++b) {
  952. mOutput << face.mIndices[b] << " ";
  953. }
  954. }
  955. mOutput << "</p>" << endstr;
  956. PopTag();
  957. mOutput << startstr << "</lines>" << endstr;
  958. }
  959. // triangle - don't use it, because compatibility problems
  960. // polygons
  961. if (countPoly) {
  962. mOutput << startstr << "<polylist count=\"" << countPoly << "\" material=\"defaultMaterial\">" << endstr;
  963. PushTag();
  964. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << geometryId << "-vertices\" />" << endstr;
  965. if (mesh->HasNormals()) {
  966. mOutput << startstr << "<input offset=\"0\" semantic=\"NORMAL\" source=\"#" << geometryId << "-normals\" />" << endstr;
  967. }
  968. for (size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) {
  969. if (mesh->HasTextureCoords(static_cast<unsigned int>(a)))
  970. mOutput << startstr << "<input offset=\"0\" semantic=\"TEXCOORD\" source=\"#" << geometryId << "-tex" << a << "\" "
  971. << "set=\"" << a << "\""
  972. << " />" << endstr;
  973. }
  974. for (size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a) {
  975. if (mesh->HasVertexColors(static_cast<unsigned int>(a)))
  976. mOutput << startstr << "<input offset=\"0\" semantic=\"COLOR\" source=\"#" << geometryId << "-color" << a << "\" "
  977. << "set=\"" << a << "\""
  978. << " />" << endstr;
  979. }
  980. mOutput << startstr << "<vcount>";
  981. for (size_t a = 0; a < mesh->mNumFaces; ++a) {
  982. if (mesh->mFaces[a].mNumIndices < 3) continue;
  983. mOutput << mesh->mFaces[a].mNumIndices << " ";
  984. }
  985. mOutput << "</vcount>" << endstr;
  986. mOutput << startstr << "<p>";
  987. for (size_t a = 0; a < mesh->mNumFaces; ++a) {
  988. const aiFace &face = mesh->mFaces[a];
  989. if (face.mNumIndices < 3) continue;
  990. for (size_t b = 0; b < face.mNumIndices; ++b) {
  991. mOutput << face.mIndices[b] << " ";
  992. }
  993. }
  994. mOutput << "</p>" << endstr;
  995. PopTag();
  996. mOutput << startstr << "</polylist>" << endstr;
  997. }
  998. // closing tags
  999. PopTag();
  1000. mOutput << startstr << "</mesh>" << endstr;
  1001. PopTag();
  1002. mOutput << startstr << "</geometry>" << endstr;
  1003. }
  1004. // ------------------------------------------------------------------------------------------------
  1005. // Writes a float array of the given type
  1006. void ColladaExporter::WriteFloatArray(const std::string &pIdString, FloatDataType pType, const ai_real *pData, size_t pElementCount) {
  1007. size_t floatsPerElement = 0;
  1008. switch (pType) {
  1009. case FloatType_Vector:
  1010. floatsPerElement = 3;
  1011. break;
  1012. case FloatType_TexCoord2:
  1013. floatsPerElement = 2;
  1014. break;
  1015. case FloatType_TexCoord3:
  1016. floatsPerElement = 3;
  1017. break;
  1018. case FloatType_Color:
  1019. floatsPerElement = 3;
  1020. break;
  1021. case FloatType_Mat4x4:
  1022. floatsPerElement = 16;
  1023. break;
  1024. case FloatType_Weight:
  1025. floatsPerElement = 1;
  1026. break;
  1027. case FloatType_Time:
  1028. floatsPerElement = 1;
  1029. break;
  1030. default:
  1031. return;
  1032. }
  1033. std::string arrayId = XMLIDEncode(pIdString) + "-array";
  1034. mOutput << startstr << "<source id=\"" << XMLIDEncode(pIdString) << "\" name=\"" << XMLEscape(pIdString) << "\">" << endstr;
  1035. PushTag();
  1036. // source array
  1037. mOutput << startstr << "<float_array id=\"" << arrayId << "\" count=\"" << pElementCount * floatsPerElement << "\"> ";
  1038. PushTag();
  1039. if (pType == FloatType_TexCoord2) {
  1040. for (size_t a = 0; a < pElementCount; ++a) {
  1041. mOutput << pData[a * 3 + 0] << " ";
  1042. mOutput << pData[a * 3 + 1] << " ";
  1043. }
  1044. } else if (pType == FloatType_Color) {
  1045. for (size_t a = 0; a < pElementCount; ++a) {
  1046. mOutput << pData[a * 4 + 0] << " ";
  1047. mOutput << pData[a * 4 + 1] << " ";
  1048. mOutput << pData[a * 4 + 2] << " ";
  1049. }
  1050. } else {
  1051. for (size_t a = 0; a < pElementCount * floatsPerElement; ++a) {
  1052. mOutput << pData[a] << " ";
  1053. }
  1054. }
  1055. mOutput << "</float_array>" << endstr;
  1056. PopTag();
  1057. // the usual Collada fun. Let's bloat it even more!
  1058. mOutput << startstr << "<technique_common>" << endstr;
  1059. PushTag();
  1060. mOutput << startstr << "<accessor count=\"" << pElementCount << "\" offset=\"0\" source=\"#" << arrayId << "\" stride=\"" << floatsPerElement << "\">" << endstr;
  1061. PushTag();
  1062. switch (pType) {
  1063. case FloatType_Vector:
  1064. mOutput << startstr << "<param name=\"X\" type=\"float\" />" << endstr;
  1065. mOutput << startstr << "<param name=\"Y\" type=\"float\" />" << endstr;
  1066. mOutput << startstr << "<param name=\"Z\" type=\"float\" />" << endstr;
  1067. break;
  1068. case FloatType_TexCoord2:
  1069. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  1070. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  1071. break;
  1072. case FloatType_TexCoord3:
  1073. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  1074. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  1075. mOutput << startstr << "<param name=\"P\" type=\"float\" />" << endstr;
  1076. break;
  1077. case FloatType_Color:
  1078. mOutput << startstr << "<param name=\"R\" type=\"float\" />" << endstr;
  1079. mOutput << startstr << "<param name=\"G\" type=\"float\" />" << endstr;
  1080. mOutput << startstr << "<param name=\"B\" type=\"float\" />" << endstr;
  1081. break;
  1082. case FloatType_Mat4x4:
  1083. mOutput << startstr << "<param name=\"TRANSFORM\" type=\"float4x4\" />" << endstr;
  1084. break;
  1085. case FloatType_Weight:
  1086. mOutput << startstr << "<param name=\"WEIGHT\" type=\"float\" />" << endstr;
  1087. break;
  1088. // customized, add animation related
  1089. case FloatType_Time:
  1090. mOutput << startstr << "<param name=\"TIME\" type=\"float\" />" << endstr;
  1091. break;
  1092. }
  1093. PopTag();
  1094. mOutput << startstr << "</accessor>" << endstr;
  1095. PopTag();
  1096. mOutput << startstr << "</technique_common>" << endstr;
  1097. PopTag();
  1098. mOutput << startstr << "</source>" << endstr;
  1099. }
  1100. // ------------------------------------------------------------------------------------------------
  1101. // Writes the scene library
  1102. void ColladaExporter::WriteSceneLibrary() {
  1103. // Determine if we are using the aiScene root or our own
  1104. std::string sceneName("Scene");
  1105. if (mAdd_root_node) {
  1106. mSceneId = MakeUniqueId(mUniqueIds, sceneName, std::string());
  1107. mUniqueIds.insert(mSceneId);
  1108. } else {
  1109. mSceneId = GetNodeUniqueId(mScene->mRootNode);
  1110. sceneName = GetNodeName(mScene->mRootNode);
  1111. }
  1112. mOutput << startstr << "<library_visual_scenes>" << endstr;
  1113. PushTag();
  1114. mOutput << startstr << "<visual_scene id=\"" + mSceneId + "\" name=\"" + sceneName + "\">" << endstr;
  1115. PushTag();
  1116. if (mAdd_root_node) {
  1117. // Export the root node
  1118. WriteNode(mScene->mRootNode);
  1119. } else {
  1120. // Have already exported the root node
  1121. for (size_t a = 0; a < mScene->mRootNode->mNumChildren; ++a)
  1122. WriteNode(mScene->mRootNode->mChildren[a]);
  1123. }
  1124. PopTag();
  1125. mOutput << startstr << "</visual_scene>" << endstr;
  1126. PopTag();
  1127. mOutput << startstr << "</library_visual_scenes>" << endstr;
  1128. }
  1129. // ------------------------------------------------------------------------------------------------
  1130. void ColladaExporter::WriteAnimationLibrary(size_t pIndex) {
  1131. const aiAnimation *anim = mScene->mAnimations[pIndex];
  1132. if (anim == nullptr) {
  1133. return;
  1134. }
  1135. if (anim->mNumChannels == 0 && anim->mNumMeshChannels == 0 && anim->mNumMorphMeshChannels == 0) {
  1136. return;
  1137. }
  1138. const std::string animationNameEscaped = GetObjectName(AiObjectType::Animation, pIndex);
  1139. const std::string idstrEscaped = GetObjectUniqueId(AiObjectType::Animation, pIndex);
  1140. mOutput << startstr << "<animation id=\"" + idstrEscaped + "\" name=\"" + animationNameEscaped + "\">" << endstr;
  1141. PushTag();
  1142. std::string cur_node_idstr;
  1143. for (size_t a = 0; a < anim->mNumChannels; ++a) {
  1144. const aiNodeAnim *nodeAnim = anim->mChannels[a];
  1145. if (nodeAnim == nullptr) {
  1146. continue;
  1147. }
  1148. // sanity checks
  1149. if (nodeAnim->mNumPositionKeys != nodeAnim->mNumScalingKeys || nodeAnim->mNumPositionKeys != nodeAnim->mNumRotationKeys) {
  1150. continue;
  1151. }
  1152. {
  1153. cur_node_idstr.clear();
  1154. cur_node_idstr += nodeAnim->mNodeName.data;
  1155. cur_node_idstr += std::string("_matrix-input");
  1156. std::vector<ai_real> frames;
  1157. for (size_t i = 0; i < nodeAnim->mNumPositionKeys; ++i) {
  1158. frames.push_back(static_cast<ai_real>(nodeAnim->mPositionKeys[i].mTime));
  1159. }
  1160. WriteFloatArray(cur_node_idstr, FloatType_Time, (const ai_real *)frames.data(), frames.size());
  1161. frames.clear();
  1162. }
  1163. {
  1164. cur_node_idstr.clear();
  1165. cur_node_idstr += nodeAnim->mNodeName.data;
  1166. cur_node_idstr += std::string("_matrix-output");
  1167. std::vector<ai_real> keyframes;
  1168. keyframes.reserve(nodeAnim->mNumPositionKeys * 16);
  1169. for (size_t i = 0; i < nodeAnim->mNumPositionKeys; ++i) {
  1170. aiVector3D Scaling = nodeAnim->mScalingKeys[i].mValue;
  1171. aiMatrix4x4 ScalingM; // identity
  1172. ScalingM[0][0] = Scaling.x;
  1173. ScalingM[1][1] = Scaling.y;
  1174. ScalingM[2][2] = Scaling.z;
  1175. aiQuaternion RotationQ = nodeAnim->mRotationKeys[i].mValue;
  1176. aiMatrix4x4 s = aiMatrix4x4(RotationQ.GetMatrix());
  1177. aiMatrix4x4 RotationM(s.a1, s.a2, s.a3, 0, s.b1, s.b2, s.b3, 0, s.c1, s.c2, s.c3, 0, 0, 0, 0, 1);
  1178. aiVector3D Translation = nodeAnim->mPositionKeys[i].mValue;
  1179. aiMatrix4x4 TranslationM; // identity
  1180. TranslationM[0][3] = Translation.x;
  1181. TranslationM[1][3] = Translation.y;
  1182. TranslationM[2][3] = Translation.z;
  1183. // Combine the above transformations
  1184. aiMatrix4x4 mat = TranslationM * RotationM * ScalingM;
  1185. for (unsigned int j = 0; j < 4; ++j) {
  1186. keyframes.insert(keyframes.end(), mat[j], mat[j] + 4);
  1187. }
  1188. }
  1189. WriteFloatArray(cur_node_idstr, FloatType_Mat4x4, (const ai_real *)keyframes.data(), keyframes.size() / 16);
  1190. }
  1191. {
  1192. std::vector<std::string> names;
  1193. for (size_t i = 0; i < nodeAnim->mNumPositionKeys; ++i) {
  1194. if (nodeAnim->mPreState == aiAnimBehaviour_DEFAULT || nodeAnim->mPreState == aiAnimBehaviour_LINEAR || nodeAnim->mPreState == aiAnimBehaviour_REPEAT) {
  1195. names.emplace_back("LINEAR");
  1196. } else if (nodeAnim->mPostState == aiAnimBehaviour_CONSTANT) {
  1197. names.emplace_back("STEP");
  1198. }
  1199. }
  1200. const std::string cur_node_idstr2 = nodeAnim->mNodeName.data + std::string("_matrix-interpolation");
  1201. std::string arrayId = XMLIDEncode(cur_node_idstr2) + "-array";
  1202. mOutput << startstr << "<source id=\"" << XMLIDEncode(cur_node_idstr2) << "\">" << endstr;
  1203. PushTag();
  1204. // source array
  1205. mOutput << startstr << "<Name_array id=\"" << arrayId << "\" count=\"" << names.size() << "\"> ";
  1206. for (size_t aa = 0; aa < names.size(); ++aa) {
  1207. mOutput << names[aa] << " ";
  1208. }
  1209. mOutput << "</Name_array>" << endstr;
  1210. mOutput << startstr << "<technique_common>" << endstr;
  1211. PushTag();
  1212. mOutput << startstr << "<accessor source=\"#" << arrayId << "\" count=\"" << names.size() << "\" stride=\"" << 1 << "\">" << endstr;
  1213. PushTag();
  1214. mOutput << startstr << "<param name=\"INTERPOLATION\" type=\"name\"></param>" << endstr;
  1215. PopTag();
  1216. mOutput << startstr << "</accessor>" << endstr;
  1217. PopTag();
  1218. mOutput << startstr << "</technique_common>" << endstr;
  1219. PopTag();
  1220. mOutput << startstr << "</source>" << endstr;
  1221. }
  1222. }
  1223. for (size_t a = 0; a < anim->mNumChannels; ++a) {
  1224. const aiNodeAnim *nodeAnim = anim->mChannels[a];
  1225. if (nodeAnim == nullptr) {
  1226. continue;
  1227. }
  1228. {
  1229. // samplers
  1230. const std::string node_idstr = nodeAnim->mNodeName.data + std::string("_matrix-sampler");
  1231. mOutput << startstr << "<sampler id=\"" << XMLIDEncode(node_idstr) << "\">" << endstr;
  1232. PushTag();
  1233. mOutput << startstr << "<input semantic=\"INPUT\" source=\"#" << XMLIDEncode(nodeAnim->mNodeName.data + std::string("_matrix-input")) << "\"/>" << endstr;
  1234. mOutput << startstr << "<input semantic=\"OUTPUT\" source=\"#" << XMLIDEncode(nodeAnim->mNodeName.data + std::string("_matrix-output")) << "\"/>" << endstr;
  1235. mOutput << startstr << "<input semantic=\"INTERPOLATION\" source=\"#" << XMLIDEncode(nodeAnim->mNodeName.data + std::string("_matrix-interpolation")) << "\"/>" << endstr;
  1236. PopTag();
  1237. mOutput << startstr << "</sampler>" << endstr;
  1238. }
  1239. }
  1240. for (size_t a = 0; a < anim->mNumChannels; ++a) {
  1241. const aiNodeAnim *nodeAnim = anim->mChannels[a];
  1242. if (nodeAnim == nullptr) {
  1243. continue;
  1244. }
  1245. {
  1246. // channels
  1247. mOutput << startstr
  1248. << "<channel source=\"#"
  1249. << XMLIDEncode(nodeAnim->mNodeName.data + std::string("_matrix-sampler"))
  1250. << "\" target=\""
  1251. << XMLIDEncode(nodeAnim->mNodeName.data)
  1252. << "/matrix\"/>"
  1253. << endstr;
  1254. }
  1255. }
  1256. PopTag();
  1257. mOutput << startstr << "</animation>" << endstr;
  1258. }
  1259. // ------------------------------------------------------------------------------------------------
  1260. void ColladaExporter::WriteAnimationsLibrary() {
  1261. if (mScene->mNumAnimations == 0) {
  1262. return;
  1263. }
  1264. mOutput << startstr << "<library_animations>" << endstr;
  1265. PushTag();
  1266. // start recursive write at the root node
  1267. for (size_t a = 0; a < mScene->mNumAnimations; ++a) {
  1268. WriteAnimationLibrary(a);
  1269. }
  1270. PopTag();
  1271. mOutput << startstr << "</library_animations>" << endstr;
  1272. }
  1273. // ------------------------------------------------------------------------------------------------
  1274. // Recursively writes the given node
  1275. void ColladaExporter::WriteNode(const aiNode *pNode) {
  1276. // If the node is associated with a bone, it is a joint node (JOINT)
  1277. // otherwise it is a normal node (NODE)
  1278. // Assimp-specific: nodes with no name cannot be associated with bones
  1279. const char *node_type;
  1280. bool is_joint, is_skeleton_root = false;
  1281. if (pNode->mName.length == 0 || nullptr == mScene->findBone(pNode->mName)) {
  1282. node_type = "NODE";
  1283. is_joint = false;
  1284. } else {
  1285. node_type = "JOINT";
  1286. is_joint = true;
  1287. if (!pNode->mParent || nullptr == mScene->findBone(pNode->mParent->mName)) {
  1288. is_skeleton_root = true;
  1289. }
  1290. }
  1291. const std::string node_id = GetNodeUniqueId(pNode);
  1292. const std::string node_name = GetNodeName(pNode);
  1293. mOutput << startstr << "<node ";
  1294. if (is_skeleton_root) {
  1295. mFoundSkeletonRootNodeID = node_id; // For now, only support one skeleton in a scene.
  1296. }
  1297. mOutput << "id=\"" << node_id << "\" " << (is_joint ? "sid=\"" + node_id + "\" " : "");
  1298. mOutput << "name=\"" << node_name
  1299. << "\" type=\"" << node_type
  1300. << "\">" << endstr;
  1301. PushTag();
  1302. // write transformation - we can directly put the matrix there
  1303. // TODO: (thom) decompose into scale - rot - quad to allow addressing it by animations afterwards
  1304. aiMatrix4x4 mat = pNode->mTransformation;
  1305. // If this node is a Camera node, the camera coordinate system needs to be multiplied in.
  1306. // When importing from Collada, the mLookAt is set to 0, 0, -1, and the node transform is unchanged.
  1307. // When importing from a different format, mLookAt is set to 0, 0, 1. Therefore, the local camera
  1308. // coordinate system must be changed to matche the Collada specification.
  1309. for (size_t i = 0; i < mScene->mNumCameras; i++) {
  1310. if (mScene->mCameras[i]->mName == pNode->mName) {
  1311. aiMatrix4x4 sourceView;
  1312. mScene->mCameras[i]->GetCameraMatrix(sourceView);
  1313. aiMatrix4x4 colladaView;
  1314. colladaView.a1 = colladaView.c3 = -1; // move into -z space.
  1315. mat *= (sourceView * colladaView);
  1316. break;
  1317. }
  1318. }
  1319. // customized, sid should be 'matrix' to match with loader code.
  1320. mOutput << startstr << "<matrix sid=\"matrix\">";
  1321. mOutput << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << " ";
  1322. mOutput << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << " ";
  1323. mOutput << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << " ";
  1324. mOutput << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4;
  1325. mOutput << "</matrix>" << endstr;
  1326. if (pNode->mNumMeshes == 0) {
  1327. //check if it is a camera node
  1328. for (size_t i = 0; i < mScene->mNumCameras; i++) {
  1329. if (mScene->mCameras[i]->mName == pNode->mName) {
  1330. mOutput << startstr << "<instance_camera url=\"#" << GetObjectUniqueId(AiObjectType::Camera, i) << "\"/>" << endstr;
  1331. break;
  1332. }
  1333. }
  1334. //check if it is a light node
  1335. for (size_t i = 0; i < mScene->mNumLights; i++) {
  1336. if (mScene->mLights[i]->mName == pNode->mName) {
  1337. mOutput << startstr << "<instance_light url=\"#" << GetObjectUniqueId(AiObjectType::Light, i) << "\"/>" << endstr;
  1338. break;
  1339. }
  1340. }
  1341. } else
  1342. // instance every geometry
  1343. for (size_t a = 0; a < pNode->mNumMeshes; ++a) {
  1344. const aiMesh *mesh = mScene->mMeshes[pNode->mMeshes[a]];
  1345. // do not instantiate mesh if empty. I wonder how this could happen
  1346. if (mesh->mNumFaces == 0 || mesh->mNumVertices == 0)
  1347. continue;
  1348. const std::string meshId = GetObjectUniqueId(AiObjectType::Mesh, pNode->mMeshes[a]);
  1349. if (mesh->mNumBones == 0) {
  1350. mOutput << startstr << "<instance_geometry url=\"#" << meshId << "\">" << endstr;
  1351. PushTag();
  1352. } else {
  1353. mOutput << startstr
  1354. << "<instance_controller url=\"#" << meshId << "-skin\">"
  1355. << endstr;
  1356. PushTag();
  1357. // note! this mFoundSkeletonRootNodeID some how affects animation, it makes the mesh attaches to armature skeleton root node.
  1358. // use the first bone to find skeleton root
  1359. const aiNode *skeletonRootBoneNode = findSkeletonRootNode(mScene, mesh);
  1360. if (skeletonRootBoneNode) {
  1361. mFoundSkeletonRootNodeID = GetNodeUniqueId(skeletonRootBoneNode);
  1362. }
  1363. mOutput << startstr << "<skeleton>#" << mFoundSkeletonRootNodeID << "</skeleton>" << endstr;
  1364. }
  1365. mOutput << startstr << "<bind_material>" << endstr;
  1366. PushTag();
  1367. mOutput << startstr << "<technique_common>" << endstr;
  1368. PushTag();
  1369. mOutput << startstr << "<instance_material symbol=\"defaultMaterial\" target=\"#" << GetObjectUniqueId(AiObjectType::Material, mesh->mMaterialIndex) << "\">" << endstr;
  1370. PushTag();
  1371. for (size_t aa = 0; aa < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++aa) {
  1372. if (mesh->HasTextureCoords(static_cast<unsigned int>(aa)))
  1373. // semantic as in <texture texcoord=...>
  1374. // input_semantic as in <input semantic=...>
  1375. // input_set as in <input set=...>
  1376. mOutput << startstr << "<bind_vertex_input semantic=\"CHANNEL" << aa << "\" input_semantic=\"TEXCOORD\" input_set=\"" << aa << "\"/>" << endstr;
  1377. }
  1378. PopTag();
  1379. mOutput << startstr << "</instance_material>" << endstr;
  1380. PopTag();
  1381. mOutput << startstr << "</technique_common>" << endstr;
  1382. PopTag();
  1383. mOutput << startstr << "</bind_material>" << endstr;
  1384. PopTag();
  1385. if (mesh->mNumBones == 0)
  1386. mOutput << startstr << "</instance_geometry>" << endstr;
  1387. else
  1388. mOutput << startstr << "</instance_controller>" << endstr;
  1389. }
  1390. // recurse into subnodes
  1391. for (size_t a = 0; a < pNode->mNumChildren; ++a) {
  1392. WriteNode(pNode->mChildren[a]);
  1393. }
  1394. PopTag();
  1395. mOutput << startstr << "</node>" << endstr;
  1396. }
  1397. void ColladaExporter::CreateNodeIds(const aiNode *node) {
  1398. GetNodeUniqueId(node);
  1399. for (size_t a = 0; a < node->mNumChildren; ++a)
  1400. CreateNodeIds(node->mChildren[a]);
  1401. }
  1402. std::string ColladaExporter::GetNodeUniqueId(const aiNode *node) {
  1403. // Use the pointer as the key. This is safe because the scene is immutable.
  1404. auto idIt = mNodeIdMap.find(node);
  1405. if (idIt != mNodeIdMap.cend()) {
  1406. return idIt->second;
  1407. }
  1408. // Prefer the requested Collada Id if extant
  1409. std::string idStr;
  1410. aiString origId;
  1411. if (node->mMetaData && node->mMetaData->Get(AI_METADATA_COLLADA_ID, origId)) {
  1412. idStr = origId.C_Str();
  1413. } else {
  1414. idStr = node->mName.C_Str();
  1415. }
  1416. // Make sure the requested id is valid
  1417. if (idStr.empty()) {
  1418. idStr = "node";
  1419. } else {
  1420. idStr = XMLIDEncode(idStr);
  1421. }
  1422. // Ensure it's unique
  1423. idStr = MakeUniqueId(mUniqueIds, idStr, std::string());
  1424. mUniqueIds.insert(idStr);
  1425. mNodeIdMap.insert(std::make_pair(node, idStr));
  1426. return idStr;
  1427. }
  1428. std::string ColladaExporter::GetNodeName(const aiNode *node) {
  1429. if (node == nullptr) {
  1430. return std::string();
  1431. }
  1432. return XMLEscape(node->mName.C_Str());
  1433. }
  1434. std::string ColladaExporter::GetBoneUniqueId(const aiBone *bone) {
  1435. // Find the Node that is this Bone
  1436. const aiNode *boneNode = mScene->mRootNode->findBoneNode(bone);
  1437. if (boneNode == nullptr) {
  1438. return std::string();
  1439. }
  1440. return GetNodeUniqueId(boneNode);
  1441. }
  1442. std::string ColladaExporter::GetObjectUniqueId(AiObjectType type, size_t pIndex) {
  1443. auto idIt = GetObjectIdMap(type).find(pIndex);
  1444. if (idIt != GetObjectIdMap(type).cend()) {
  1445. return idIt->second;
  1446. }
  1447. // Not seen this object before, create and add
  1448. NameIdPair result = AddObjectIndexToMaps(type, pIndex);
  1449. return result.second;
  1450. }
  1451. std::string ColladaExporter::GetObjectName(AiObjectType type, size_t pIndex) {
  1452. auto objectName = GetObjectNameMap(type).find(pIndex);
  1453. if (objectName != GetObjectNameMap(type).cend()) {
  1454. return objectName->second;
  1455. }
  1456. // Not seen this object before, create and add
  1457. NameIdPair result = AddObjectIndexToMaps(type, pIndex);
  1458. return result.first;
  1459. }
  1460. // Determine unique id and add the name and id to the maps
  1461. // @param type object type
  1462. // @param index object index
  1463. // @param name in/out. Caller to set the original name if known.
  1464. // @param idStr in/out. Caller to set the preferred id if known.
  1465. ColladaExporter::NameIdPair ColladaExporter::AddObjectIndexToMaps(AiObjectType type, size_t index) {
  1466. std::string name;
  1467. std::string idStr;
  1468. std::string idPostfix;
  1469. // Get the name and id postfix
  1470. switch (type) {
  1471. case AiObjectType::Mesh:
  1472. name = mScene->mMeshes[index]->mName.C_Str();
  1473. break;
  1474. case AiObjectType::Material:
  1475. name = mScene->mMaterials[index]->GetName().C_Str();
  1476. break;
  1477. case AiObjectType::Animation:
  1478. name = mScene->mAnimations[index]->mName.C_Str();
  1479. break;
  1480. case AiObjectType::Light:
  1481. name = mScene->mLights[index]->mName.C_Str();
  1482. idPostfix = "-light";
  1483. break;
  1484. case AiObjectType::Camera:
  1485. name = mScene->mCameras[index]->mName.C_Str();
  1486. idPostfix = "-camera";
  1487. break;
  1488. case AiObjectType::Count:
  1489. throw std::logic_error("ColladaExporter::AiObjectType::Count is not an object type");
  1490. }
  1491. if (name.empty()) {
  1492. // Default ids if empty name
  1493. switch (type) {
  1494. case AiObjectType::Mesh: idStr = std::string("mesh_"); break;
  1495. case AiObjectType::Material: idStr = std::string("material_"); break; // This one should never happen
  1496. case AiObjectType::Animation: idStr = std::string("animation_"); break;
  1497. case AiObjectType::Light: idStr = std::string("light_"); break;
  1498. case AiObjectType::Camera: idStr = std::string("camera_"); break;
  1499. case AiObjectType::Count: throw std::logic_error("ColladaExporter::AiObjectType::Count is not an object type");
  1500. }
  1501. idStr.append(ai_to_string(index));
  1502. } else {
  1503. idStr = XMLIDEncode(name);
  1504. }
  1505. if (!name.empty()) {
  1506. name = XMLEscape(name);
  1507. }
  1508. idStr = MakeUniqueId(mUniqueIds, idStr, idPostfix);
  1509. // Add to maps
  1510. mUniqueIds.insert(idStr);
  1511. GetObjectIdMap(type).insert(std::make_pair(index, idStr));
  1512. GetObjectNameMap(type).insert(std::make_pair(index, name));
  1513. return std::make_pair(name, idStr);
  1514. }
  1515. } // end of namespace Assimp
  1516. #endif // ASSIMP_BUILD_NO_COLLADA_EXPORTER
  1517. #endif // ASSIMP_BUILD_NO_EXPORT