2
0

ColladaExporter.cpp 69 KB

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