Exporter.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  1. // Copyright (C) 2009-2015, Panagiotis Christopoulos Charitos.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include "Exporter.h"
  6. #include <iostream>
  7. //==============================================================================
  8. // Statics =
  9. //==============================================================================
  10. static const char* XML_HEADER = R"(<?xml version="1.0" encoding="UTF-8" ?>)";
  11. //==============================================================================
  12. static aiColor3D srgbToLinear(aiColor3D in)
  13. {
  14. const float p = 1.0 / 2.4;
  15. aiColor3D out;
  16. out[0] = pow(in[0], p);
  17. out[1] = pow(in[1], p);
  18. out[2] = pow(in[2], p);
  19. out[3] = in[3];
  20. return out;
  21. }
  22. //==============================================================================
  23. /// Convert from sRGB to linear and preserve energy
  24. static aiColor3D computeLightColor(aiColor3D in)
  25. {
  26. float energy = std::max(std::max(in[0], in[1]), in[2]);
  27. if(energy > 1.0)
  28. {
  29. in[0] /= energy;
  30. in[1] /= energy;
  31. in[2] /= energy;
  32. }
  33. else
  34. {
  35. energy = 1.0;
  36. }
  37. in = srgbToLinear(in);
  38. in[0] *= energy;
  39. in[1] *= energy;
  40. in[2] *= energy;
  41. return in;
  42. }
  43. //==============================================================================
  44. /// Round up the instances count.
  45. static uint32_t roundUpInstancesCount(uint32_t instances)
  46. {
  47. if(instances == 1)
  48. {
  49. instances = 1;
  50. }
  51. else if(instances <= 4)
  52. {
  53. instances = 4;
  54. }
  55. else if(instances <= 8)
  56. {
  57. instances = 8;
  58. }
  59. else if(instances <= 16)
  60. {
  61. instances = 16;
  62. }
  63. else if(instances <= 32)
  64. {
  65. instances = 32;
  66. }
  67. else
  68. {
  69. ERROR("Too many instances %u", instances);
  70. }
  71. return instances;
  72. }
  73. //==============================================================================
  74. static std::string getMaterialName(const aiMaterial& mtl, uint32_t instances)
  75. {
  76. aiString ainame;
  77. std::string name;
  78. if(mtl.Get(AI_MATKEY_NAME, ainame) == AI_SUCCESS)
  79. {
  80. name = ainame.C_Str();
  81. if(instances > 1)
  82. {
  83. name += "_inst" + std::to_string(roundUpInstancesCount(instances));
  84. }
  85. }
  86. else
  87. {
  88. ERROR("Material's name is missing");
  89. }
  90. return name;
  91. }
  92. //==============================================================================
  93. static std::string getMeshName(const aiMesh& mesh)
  94. {
  95. return std::string(mesh.mName.C_Str());
  96. }
  97. //==============================================================================
  98. /// Walk the node hierarchy and find the node.
  99. static const aiNode* findNodeWithName(
  100. const std::string& name,
  101. const aiNode* node)
  102. {
  103. if(node == nullptr || node->mName.C_Str() == name)
  104. {
  105. return node;
  106. }
  107. const aiNode* out = nullptr;
  108. // Go to children
  109. for(uint32_t i = 0; i < node->mNumChildren; i++)
  110. {
  111. out = findNodeWithName(name, node->mChildren[i]);
  112. if(out)
  113. {
  114. break;
  115. }
  116. }
  117. return out;
  118. }
  119. //==============================================================================
  120. static std::vector<std::string> tokenize(const std::string &source)
  121. {
  122. const char *delimiter = " ";
  123. bool keepEmpty = false;
  124. std::vector<std::string> results;
  125. size_t prev = 0;
  126. size_t next = 0;
  127. while((next = source.find_first_of(delimiter, prev)) != std::string::npos)
  128. {
  129. if(keepEmpty || (next - prev != 0))
  130. {
  131. results.push_back(source.substr(prev, next - prev));
  132. }
  133. prev = next + 1;
  134. }
  135. if(prev < source.size())
  136. {
  137. results.push_back(source.substr(prev));
  138. }
  139. return results;
  140. }
  141. //==============================================================================
  142. template<int N, typename Arr>
  143. static void stringToFloatArray(const std::string& in, Arr& out)
  144. {
  145. std::vector<std::string> tokens = tokenize(in);
  146. if(tokens.size() != N)
  147. {
  148. ERROR("Failed to parse %s", in.c_str());
  149. }
  150. int count = 0;
  151. for(const std::string& s : tokens)
  152. {
  153. out[count] = std::stof(s);
  154. ++count;
  155. }
  156. }
  157. //==============================================================================
  158. // Exporter =
  159. //==============================================================================
  160. //==============================================================================
  161. aiMatrix4x4 Exporter::toAnkiMatrix(const aiMatrix4x4& in) const
  162. {
  163. static const aiMatrix4x4 toLeftHanded(
  164. 1, 0, 0, 0,
  165. 0, 0, 1, 0,
  166. 0, -1, 0, 0,
  167. 0, 0, 0, 1);
  168. static const aiMatrix4x4 toLeftHandedInv(
  169. 1, 0, 0, 0,
  170. 0, 0, -1, 0,
  171. 0, 1, 0, 0,
  172. 0, 0, 0, 1);
  173. if(m_flipyz)
  174. {
  175. return toLeftHanded * in * toLeftHandedInv;
  176. }
  177. else
  178. {
  179. return in;
  180. }
  181. }
  182. //==============================================================================
  183. aiMatrix3x3 Exporter::toAnkiMatrix(const aiMatrix3x3& in) const
  184. {
  185. static const aiMatrix3x3 toLeftHanded(
  186. 1, 0, 0,
  187. 0, 0, 1,
  188. 0, -1, 0);
  189. static const aiMatrix3x3 toLeftHandedInv(
  190. 1, 0, 0,
  191. 0, 0, -1,
  192. 0, 1, 0);
  193. if(m_flipyz)
  194. {
  195. return toLeftHanded * in;
  196. }
  197. else
  198. {
  199. return in;
  200. }
  201. }
  202. //==============================================================================
  203. void Exporter::writeTransform(const aiMatrix4x4& mat)
  204. {
  205. std::ofstream& file = m_sceneFile;
  206. aiMatrix4x4 m = toAnkiMatrix(mat);
  207. float pos[3];
  208. pos[0] = m[0][3];
  209. pos[1] = m[1][3];
  210. pos[2] = m[2][3];
  211. file << "trf = Transform.new()\n";
  212. file << "trf:setOrigin(Vec4.new("
  213. << pos[0] << ", " << pos[1] << ", " << pos[2] << ", 0))\n";
  214. file << "rot = Mat3x4.new()\n";
  215. file << "rot:setAll(";
  216. for(unsigned j = 0; j < 3; j++)
  217. {
  218. for(unsigned i = 0; i < 4; i++)
  219. {
  220. if(i == 3)
  221. {
  222. file << "0";
  223. }
  224. else
  225. {
  226. file << m[j][i];
  227. }
  228. if(!(i == 3 && j == 2))
  229. {
  230. file << ", ";
  231. }
  232. }
  233. }
  234. file << ")\n";
  235. file << "trf:setRotation(rot)\n";
  236. file << "trf:setScale(1.0)\n";
  237. }
  238. //==============================================================================
  239. void Exporter::writeNodeTransform(
  240. const std::string& node,
  241. const aiMatrix4x4& mat)
  242. {
  243. std::ofstream& file = m_sceneFile;
  244. writeTransform(mat);
  245. file << node
  246. << ":getSceneNodeBase():getMoveComponent():setLocalTransform(trf)\n";
  247. }
  248. //==============================================================================
  249. const aiMesh& Exporter::getMeshAt(unsigned index) const
  250. {
  251. assert(index < m_scene->mNumMeshes);
  252. return *m_scene->mMeshes[index];
  253. }
  254. //==============================================================================
  255. const aiMaterial& Exporter::getMaterialAt(unsigned index) const
  256. {
  257. assert(index < m_scene->mNumMaterials);
  258. return *m_scene->mMaterials[index];
  259. }
  260. //==============================================================================
  261. std::string Exporter::getModelName(const Model& model) const
  262. {
  263. std::string name = getMeshName(getMeshAt(model.m_meshIndex));
  264. name += getMaterialName(
  265. getMaterialAt(model.m_materialIndex), model.m_instancesCount);
  266. return name;
  267. }
  268. //==============================================================================
  269. void Exporter::exportSkeleton(const aiMesh& mesh) const
  270. {
  271. assert(mesh.HasBones());
  272. std::string name = mesh.mName.C_Str();
  273. std::fstream file;
  274. LOGI("Exporting skeleton %s", name.c_str());
  275. // Open file
  276. file.open(m_outputDirectory + name + ".skel", std::ios::out);
  277. file << XML_HEADER << "\n";
  278. file << "<skeleton>\n";
  279. file << "\t<bones>\n";
  280. bool rootBoneFound = false;
  281. for(uint32_t i = 0; i < mesh.mNumBones; i++)
  282. {
  283. const aiBone& bone = *mesh.mBones[i];
  284. file << "\t\t<bone>\n";
  285. // <name>
  286. file << "\t\t\t<name>" << bone.mName.C_Str() << "</name>\n";
  287. if(strcmp(bone.mName.C_Str(), "root") == 0)
  288. {
  289. rootBoneFound = true;
  290. }
  291. // <transform>
  292. file << "\t\t\t<transform>";
  293. for(uint32_t j = 0; j < 16; j++)
  294. {
  295. file << bone.mOffsetMatrix[j] << " ";
  296. }
  297. file << "</transform>\n";
  298. file << "\t\t</bone>\n";
  299. }
  300. if(!rootBoneFound)
  301. {
  302. ERROR("There should be one bone named \"root\"");
  303. }
  304. file << "\t</bones>\n";
  305. file << "</skeleton>\n";
  306. }
  307. //==============================================================================
  308. void Exporter::exportMaterial(
  309. const aiMaterial& mtl,
  310. uint32_t instances) const
  311. {
  312. std::string diffTex;
  313. std::string normTex;
  314. std::string specColTex;
  315. std::string shininessTex;
  316. std::string dispTex;
  317. aiString path;
  318. std::string name = getMaterialName(mtl, instances);
  319. LOGI("Exporting material %s", name.c_str());
  320. // Diffuse texture
  321. if(mtl.GetTextureCount(aiTextureType_DIFFUSE) > 0)
  322. {
  323. if(mtl.GetTexture(aiTextureType_DIFFUSE, 0, &path) == AI_SUCCESS)
  324. {
  325. diffTex = getFilename(path.C_Str());
  326. }
  327. else
  328. {
  329. ERROR("Failed to retrieve texture");
  330. }
  331. }
  332. // Normal texture
  333. if(mtl.GetTextureCount(aiTextureType_NORMALS) > 0)
  334. {
  335. if(mtl.GetTexture(aiTextureType_NORMALS, 0, &path) == AI_SUCCESS)
  336. {
  337. normTex = getFilename(path.C_Str());
  338. }
  339. else
  340. {
  341. ERROR("Failed to retrieve texture");
  342. }
  343. }
  344. // Specular color
  345. if(mtl.GetTextureCount(aiTextureType_SPECULAR) > 0)
  346. {
  347. if(mtl.GetTexture(aiTextureType_SPECULAR, 0, &path) == AI_SUCCESS)
  348. {
  349. specColTex = getFilename(path.C_Str());
  350. }
  351. else
  352. {
  353. ERROR("Failed to retrieve texture");
  354. }
  355. }
  356. // Shininess color
  357. if(mtl.GetTextureCount(aiTextureType_SHININESS) > 0)
  358. {
  359. if(mtl.GetTexture(aiTextureType_SHININESS, 0, &path) == AI_SUCCESS)
  360. {
  361. shininessTex = getFilename(path.C_Str());
  362. }
  363. else
  364. {
  365. ERROR("Failed to retrieve texture");
  366. }
  367. }
  368. // Height texture
  369. if(mtl.GetTextureCount(aiTextureType_DISPLACEMENT) > 0)
  370. {
  371. if(mtl.GetTexture(aiTextureType_DISPLACEMENT, 0, &path) == AI_SUCCESS)
  372. {
  373. dispTex = getFilename(path.C_Str());
  374. }
  375. else
  376. {
  377. ERROR("Failed to retrieve texture");
  378. }
  379. }
  380. // Write file
  381. static const char* diffNormSpecFragTemplate =
  382. #include "templates/diffNormSpecFrag.h"
  383. ;
  384. static const char* simpleVertTemplate =
  385. #include "templates/simpleVert.h"
  386. ;
  387. static const char* tessVertTemplate =
  388. #include "templates/tessVert.h"
  389. ;
  390. static const char* readRgbFromTextureTemplate = R"(
  391. <operation>
  392. <id>%id%</id>
  393. <returnType>vec3</returnType>
  394. <function>readRgbFromTexture</function>
  395. <arguments>
  396. <argument>%map%</argument>
  397. <argument>out2</argument>
  398. </arguments>
  399. </operation>)";
  400. static const char* readRFromTextureTemplate = R"(
  401. <operation>
  402. <id>%id%</id>
  403. <returnType>float</returnType>
  404. <function>readRFromTexture</function>
  405. <arguments>
  406. <argument>%map%</argument>
  407. <argument>out2</argument>
  408. </arguments>
  409. </operation>)";
  410. // Compose full template
  411. // First geometry part
  412. std::string materialStr;
  413. materialStr = R"(<?xml version="1.0" encoding="UTF-8" ?>)";
  414. materialStr += "\n<material>\n\t<programs>\n";
  415. if(dispTex.empty())
  416. {
  417. materialStr += simpleVertTemplate;
  418. }
  419. else
  420. {
  421. materialStr += tessVertTemplate;
  422. }
  423. materialStr += "\n";
  424. // Then fragment part
  425. materialStr += diffNormSpecFragTemplate;
  426. materialStr += "\n\t</programs>\t</material>";
  427. // Replace strings
  428. if(!dispTex.empty())
  429. {
  430. materialStr = replaceAllString(materialStr, "%dispMap%",
  431. m_texrpath + dispTex);
  432. }
  433. // Diffuse
  434. if(!diffTex.empty())
  435. {
  436. materialStr = replaceAllString(materialStr, "%diffuseColorInput%",
  437. R"(<input><type>sampler2D</type><name>uDiffuseColor</name><value>)"
  438. + m_texrpath + diffTex
  439. + R"(</value></input>)");
  440. materialStr = replaceAllString(materialStr, "%diffuseColorFunc%",
  441. readRgbFromTextureTemplate);
  442. materialStr = replaceAllString(materialStr, "%id%",
  443. "10");
  444. materialStr = replaceAllString(materialStr, "%map%",
  445. "uDiffuseColor");
  446. materialStr = replaceAllString(materialStr, "%diffuseColorArg%",
  447. "out10");
  448. }
  449. else
  450. {
  451. aiColor3D diffCol = {0.0, 0.0, 0.0};
  452. mtl.Get(AI_MATKEY_COLOR_DIFFUSE, diffCol);
  453. materialStr = replaceAllString(materialStr, "%diffuseColorInput%",
  454. R"(<input><type>vec3</type><name>uDiffuseColor</name><value>)"
  455. + std::to_string(diffCol[0]) + " "
  456. + std::to_string(diffCol[1]) + " "
  457. + std::to_string(diffCol[2])
  458. + R"(</value></input>)");
  459. materialStr = replaceAllString(materialStr, "%diffuseColorFunc%",
  460. "");
  461. materialStr = replaceAllString(materialStr, "%diffuseColorArg%",
  462. "uDiffuseColor");
  463. }
  464. // Normal
  465. if(!normTex.empty())
  466. {
  467. materialStr = replaceAllString(materialStr, "%normalInput%",
  468. R"(<input><type>sampler2D</type><name>uNormal</name><value>)"
  469. + m_texrpath + normTex
  470. + R"(</value></input>)");
  471. materialStr = replaceAllString(materialStr, "%normalFunc%",
  472. R"(
  473. <operation>
  474. <id>20</id>
  475. <returnType>vec3</returnType>
  476. <function>readNormalFromTexture</function>
  477. <arguments>
  478. <argument>out0</argument>
  479. <argument>out1</argument>
  480. <argument>uNormal</argument>
  481. <argument>out2</argument>
  482. </arguments>
  483. </operation>)");
  484. materialStr = replaceAllString(materialStr, "%normalArg%",
  485. "out20");
  486. }
  487. else
  488. {
  489. materialStr = replaceAllString(materialStr, "%normalInput%", " ");
  490. materialStr = replaceAllString(materialStr, "%normalFunc%", " ");
  491. materialStr = replaceAllString(materialStr, "%normalArg%", "out0");
  492. }
  493. // Specular
  494. if(!specColTex.empty())
  495. {
  496. materialStr = replaceAllString(materialStr, "%specularColorInput%",
  497. R"(<input><type>sampler2D</type><name>uSpecularColor</name><value>)"
  498. + m_texrpath + specColTex
  499. + R"(</value></input>)");
  500. materialStr = replaceAllString(materialStr, "%specularColorFunc%",
  501. readRgbFromTextureTemplate);
  502. materialStr = replaceAllString(materialStr, "%id%",
  503. "50");
  504. materialStr = replaceAllString(materialStr, "%map%",
  505. "uSpecularColor");
  506. materialStr = replaceAllString(materialStr, "%specularColorArg%",
  507. "out50");
  508. }
  509. else
  510. {
  511. aiColor3D specCol = {0.0, 0.0, 0.0};
  512. mtl.Get(AI_MATKEY_COLOR_SPECULAR, specCol);
  513. materialStr = replaceAllString(materialStr, "%specularColorInput%",
  514. R"(<input><type>vec3</type><name>uSpecularColor</name><value>)"
  515. + std::to_string(specCol[0]) + " "
  516. + std::to_string(specCol[1]) + " "
  517. + std::to_string(specCol[2])
  518. + R"(</value></input>)");
  519. materialStr = replaceAllString(materialStr, "%specularColorFunc%",
  520. "");
  521. materialStr = replaceAllString(materialStr, "%specularColorArg%",
  522. "uSpecularColor");
  523. }
  524. if(!shininessTex.empty())
  525. {
  526. materialStr = replaceAllString(materialStr, "%specularPowerInput%",
  527. R"(<input><type>sampler2D</type><name>uSpecularPower</name><value>)"
  528. + m_texrpath + shininessTex
  529. + R"(</value></input>)");
  530. materialStr = replaceAllString(materialStr, "%specularPowerValue%",
  531. m_texrpath + shininessTex);
  532. materialStr = replaceAllString(materialStr, "%specularPowerFunc%",
  533. readRFromTextureTemplate);
  534. materialStr = replaceAllString(materialStr, "%id%",
  535. "60");
  536. materialStr = replaceAllString(materialStr, "%map%",
  537. "uSpecularPower");
  538. materialStr = replaceAllString(materialStr, "%specularPowerArg%",
  539. "out60");
  540. }
  541. else
  542. {
  543. float shininess = 0.0;
  544. mtl.Get(AI_MATKEY_SHININESS, shininess);
  545. const float MAX_SHININESS = 511.0;
  546. shininess = std::min(MAX_SHININESS, shininess);
  547. if(shininess > MAX_SHININESS)
  548. {
  549. LOGW("Shininness exceeds %f", MAX_SHININESS);
  550. }
  551. shininess = shininess / MAX_SHININESS;
  552. materialStr = replaceAllString(materialStr, "%specularPowerInput%",
  553. R"(<input><type>float</type><name>uSpecularPower</name><value>)"
  554. + std::to_string(shininess)
  555. + R"(</value></input>)");
  556. materialStr = replaceAllString(materialStr, "%specularPowerFunc%",
  557. "");
  558. materialStr = replaceAllString(materialStr, "%specularPowerArg%",
  559. "uSpecularPower");
  560. }
  561. materialStr = replaceAllString(materialStr, "%maxSpecularPower%", " ");
  562. materialStr = replaceAllString(materialStr, "%instanced%",
  563. (instances > 1) ? "1" : "0");
  564. materialStr = replaceAllString(materialStr, "%arraySize%",
  565. std::to_string(roundUpInstancesCount(instances)));
  566. materialStr = replaceAllString(materialStr, "%diffuseMap%",
  567. m_texrpath + diffTex);
  568. // Replace texture extensions with .anki
  569. materialStr = replaceAllString(materialStr, ".tga", ".ankitex");
  570. materialStr = replaceAllString(materialStr, ".png", ".ankitex");
  571. materialStr = replaceAllString(materialStr, ".jpg", ".ankitex");
  572. materialStr = replaceAllString(materialStr, ".jpeg", ".ankitex");
  573. // Open and write file
  574. std::fstream file;
  575. file.open(m_outputDirectory + name + ".ankimtl", std::ios::out);
  576. file << materialStr;
  577. }
  578. //==============================================================================
  579. void Exporter::exportModel(const Model& model) const
  580. {
  581. std::string name = getModelName(model);
  582. LOGI("Exporting model %s", name.c_str());
  583. std::fstream file;
  584. file.open(m_outputDirectory + name + ".ankimdl", std::ios::out);
  585. file << XML_HEADER << '\n';
  586. file << "<model>\n";
  587. file << "\t<modelPatches>\n";
  588. // Start patches
  589. file << "\t\t<modelPatch>\n";
  590. // Write mesh
  591. file << "\t\t\t<mesh>" << m_rpath
  592. << getMeshName(getMeshAt(model.m_meshIndex))
  593. << ".ankimesh</mesh>\n";
  594. // Write mesh1
  595. if(!model.m_lod1MeshName.empty())
  596. {
  597. bool found = false;
  598. for(unsigned i = 0; i < m_scene->mNumMeshes; i++)
  599. {
  600. if(m_scene->mMeshes[i]->mName.C_Str() == model.m_lod1MeshName)
  601. {
  602. file << "\t\t\t<mesh1>" << m_rpath
  603. << getMeshName(getMeshAt(i))
  604. << ".ankimesh</mesh1>\n";
  605. found = true;
  606. break;
  607. }
  608. }
  609. if(!found)
  610. {
  611. ERROR("Couldn't find the LOD1 %s", model.m_lod1MeshName.c_str());
  612. }
  613. }
  614. // Write material
  615. file << "\t\t\t<material>" << m_rpath
  616. << getMaterialName(getMaterialAt(model.m_materialIndex),
  617. model.m_instancesCount)
  618. << ".ankimtl</material>\n";
  619. // End patches
  620. file << "\t\t</modelPatch>\n";
  621. file << "\t</modelPatches>\n";
  622. file << "</model>\n";
  623. }
  624. //==============================================================================
  625. void Exporter::exportLight(const aiLight& light)
  626. {
  627. std::ofstream& file = m_sceneFile;
  628. LOGI("Exporting light %s", light.mName.C_Str());
  629. if(light.mType != aiLightSource_POINT && light.mType != aiLightSource_SPOT)
  630. {
  631. LOGW("Skipping light %s. Unsupported type (0x%x)",
  632. light.mName.C_Str(), light.mType);
  633. return;
  634. }
  635. if(light.mAttenuationLinear != 0.0)
  636. {
  637. LOGW("Skipping light %s. Linear attenuation is not 0.0",
  638. light.mName.C_Str());
  639. return;
  640. }
  641. file << "\nnode = scene:new"
  642. << ((light.mType == aiLightSource_POINT) ? "Point" : "Spot")
  643. << "Light(\"" << light.mName.C_Str() << "\")\n";
  644. file << "lcomp = node:getSceneNodeBase():getLightComponent()\n";
  645. // Colors
  646. //aiColor3D linear = computeLightColor(light.mColorDiffuse);
  647. aiVector3D linear(light.mColorDiffuse[0], light.mColorDiffuse[1],
  648. light.mColorDiffuse[2]);
  649. file << "lcomp:setDiffuseColor(Vec4.new("
  650. << linear[0] << ", "
  651. << linear[1] << ", "
  652. << linear[2] << ", "
  653. << "1))\n";
  654. //linear = computeLightColor(light.mColorSpecular);
  655. if(light.mProperties.find("specular_color") != light.mProperties.end())
  656. {
  657. stringToFloatArray<3>(light.mProperties.at("specular_color"), linear);
  658. }
  659. file << "lcomp:setSpecularColor(Vec4.new("
  660. << linear[0] << ", "
  661. << linear[1] << ", "
  662. << linear[2] << ", "
  663. << "1))\n";
  664. // Geometry
  665. aiVector3D direction(0.0, 0.0, 1.0);
  666. switch(light.mType)
  667. {
  668. case aiLightSource_POINT:
  669. {
  670. // At this point I want the radius and have the attenuation factors
  671. // att = Ac + Al*d + Aq*d^2. When d = r then att = 0.0. Also if we
  672. // assume that Al is 0 then:
  673. // 0 = Ac + Aq*r^2. Solving by r is easy
  674. float r =
  675. sqrt(light.mAttenuationConstant / light.mAttenuationQuadratic);
  676. file << "lcomp:setRadius(" << r << ")\n";
  677. }
  678. break;
  679. case aiLightSource_SPOT:
  680. {
  681. float dist =
  682. sqrt(light.mAttenuationConstant / light.mAttenuationQuadratic);
  683. float outer = light.mAngleOuterCone;
  684. float inner = light.mAngleInnerCone;
  685. if(outer == inner)
  686. {
  687. inner = outer / 2.0;
  688. }
  689. file << "lcomp:setInnerAngle(" << inner << ")\n"
  690. << "lcomp:setOuterAngle(" << outer << ")\n"
  691. << "lcomp:setDistance(" << dist << ")\n";
  692. direction = light.mDirection;
  693. break;
  694. }
  695. default:
  696. assert(0);
  697. break;
  698. }
  699. // Transform
  700. const aiNode* node =
  701. findNodeWithName(light.mName.C_Str(), m_scene->mRootNode);
  702. if(node == nullptr)
  703. {
  704. ERROR("Couldn't find node for light %s", light.mName.C_Str());
  705. }
  706. aiMatrix4x4 rot;
  707. aiMatrix4x4::RotationX(-3.1415 / 2.0, rot);
  708. writeNodeTransform("node", node->mTransformation * rot);
  709. // Extra
  710. if(light.mProperties.find("shadow") != light.mProperties.end())
  711. {
  712. if(light.mProperties.at("shadow") == "true")
  713. {
  714. file << "lcomp:setShadowEnabled(1)\n";
  715. }
  716. else
  717. {
  718. file << "lcomp:setShadowEnabled(0)\n";
  719. }
  720. }
  721. if(light.mProperties.find("lens_flare") != light.mProperties.end())
  722. {
  723. file << "node:loadLensFlare(\"" << light.mProperties.at("lens_flare")
  724. << "\")\n";
  725. }
  726. bool lfCompRetrieved = false;
  727. if(light.mProperties.find("lens_flare_first_sprite_size")
  728. != light.mProperties.end())
  729. {
  730. if(!lfCompRetrieved)
  731. {
  732. file << "lfcomp = node:getSceneNodeBase():"
  733. << "getLensFlareComponent()\n";
  734. lfCompRetrieved = true;
  735. }
  736. aiVector3D vec;
  737. stringToFloatArray<2>(
  738. light.mProperties.at("lens_flare_first_sprite_size"), vec);
  739. file << "lfcomp:setFirstFlareSize(Vec2.new("
  740. << vec[0] << ", " << vec[1] << "))\n";
  741. }
  742. if(light.mProperties.find("lens_flare_color") != light.mProperties.end())
  743. {
  744. if(!lfCompRetrieved)
  745. {
  746. file << "lfcomp = node:getSceneNodeBase():"
  747. << "getLensFlareComponent()\n";
  748. lfCompRetrieved = true;
  749. }
  750. aiVector3D vec;
  751. stringToFloatArray<4>(light.mProperties.at("lens_flare_color"), vec);
  752. file << "lfcomp:setColorMultiplier(Vec4.new("
  753. << vec[0] << ", "
  754. << vec[1] << ", "
  755. << vec[2] << ", "
  756. << vec[3] << "))\n";
  757. }
  758. }
  759. //==============================================================================
  760. void Exporter::exportAnimation(
  761. const aiAnimation& anim,
  762. unsigned index)
  763. {
  764. // Get name
  765. std::string name = anim.mName.C_Str();
  766. if(name.size() == 0)
  767. {
  768. name = std::string("unnamed_") + std::to_string(index);
  769. }
  770. // Find if it's skeleton animation
  771. /*bool isSkeletalAnimation = false;
  772. for(uint32_t i = 0; i < scene.mNumMeshes; i++)
  773. {
  774. const aiMesh& mesh = *scene.mMeshes[i];
  775. if(mesh.HasBones())
  776. {
  777. }
  778. }*/
  779. std::fstream file;
  780. LOGI("Exporting animation %s", name.c_str());
  781. file.open(m_outputDirectory + name + ".ankianim", std::ios::out);
  782. file << XML_HEADER << "\n";
  783. file << "<animation>\n";
  784. file << "\t<channels>\n";
  785. for(uint32_t i = 0; i < anim.mNumChannels; i++)
  786. {
  787. const aiNodeAnim& nAnim = *anim.mChannels[i];
  788. file << "\t\t<channel>\n";
  789. // Name
  790. file << "\t\t\t<name>" << nAnim.mNodeName.C_Str() << "</name>\n";
  791. // Positions
  792. file << "\t\t\t<positionKeys>\n";
  793. for(uint32_t j = 0; j < nAnim.mNumPositionKeys; j++)
  794. {
  795. const aiVectorKey& key = nAnim.mPositionKeys[j];
  796. if(m_flipyz)
  797. {
  798. file << "\t\t\t\t<key><time>" << key.mTime << "</time>"
  799. << "<value>" << key.mValue[0] << " "
  800. << key.mValue[2] << " " << -key.mValue[1]
  801. << "</value></key>\n";
  802. }
  803. else
  804. {
  805. file << "\t\t\t\t<key><time>" << key.mTime << "</time>"
  806. << "<value>" << key.mValue[0] << " "
  807. << key.mValue[1] << " " << key.mValue[2]
  808. << "</value></key>\n";
  809. }
  810. }
  811. file << "\t\t\t</positionKeys>\n";
  812. // Rotations
  813. file << "\t\t\t<rotationKeys>\n";
  814. for(uint32_t j = 0; j < nAnim.mNumRotationKeys; j++)
  815. {
  816. const aiQuatKey& key = nAnim.mRotationKeys[j];
  817. aiMatrix3x3 mat = toAnkiMatrix(key.mValue.GetMatrix());
  818. aiQuaternion quat(mat);
  819. //aiQuaternion quat(key.mValue);
  820. file << "\t\t\t\t<key><time>" << key.mTime << "</time>"
  821. << "<value>" << quat.x << " " << quat.y
  822. << " " << quat.z << " "
  823. << quat.w << "</value></key>\n";
  824. }
  825. file << "\t\t\t</rotationKeys>\n";
  826. // Scale
  827. file << "\t\t\t<scalingKeys>\n";
  828. for(uint32_t j = 0; j < nAnim.mNumScalingKeys; j++)
  829. {
  830. const aiVectorKey& key = nAnim.mScalingKeys[j];
  831. // Note: only uniform scale
  832. file << "\t\t\t\t<key><time>" << key.mTime << "</time>"
  833. << "<value>"
  834. << ((key.mValue[0] + key.mValue[1] + key.mValue[2]) / 3.0)
  835. << "</value></key>\n";
  836. }
  837. file << "\t\t\t</scalingKeys>\n";
  838. file << "\t\t</channel>\n";
  839. }
  840. file << "\t</channels>\n";
  841. file << "</animation>\n";
  842. }
  843. //==============================================================================
  844. void Exporter::load()
  845. {
  846. LOGI("Loading file %s", &m_inputFilename[0]);
  847. //Assimp::DefaultLogger::create("", Logger::VERBOSE);
  848. m_importer.SetPropertyFloat(AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE, 170);
  849. const aiScene* scene = m_importer.ReadFile(m_inputFilename, 0
  850. //| aiProcess_FindInstances
  851. | aiProcess_Triangulate
  852. | aiProcess_JoinIdenticalVertices
  853. //| aiProcess_SortByPType
  854. | aiProcess_ImproveCacheLocality
  855. | aiProcess_OptimizeMeshes
  856. | aiProcess_RemoveRedundantMaterials
  857. | aiProcess_CalcTangentSpace
  858. | aiProcess_GenSmoothNormals
  859. );
  860. if(!scene)
  861. {
  862. ERROR("%s", m_importer.GetErrorString());
  863. }
  864. m_scene = scene;
  865. }
  866. //==============================================================================
  867. void Exporter::visitNode(const aiNode* ainode)
  868. {
  869. if(ainode == nullptr)
  870. {
  871. return;
  872. }
  873. // For every mesh of this node
  874. for(unsigned i = 0; i < ainode->mNumMeshes; i++)
  875. {
  876. unsigned meshIndex = ainode->mMeshes[i];
  877. unsigned mtlIndex = m_scene->mMeshes[meshIndex]->mMaterialIndex;
  878. // Check properties
  879. std::string lod1MeshName;
  880. bool special = false;
  881. for(const auto& prop : m_scene->mMeshes[meshIndex]->mProperties)
  882. {
  883. if(prop.first == "particles")
  884. {
  885. ParticleEmitter p;
  886. p.m_filename = prop.second;
  887. p.m_transform = ainode->mTransformation;
  888. m_particleEmitters.push_back(p);
  889. special = true;
  890. }
  891. else if(prop.first == "collision" && prop.second == "true")
  892. {
  893. StaticCollisionNode n;
  894. n.m_meshIndex = meshIndex;
  895. n.m_transform = ainode->mTransformation;
  896. m_staticCollisionNodes.push_back(n);
  897. special = true;
  898. }
  899. else if(prop.first == "portal" && prop.second == "true")
  900. {
  901. Portal portal;
  902. portal.m_meshIndex = meshIndex;
  903. portal.m_transform = ainode->mTransformation;
  904. m_portals.push_back(portal);
  905. special = true;
  906. }
  907. else if(prop.first == "sector" && prop.second == "true")
  908. {
  909. Sector sector;
  910. sector.m_meshIndex = meshIndex;
  911. sector.m_transform = ainode->mTransformation;
  912. m_sectors.push_back(sector);
  913. special = true;
  914. }
  915. else if(prop.first == "lod1")
  916. {
  917. lod1MeshName = prop.second;
  918. special = false;
  919. }
  920. }
  921. if(special)
  922. {
  923. continue;
  924. }
  925. // Find if there is another node with the same mesh-material-group pair
  926. std::vector<Node>::iterator it;
  927. for(it = m_nodes.begin(); it != m_nodes.end(); ++it)
  928. {
  929. const Node& node = *it;
  930. const Model& model = m_models[node.m_modelIndex];
  931. if(model.m_meshIndex == meshIndex
  932. && model.m_materialIndex == mtlIndex
  933. && node.m_group == ainode->mGroup.C_Str()
  934. && node.m_group != "none")
  935. {
  936. break;
  937. }
  938. }
  939. if(it != m_nodes.end())
  940. {
  941. // A node with the same model exists. It's instanced
  942. Node& node = *it;
  943. Model& model = m_models[node.m_modelIndex];
  944. assert(node.m_transforms.size() > 0);
  945. node.m_transforms.push_back(ainode->mTransformation);
  946. ++model.m_instancesCount;
  947. break;
  948. }
  949. // Create new model
  950. Model mdl;
  951. mdl.m_meshIndex = meshIndex;
  952. mdl.m_materialIndex = mtlIndex;
  953. mdl.m_lod1MeshName = lod1MeshName;
  954. m_models.push_back(mdl);
  955. // Create new node
  956. Node node;
  957. node.m_modelIndex = m_models.size() - 1;
  958. node.m_transforms.push_back(ainode->mTransformation);
  959. node.m_group = ainode->mGroup.C_Str();
  960. m_nodes.push_back(node);
  961. }
  962. // Go to children
  963. for(uint32_t i = 0; i < ainode->mNumChildren; i++)
  964. {
  965. visitNode(ainode->mChildren[i]);
  966. }
  967. }
  968. //==============================================================================
  969. void Exporter::exportCollisionMesh(uint32_t meshIdx)
  970. {
  971. std::string name = getMeshName(getMeshAt(meshIdx));
  972. std::fstream file;
  973. file.open(m_outputDirectory + name + ".ankicl", std::ios::out);
  974. file << XML_HEADER << '\n';
  975. // Write collision mesh
  976. file << "<collisionShape>\n\t<type>staticMesh</type>\n\t<value>"
  977. << m_rpath << name
  978. << ".ankimesh</value>\n</collisionShape>\n";
  979. }
  980. //==============================================================================
  981. void Exporter::exportAll()
  982. {
  983. LOGI("Exporting scene to %s", &m_outputDirectory[0]);
  984. //
  985. // Open scene file
  986. //
  987. m_sceneFile.open(m_outputDirectory + "scene.lua");
  988. std::ofstream& file = m_sceneFile;
  989. file << "local scene = getSceneGraph()\n"
  990. << "local rot\n"
  991. << "local node\n"
  992. << "local inst\n"
  993. << "local lcomp\n";
  994. //
  995. // Get all node/model data
  996. //
  997. visitNode(m_scene->mRootNode);
  998. //
  999. // Export collision meshes
  1000. //
  1001. for(auto n : m_staticCollisionNodes)
  1002. {
  1003. exportMesh(*m_scene->mMeshes[n.m_meshIndex], nullptr);
  1004. exportCollisionMesh(n.m_meshIndex);
  1005. file << "\n";
  1006. writeTransform(n.m_transform);
  1007. std::string name = getMeshName(getMeshAt(n.m_meshIndex));
  1008. std::string fname = m_rpath + name + ".ankicl";
  1009. file << "node = scene:newStaticCollisionNode(\""
  1010. << name << "\", \"" << fname << "\", trf)\n";
  1011. }
  1012. //
  1013. // Export portals
  1014. //
  1015. unsigned i = 0;
  1016. for(const Portal& portal : m_portals)
  1017. {
  1018. uint32_t meshIndex = portal.m_meshIndex;
  1019. exportMesh(*m_scene->mMeshes[meshIndex], nullptr);
  1020. std::string name = getMeshName(getMeshAt(meshIndex));
  1021. std::string fname = m_rpath + name + ".ankimesh";
  1022. file << "\nnode = scene:newPortal(\""
  1023. << name << i << "\", \"" << fname << "\")\n";
  1024. writeNodeTransform("node", portal.m_transform);
  1025. ++i;
  1026. }
  1027. //
  1028. // Export sectors
  1029. //
  1030. i = 0;
  1031. for(const Sector& sector : m_sectors)
  1032. {
  1033. uint32_t meshIndex = sector.m_meshIndex;
  1034. exportMesh(*m_scene->mMeshes[meshIndex], nullptr);
  1035. std::string name = getMeshName(getMeshAt(meshIndex));
  1036. std::string fname = m_rpath + name + ".ankimesh";
  1037. file << "\nnode = scene:newSector(\""
  1038. << name << i << "\", \"" << fname << "\")\n";
  1039. writeNodeTransform("node", sector.m_transform);
  1040. ++i;
  1041. }
  1042. //
  1043. // Export particle emitters
  1044. //
  1045. i = 0;
  1046. for(const ParticleEmitter& p : m_particleEmitters)
  1047. {
  1048. std::string name = "particles" + std::to_string(i);
  1049. file << "\nnode = scene:newParticleEmitter(\"" << name << "\", \""
  1050. << p.m_filename << "\")\n";
  1051. writeNodeTransform("node", p.m_transform);
  1052. ++i;
  1053. }
  1054. //
  1055. // Export nodes and models.
  1056. //
  1057. for(uint32_t i = 0; i < m_nodes.size(); i++)
  1058. {
  1059. Node& node = m_nodes[i];
  1060. Model& model = m_models[node.m_modelIndex];
  1061. // TODO If not instanced bake transform
  1062. exportMesh(*m_scene->mMeshes[model.m_meshIndex], nullptr);
  1063. exportMaterial(*m_scene->mMaterials[model.m_materialIndex],
  1064. model.m_instancesCount);
  1065. exportModel(model);
  1066. std::string modelName = getModelName(model);
  1067. std::string nodeName = modelName + node.m_group + std::to_string(i);
  1068. // Write the main node
  1069. file << "\nnode = scene:newModelNode(\""
  1070. << nodeName << "\", \""
  1071. << m_rpath << modelName << ".ankimdl" << "\")\n";
  1072. writeNodeTransform("node", node.m_transforms[0]);
  1073. // Write instance nodes
  1074. for(unsigned j = 1; j < node.m_transforms.size(); j++)
  1075. {
  1076. file << "\ninst = scene:newInstanceNode(\""
  1077. << nodeName << "_inst" << (j - 1) << "\")\n"
  1078. << "node:getSceneNodeBase():addChild("
  1079. << "inst:getSceneNodeBase())\n";
  1080. writeNodeTransform("inst", node.m_transforms[j]);
  1081. }
  1082. }
  1083. //
  1084. // Lights
  1085. //
  1086. for(unsigned i = 0; i < m_scene->mNumLights; i++)
  1087. {
  1088. exportLight(*m_scene->mLights[i]);
  1089. }
  1090. //
  1091. // Animations
  1092. //
  1093. for(unsigned i = 0; i < m_scene->mNumAnimations; i++)
  1094. {
  1095. exportAnimation(*m_scene->mAnimations[i], i);
  1096. }
  1097. LOGI("Done exporting scene!");
  1098. }