ColladaExporter.cpp 64 KB

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