ColladaExporter.cpp 61 KB

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