GPBFile.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. #include "Base.h"
  2. #include "GPBFile.h"
  3. #include "Transform.h"
  4. #include "StringUtil.h"
  5. #include "EncoderArguments.h"
  6. #include "Heightmap.h"
  7. #define EPSILON 1.2e-7f;
  8. namespace gameplay
  9. {
  10. static GPBFile* __instance = NULL;
  11. /**
  12. * Returns true if the given value is close to one.
  13. */
  14. static bool isAlmostOne(float value);
  15. /**
  16. * Returns true if the given value is close to zero.
  17. */
  18. static bool isAlmostZero(float value);
  19. /**
  20. * Gets the common node ancestor for the given list of nodes.
  21. * This function assumes that the nodes share a common ancestor.
  22. *
  23. * @param nodes The list of nodes.
  24. *
  25. * @return The common node ancestor or NULL if the list of was empty.
  26. */
  27. static Node* getCommonNodeAncestor(const std::vector<Node*>& nodes);
  28. /**
  29. * Gets the list of node ancestors for the given node.
  30. *
  31. * @param node The node to get the ancestors for.
  32. * @param ancestors The output list of ancestors.
  33. * The first element is the root node and the last element is the direct parent of the node.
  34. */
  35. static void getNodeAncestors(Node* node, std::list<Node*>& ancestors);
  36. GPBFile::GPBFile(void)
  37. : _file(NULL), _animationsAdded(false)
  38. {
  39. __instance = this;
  40. }
  41. GPBFile::~GPBFile(void)
  42. {
  43. }
  44. GPBFile* GPBFile::getInstance()
  45. {
  46. return __instance;
  47. }
  48. bool GPBFile::saveBinary(const std::string& filepath)
  49. {
  50. _file = fopen(filepath.c_str(), "w+b");
  51. if (!_file)
  52. {
  53. return false;
  54. }
  55. size_t n = 0;
  56. // identifier
  57. char identifier[] = { '\xAB', 'G', 'P', 'B', '\xBB', '\r', '\n', '\x1A', '\n' };
  58. n = fwrite(identifier, 1, sizeof(identifier), _file);
  59. if (n != sizeof(identifier))
  60. {
  61. fclose(_file);
  62. return false;
  63. }
  64. // version
  65. n = fwrite(GPB_VERSION, 1, sizeof(GPB_VERSION), _file);
  66. if (n != sizeof(GPB_VERSION))
  67. {
  68. fclose(_file);
  69. return false;
  70. }
  71. // TODO: Check for errors on all file writing.
  72. // write refs
  73. _refTable.writeBinary(_file);
  74. // meshes
  75. write((unsigned int)_geometry.size(), _file);
  76. for (std::list<Mesh*>::const_iterator i = _geometry.begin(); i != _geometry.end(); ++i)
  77. {
  78. (*i)->writeBinary(_file);
  79. }
  80. // Objects
  81. write((unsigned int)_objects.size(), _file);
  82. for (std::list<Object*>::const_iterator i = _objects.begin(); i != _objects.end(); ++i)
  83. {
  84. (*i)->writeBinary(_file);
  85. }
  86. _refTable.updateOffsets(_file);
  87. fclose(_file);
  88. return true;
  89. }
  90. bool GPBFile::saveText(const std::string& filepath)
  91. {
  92. _file = fopen(filepath.c_str(), "w");
  93. if (!_file)
  94. {
  95. return false;
  96. }
  97. if (fprintf(_file, "<root>\n") <= 0)
  98. {
  99. fclose(_file);
  100. return false;
  101. }
  102. // TODO: Check for errors on all file writing.
  103. // write refs
  104. _refTable.writeText(_file);
  105. // meshes
  106. for (std::list<Mesh*>::const_iterator i = _geometry.begin(); i != _geometry.end(); ++i)
  107. {
  108. (*i)->writeText(_file);
  109. }
  110. // Objects
  111. for (std::list<Object*>::const_iterator i = _objects.begin(); i != _objects.end(); ++i)
  112. {
  113. (*i)->writeText(_file);
  114. }
  115. fprintf(_file, "</root>");
  116. fclose(_file);
  117. return true;
  118. }
  119. void GPBFile::add(Object* obj)
  120. {
  121. _objects.push_back(obj);
  122. }
  123. void GPBFile::addScene(Scene* scene)
  124. {
  125. addToRefTable(scene);
  126. _objects.push_back(scene);
  127. }
  128. void GPBFile::addCamera(Camera* camera)
  129. {
  130. addToRefTable(camera);
  131. _cameras.push_back(camera);
  132. }
  133. void GPBFile::addLight(Light* light)
  134. {
  135. addToRefTable(light);
  136. _lights.push_back(light);
  137. }
  138. void GPBFile::addMesh(Mesh* mesh)
  139. {
  140. addToRefTable(mesh);
  141. _geometry.push_back(mesh);
  142. }
  143. void GPBFile::addNode(Node* node)
  144. {
  145. addToRefTable(node);
  146. _nodes.push_back(node);
  147. }
  148. void GPBFile::addScenelessNode(Node* node)
  149. {
  150. addToRefTable(node);
  151. _nodes.push_back(node);
  152. // Nodes are normally written to file as part of a scene.
  153. // Nodes that don't belong to a scene need to be written on their own (outside a scene).
  154. // That is why node is added to the list of objects here.
  155. _objects.push_back(node);
  156. }
  157. void GPBFile::addAnimation(Animation* animation)
  158. {
  159. _animations.add(animation);
  160. if (!_animationsAdded)
  161. {
  162. // The animations container should only be added once and only if the file has at least one animation.
  163. _animationsAdded = true;
  164. addToRefTable(&_animations);
  165. add(&_animations);
  166. }
  167. }
  168. void GPBFile::addToRefTable(Object* obj)
  169. {
  170. if (obj)
  171. {
  172. const std::string& id = obj->getId();
  173. if (id.length() > 0)
  174. {
  175. if (_refTable.get(id) == NULL)
  176. {
  177. _refTable.add(id, obj);
  178. }
  179. }
  180. }
  181. }
  182. Object* GPBFile::getFromRefTable(const std::string& id)
  183. {
  184. return _refTable.get(id);
  185. }
  186. bool GPBFile::idExists(const std::string& id)
  187. {
  188. return _refTable.get(id) != NULL;
  189. }
  190. Camera* GPBFile::getCamera(const char* id)
  191. {
  192. if (!id)
  193. return NULL;
  194. // TODO: O(n) search is not ideal
  195. for (std::list<Camera*>::const_iterator i = _cameras.begin(); i != _cameras.end(); ++i)
  196. {
  197. const std::string& _id = (*i)->getId();
  198. if (_id.length() > 0 && strncmp(id, _id.c_str(), 255) == 0)
  199. {
  200. return *i;
  201. }
  202. }
  203. return NULL;
  204. }
  205. Light* GPBFile::getLight(const char* id)
  206. {
  207. if (!id)
  208. return NULL;
  209. // TODO: O(n) search is not ideal
  210. for (std::list<Light*>::const_iterator i = _lights.begin(); i != _lights.end(); ++i)
  211. {
  212. const std::string& _id = (*i)->getId();
  213. if (_id.length() > 0 && strncmp(id, _id.c_str(), 255) == 0)
  214. {
  215. return *i;
  216. }
  217. }
  218. return NULL;
  219. }
  220. Mesh* GPBFile::getMesh(const char* id)
  221. {
  222. if (!id)
  223. return NULL;
  224. // TODO: O(n) search is not ideal
  225. for (std::list<Mesh*>::const_iterator i = _geometry.begin(); i != _geometry.end(); ++i)
  226. {
  227. const std::string& _id = (*i)->getId();
  228. if (_id.length() > 0 && strncmp(id, _id.c_str(), 255) == 0)
  229. {
  230. return *i;
  231. }
  232. }
  233. return NULL;
  234. }
  235. Node* GPBFile::getNode(const char* id)
  236. {
  237. if (!id)
  238. return NULL;
  239. // TODO: O(n) search is not ideal
  240. for (std::list<Node*>::const_iterator i = _nodes.begin(); i != _nodes.end(); ++i)
  241. {
  242. const std::string& _id = (*i)->getId();
  243. if (_id.length() > 0 && strncmp(id, _id.c_str(), 255) == 0)
  244. {
  245. return *i;
  246. }
  247. }
  248. return NULL;
  249. }
  250. Animations* GPBFile::getAnimations()
  251. {
  252. return &_animations;
  253. }
  254. void GPBFile::adjust()
  255. {
  256. // calculate the ambient color for each scene
  257. for (std::list<Object*>::iterator i = _objects.begin(); i != _objects.end(); ++i)
  258. {
  259. Object* obj = *i;
  260. if (obj->getTypeId() == Object::SCENE_ID)
  261. {
  262. Scene* scene = dynamic_cast<Scene*>(obj);
  263. scene->calcAmbientColor();
  264. }
  265. }
  266. for (std::list<Node*>::const_iterator i = _nodes.begin(); i != _nodes.end(); ++i)
  267. {
  268. computeBounds(*i);
  269. }
  270. if (EncoderArguments::getInstance()->optimizeAnimationsEnabled())
  271. {
  272. LOG(1, "Optimizing animations.\n");
  273. optimizeAnimations();
  274. }
  275. // TODO:
  276. // remove ambient _lights
  277. // for each node
  278. // if node has ambient light
  279. // if node has no camera, mesh or children but 1 ambient light
  280. // delete node and remove from ref table
  281. // delete light and remove from ref table
  282. //
  283. // merge animations if possible
  284. // Search for animations that have the same target and key times and see if they can be merged.
  285. // Blender will output a simple translation animation to 3 separate animations with the same key times but targeting X, Y and Z.
  286. // This can be merged into one animation. Same for scale animations.
  287. // Generate heightmaps
  288. const std::vector<EncoderArguments::HeightmapOption>& heightmaps = EncoderArguments::getInstance()->getHeightmapOptions();
  289. for (unsigned int i = 0, count = heightmaps.size(); i < count; ++i)
  290. {
  291. Heightmap::generate(heightmaps[i].nodeIds, heightmaps[i].width, heightmaps[i].height, heightmaps[i].filename.c_str(), heightmaps[i].isHighPrecision);
  292. }
  293. }
  294. void GPBFile::groupMeshSkinAnimations()
  295. {
  296. for (std::list<Node*>::iterator it = _nodes.begin(); it != _nodes.end(); ++it)
  297. {
  298. if (Model* model = (*it)->getModel())
  299. {
  300. if (MeshSkin* skin = model->getSkin())
  301. {
  302. const std::vector<Node*>& joints = skin->getJoints();
  303. Node* commonAncestor = getCommonNodeAncestor(joints);
  304. if (commonAncestor)
  305. {
  306. // group the animation channels that target this common ancestor and its child nodes
  307. Animation* animation = new Animation();
  308. animation->setId("animations");
  309. moveAnimationChannels(commonAncestor, animation);
  310. _animations.add(animation);
  311. }
  312. }
  313. }
  314. }
  315. }
  316. void GPBFile::renameAnimations(std::vector<std::string>& animationIds, const char* newId)
  317. {
  318. const unsigned int animationCount = _animations.getAnimationCount();
  319. for (unsigned int animationIndex = 0; animationIndex < animationCount; ++animationIndex)
  320. {
  321. Animation* animation = _animations.getAnimation(animationIndex);
  322. assert(animation);
  323. std::vector<std::string>::const_iterator it = find(animationIds.begin(), animationIds.end(), animation->getId());
  324. if (it != animationIds.end())
  325. {
  326. animation->setId(newId);
  327. }
  328. }
  329. }
  330. void GPBFile::computeBounds(Node* node)
  331. {
  332. assert(node);
  333. if (Model* model = node->getModel())
  334. {
  335. if (Mesh* mesh = model->getMesh())
  336. {
  337. mesh->computeBounds();
  338. }
  339. }
  340. }
  341. void GPBFile::optimizeAnimations()
  342. {
  343. const unsigned int animationCount = _animations.getAnimationCount();
  344. for (unsigned int animationIndex = 0; animationIndex < animationCount; ++animationIndex)
  345. {
  346. Animation* animation = _animations.getAnimation(animationIndex);
  347. assert(animation);
  348. const int channelCount = animation->getAnimationChannelCount();
  349. LOG(2, "Optimizing %d channel(s) in animation '%s'.\n", channelCount, animation->getId().c_str());
  350. // loop backwards because we will be adding and removing channels
  351. for (int channelIndex = channelCount -1; channelIndex >= 0 ; --channelIndex)
  352. {
  353. AnimationChannel* channel = animation->getAnimationChannel(channelIndex);
  354. assert(channel);
  355. // Optimize node animation channels
  356. const Object* obj = _refTable.get(channel->getTargetId());
  357. if (obj && obj->getTypeId() == Object::NODE_ID)
  358. {
  359. if (channel->getTargetAttribute() == Transform::ANIMATE_SCALE_ROTATE_TRANSLATE)
  360. {
  361. decomposeTransformAnimationChannel(animation, channel, channelIndex);
  362. animation->remove(channel);
  363. SAFE_DELETE(channel);
  364. }
  365. }
  366. }
  367. }
  368. }
  369. void GPBFile::decomposeTransformAnimationChannel(Animation* animation, AnimationChannel* channel, int channelIndex)
  370. {
  371. LOG(2, " Optimizing animaton channel %s:%d.\n", animation->getId().c_str(), channelIndex+1);
  372. const std::vector<float>& keyTimes = channel->getKeyTimes();
  373. const std::vector<float>& keyValues = channel->getKeyValues();
  374. const size_t keyTimesSize = keyTimes.size();
  375. const size_t keyValuesSize = keyValues.size();
  376. std::vector<float> scaleKeyValues;
  377. std::vector<float> rotateKeyValues;
  378. std::vector<float> translateKeyValues;
  379. scaleKeyValues.reserve(keyTimesSize * 3);
  380. rotateKeyValues.reserve(keyTimesSize * 4);
  381. translateKeyValues.reserve(keyTimesSize * 3);
  382. for (size_t kv = 0; kv < keyValuesSize; kv += 10)
  383. {
  384. scaleKeyValues.push_back(keyValues[kv]);
  385. scaleKeyValues.push_back(keyValues[kv+1]);
  386. scaleKeyValues.push_back(keyValues[kv+2]);
  387. rotateKeyValues.push_back(keyValues[kv+3]);
  388. rotateKeyValues.push_back(keyValues[kv+4]);
  389. rotateKeyValues.push_back(keyValues[kv+5]);
  390. rotateKeyValues.push_back(keyValues[kv+6]);
  391. translateKeyValues.push_back(keyValues[kv+7]);
  392. translateKeyValues.push_back(keyValues[kv+8]);
  393. translateKeyValues.push_back(keyValues[kv+9]);
  394. }
  395. // replace transform animation channel with translate, rotate and scale animation channels
  396. // Don't add the scale channel if all the key values are close to 1.0
  397. size_t oneCount = (size_t)std::count_if(scaleKeyValues.begin(), scaleKeyValues.end(), isAlmostOne);
  398. if (scaleKeyValues.size() == oneCount)
  399. {
  400. LOG(2, " Discarding scale channel.\n");
  401. }
  402. else
  403. {
  404. LOG(3, " Keeping scale channel.\n");
  405. AnimationChannel* scaleChannel = new AnimationChannel();
  406. scaleChannel->setTargetId(channel->getTargetId());
  407. scaleChannel->setKeyTimes(channel->getKeyTimes());
  408. scaleChannel->setTangentsIn(channel->getTangentsIn());
  409. scaleChannel->setTangentsOut(channel->getTangentsOut());
  410. scaleChannel->setInterpolations(channel->getInterpolationTypes());
  411. scaleChannel->setTargetAttribute(Transform::ANIMATE_SCALE);
  412. scaleChannel->setKeyValues(scaleKeyValues);
  413. scaleChannel->removeDuplicates();
  414. animation->add(scaleChannel);
  415. }
  416. // Don't add the rotation channel if all quaternions are close to identity
  417. oneCount = 0;
  418. for (unsigned int i = 0, count = rotateKeyValues.size(); i < count; i += 4)
  419. {
  420. float x = rotateKeyValues[i];
  421. float y = rotateKeyValues[i+1];
  422. float z = rotateKeyValues[i+2];
  423. float w = rotateKeyValues[i+3];
  424. if (ISZERO(x) && ISZERO(y) && ISZERO(z) && ISONE(w))
  425. ++oneCount;
  426. else
  427. {
  428. LOG(4, "Rotation not identity: %u\n", i);
  429. Quaternion q(x, y, z, w);
  430. Vector3 axis;
  431. float angle = q.toAxisAngle(&axis);
  432. angle = 0;
  433. }
  434. }
  435. if ((rotateKeyValues.size()>>2) == oneCount)
  436. {
  437. LOG(2, " Discarding rotation channel.\n");
  438. }
  439. else
  440. {
  441. LOG(3, " Keeping rotation channel.\n");
  442. AnimationChannel* rotateChannel = new AnimationChannel();
  443. rotateChannel->setTargetId(channel->getTargetId());
  444. rotateChannel->setKeyTimes(channel->getKeyTimes());
  445. rotateChannel->setTangentsIn(channel->getTangentsIn());
  446. rotateChannel->setTangentsOut(channel->getTangentsOut());
  447. rotateChannel->setInterpolations(channel->getInterpolationTypes());
  448. rotateChannel->setTargetAttribute(Transform::ANIMATE_ROTATE);
  449. rotateChannel->setKeyValues(rotateKeyValues);
  450. rotateChannel->removeDuplicates();
  451. animation->add(rotateChannel);
  452. }
  453. // Don't add the translation channel if all values are close to zero
  454. oneCount = (size_t)std::count_if(translateKeyValues.begin(), translateKeyValues.end(), isAlmostZero);
  455. if (translateKeyValues.size() == oneCount)
  456. {
  457. LOG(2, " Discarding translation channel.\n");
  458. }
  459. else
  460. {
  461. LOG(3, " Keeping translation channel.\n");
  462. AnimationChannel* translateChannel = new AnimationChannel();
  463. translateChannel->setTargetId(channel->getTargetId());
  464. translateChannel->setKeyTimes(channel->getKeyTimes());
  465. translateChannel->setTangentsIn(channel->getTangentsIn());
  466. translateChannel->setTangentsOut(channel->getTangentsOut());
  467. translateChannel->setInterpolations(channel->getInterpolationTypes());
  468. translateChannel->setTargetAttribute(Transform::ANIMATE_TRANSLATE);
  469. translateChannel->setKeyValues(translateKeyValues);
  470. translateChannel->removeDuplicates();
  471. animation->add(translateChannel);
  472. }
  473. }
  474. void GPBFile::moveAnimationChannels(Node* node, Animation* dstAnimation)
  475. {
  476. // Loop through the animations and channels backwards because they will be removed when found.
  477. int animationCount = _animations.getAnimationCount();
  478. for (int i = animationCount - 1; i >= 0; --i)
  479. {
  480. Animation* animation = _animations.getAnimation(i);
  481. int channelCount = animation->getAnimationChannelCount();
  482. for (int j = channelCount - 1; j >= 0; --j)
  483. {
  484. AnimationChannel* channel = animation->getAnimationChannel(j);
  485. if (equals(channel->getTargetId(), node->getId()))
  486. {
  487. animation->remove(channel);
  488. dstAnimation->add(channel);
  489. }
  490. }
  491. if (animation->getAnimationChannelCount() == 0)
  492. {
  493. _animations.removeAnimation(i);
  494. }
  495. }
  496. for (Node* child = node->getFirstChild(); child != NULL; child = child->getNextSibling())
  497. {
  498. moveAnimationChannels(child, dstAnimation);
  499. }
  500. }
  501. bool isAlmostOne(float value)
  502. {
  503. return (value - 1.0f) < EPSILON;
  504. }
  505. bool isAlmostZero(float value)
  506. {
  507. return std::fabs(value) < EPSILON;
  508. }
  509. Node* getCommonNodeAncestor(const std::vector<Node*>& nodes)
  510. {
  511. if (nodes.empty())
  512. return NULL;
  513. if (nodes.size() == 1)
  514. return nodes.front();
  515. std::list<Node*> ancestors;
  516. size_t minAncestorCount = INT_MAX;
  517. for (std::vector<Node*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it)
  518. {
  519. Node* node = *it;
  520. getNodeAncestors(node, ancestors);
  521. ancestors.push_back(node);
  522. minAncestorCount = std::min(minAncestorCount, ancestors.size());
  523. }
  524. ancestors.resize(minAncestorCount);
  525. return ancestors.back();
  526. }
  527. void getNodeAncestors(Node* node, std::list<Node*>& ancestors)
  528. {
  529. ancestors.clear();
  530. Node* parent = node->getParent();
  531. while (parent != NULL)
  532. {
  533. ancestors.push_front(parent);
  534. parent = parent->getParent();
  535. }
  536. }
  537. }