ColladaExporter.cpp 61 KB

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