ColladaExporter.cpp 69 KB

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