ColladaExporter.cpp 69 KB

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