GPBFile.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. unsigned int GPBFile::getLightCount() const
  255. {
  256. return (unsigned int)_lights.size();
  257. }
  258. void GPBFile::adjust()
  259. {
  260. // calculate the ambient color for each scene
  261. for (std::list<Object*>::iterator i = _objects.begin(); i != _objects.end(); ++i)
  262. {
  263. Object* obj = *i;
  264. if (obj->getTypeId() == Object::SCENE_ID)
  265. {
  266. Scene* scene = dynamic_cast<Scene*>(obj);
  267. scene->calcAmbientColor();
  268. }
  269. }
  270. for (std::list<Node*>::const_iterator i = _nodes.begin(); i != _nodes.end(); ++i)
  271. {
  272. computeBounds(*i);
  273. }
  274. if (EncoderArguments::getInstance()->optimizeAnimationsEnabled())
  275. {
  276. LOG(1, "Optimizing animations.\n");
  277. optimizeAnimations();
  278. }
  279. // TODO:
  280. // remove ambient _lights
  281. // for each node
  282. // if node has ambient light
  283. // if node has no camera, mesh or children but 1 ambient light
  284. // delete node and remove from ref table
  285. // delete light and remove from ref table
  286. //
  287. // merge animations if possible
  288. // Search for animations that have the same target and key times and see if they can be merged.
  289. // Blender will output a simple translation animation to 3 separate animations with the same key times but targeting X, Y and Z.
  290. // This can be merged into one animation. Same for scale animations.
  291. // Generate heightmaps
  292. const std::vector<EncoderArguments::HeightmapOption>& heightmaps = EncoderArguments::getInstance()->getHeightmapOptions();
  293. for (unsigned int i = 0, count = heightmaps.size(); i < count; ++i)
  294. {
  295. Heightmap::generate(heightmaps[i].nodeIds, heightmaps[i].width, heightmaps[i].height, heightmaps[i].filename.c_str(), heightmaps[i].isHighPrecision);
  296. }
  297. }
  298. void GPBFile::groupMeshSkinAnimations()
  299. {
  300. for (std::list<Node*>::iterator it = _nodes.begin(); it != _nodes.end(); ++it)
  301. {
  302. if (Model* model = (*it)->getModel())
  303. {
  304. if (MeshSkin* skin = model->getSkin())
  305. {
  306. const std::vector<Node*>& joints = skin->getJoints();
  307. Node* commonAncestor = getCommonNodeAncestor(joints);
  308. if (commonAncestor)
  309. {
  310. // group the animation channels that target this common ancestor and its child nodes
  311. Animation* animation = new Animation();
  312. animation->setId("animations");
  313. moveAnimationChannels(commonAncestor, animation);
  314. _animations.add(animation);
  315. }
  316. }
  317. }
  318. }
  319. }
  320. void GPBFile::renameAnimations(std::vector<std::string>& animationIds, const char* newId)
  321. {
  322. const unsigned int animationCount = _animations.getAnimationCount();
  323. for (unsigned int animationIndex = 0; animationIndex < animationCount; ++animationIndex)
  324. {
  325. Animation* animation = _animations.getAnimation(animationIndex);
  326. assert(animation);
  327. std::vector<std::string>::const_iterator it = find(animationIds.begin(), animationIds.end(), animation->getId());
  328. if (it != animationIds.end())
  329. {
  330. animation->setId(newId);
  331. }
  332. }
  333. }
  334. void GPBFile::computeBounds(Node* node)
  335. {
  336. assert(node);
  337. if (Model* model = node->getModel())
  338. {
  339. if (Mesh* mesh = model->getMesh())
  340. {
  341. mesh->computeBounds();
  342. }
  343. }
  344. }
  345. void GPBFile::optimizeAnimations()
  346. {
  347. const unsigned int animationCount = _animations.getAnimationCount();
  348. for (unsigned int animationIndex = 0; animationIndex < animationCount; ++animationIndex)
  349. {
  350. Animation* animation = _animations.getAnimation(animationIndex);
  351. assert(animation);
  352. const int channelCount = animation->getAnimationChannelCount();
  353. LOG(2, "Optimizing %d channel(s) in animation '%s'.\n", channelCount, animation->getId().c_str());
  354. // loop backwards because we will be adding and removing channels
  355. for (int channelIndex = channelCount -1; channelIndex >= 0 ; --channelIndex)
  356. {
  357. AnimationChannel* channel = animation->getAnimationChannel(channelIndex);
  358. assert(channel);
  359. // Optimize node animation channels
  360. const Object* obj = _refTable.get(channel->getTargetId());
  361. if (obj && obj->getTypeId() == Object::NODE_ID)
  362. {
  363. if (channel->getTargetAttribute() == Transform::ANIMATE_SCALE_ROTATE_TRANSLATE)
  364. {
  365. decomposeTransformAnimationChannel(animation, channel, channelIndex);
  366. animation->remove(channel);
  367. SAFE_DELETE(channel);
  368. }
  369. }
  370. }
  371. }
  372. }
  373. void GPBFile::decomposeTransformAnimationChannel(Animation* animation, AnimationChannel* channel, int channelIndex)
  374. {
  375. LOG(2, " Optimizing animaton channel %s:%d.\n", animation->getId().c_str(), channelIndex+1);
  376. const std::vector<float>& keyTimes = channel->getKeyTimes();
  377. const std::vector<float>& keyValues = channel->getKeyValues();
  378. const size_t keyTimesSize = keyTimes.size();
  379. const size_t keyValuesSize = keyValues.size();
  380. std::vector<float> scaleKeyValues;
  381. std::vector<float> rotateKeyValues;
  382. std::vector<float> translateKeyValues;
  383. scaleKeyValues.reserve(keyTimesSize * 3);
  384. rotateKeyValues.reserve(keyTimesSize * 4);
  385. translateKeyValues.reserve(keyTimesSize * 3);
  386. for (size_t kv = 0; kv < keyValuesSize; kv += 10)
  387. {
  388. scaleKeyValues.push_back(keyValues[kv]);
  389. scaleKeyValues.push_back(keyValues[kv+1]);
  390. scaleKeyValues.push_back(keyValues[kv+2]);
  391. rotateKeyValues.push_back(keyValues[kv+3]);
  392. rotateKeyValues.push_back(keyValues[kv+4]);
  393. rotateKeyValues.push_back(keyValues[kv+5]);
  394. rotateKeyValues.push_back(keyValues[kv+6]);
  395. translateKeyValues.push_back(keyValues[kv+7]);
  396. translateKeyValues.push_back(keyValues[kv+8]);
  397. translateKeyValues.push_back(keyValues[kv+9]);
  398. }
  399. // replace transform animation channel with translate, rotate and scale animation channels
  400. // Don't add the scale channel if all the key values are close to 1.0
  401. size_t oneCount = (size_t)std::count_if(scaleKeyValues.begin(), scaleKeyValues.end(), isAlmostOne);
  402. if (scaleKeyValues.size() == oneCount)
  403. {
  404. LOG(2, " Discarding scale channel.\n");
  405. }
  406. else
  407. {
  408. LOG(3, " Keeping scale channel.\n");
  409. AnimationChannel* scaleChannel = new AnimationChannel();
  410. scaleChannel->setTargetId(channel->getTargetId());
  411. scaleChannel->setKeyTimes(channel->getKeyTimes());
  412. scaleChannel->setTangentsIn(channel->getTangentsIn());
  413. scaleChannel->setTangentsOut(channel->getTangentsOut());
  414. scaleChannel->setInterpolations(channel->getInterpolationTypes());
  415. scaleChannel->setTargetAttribute(Transform::ANIMATE_SCALE);
  416. scaleChannel->setKeyValues(scaleKeyValues);
  417. scaleChannel->removeDuplicates();
  418. animation->add(scaleChannel);
  419. }
  420. // Don't add the rotation channel if all quaternions are close to identity
  421. oneCount = 0;
  422. for (unsigned int i = 0, count = rotateKeyValues.size(); i < count; i += 4)
  423. {
  424. float x = rotateKeyValues[i];
  425. float y = rotateKeyValues[i+1];
  426. float z = rotateKeyValues[i+2];
  427. float w = rotateKeyValues[i+3];
  428. if (ISZERO(x) && ISZERO(y) && ISZERO(z) && ISONE(w))
  429. ++oneCount;
  430. else
  431. {
  432. LOG(4, "Rotation not identity: %u\n", i);
  433. Quaternion q(x, y, z, w);
  434. Vector3 axis;
  435. float angle = q.toAxisAngle(&axis);
  436. angle = 0;
  437. }
  438. }
  439. if ((rotateKeyValues.size()>>2) == oneCount)
  440. {
  441. LOG(2, " Discarding rotation channel.\n");
  442. }
  443. else
  444. {
  445. LOG(3, " Keeping rotation channel.\n");
  446. AnimationChannel* rotateChannel = new AnimationChannel();
  447. rotateChannel->setTargetId(channel->getTargetId());
  448. rotateChannel->setKeyTimes(channel->getKeyTimes());
  449. rotateChannel->setTangentsIn(channel->getTangentsIn());
  450. rotateChannel->setTangentsOut(channel->getTangentsOut());
  451. rotateChannel->setInterpolations(channel->getInterpolationTypes());
  452. rotateChannel->setTargetAttribute(Transform::ANIMATE_ROTATE);
  453. rotateChannel->setKeyValues(rotateKeyValues);
  454. rotateChannel->removeDuplicates();
  455. animation->add(rotateChannel);
  456. }
  457. // Don't add the translation channel if all values are close to zero
  458. oneCount = (size_t)std::count_if(translateKeyValues.begin(), translateKeyValues.end(), isAlmostZero);
  459. if (translateKeyValues.size() == oneCount)
  460. {
  461. LOG(2, " Discarding translation channel.\n");
  462. }
  463. else
  464. {
  465. LOG(3, " Keeping translation channel.\n");
  466. AnimationChannel* translateChannel = new AnimationChannel();
  467. translateChannel->setTargetId(channel->getTargetId());
  468. translateChannel->setKeyTimes(channel->getKeyTimes());
  469. translateChannel->setTangentsIn(channel->getTangentsIn());
  470. translateChannel->setTangentsOut(channel->getTangentsOut());
  471. translateChannel->setInterpolations(channel->getInterpolationTypes());
  472. translateChannel->setTargetAttribute(Transform::ANIMATE_TRANSLATE);
  473. translateChannel->setKeyValues(translateKeyValues);
  474. translateChannel->removeDuplicates();
  475. animation->add(translateChannel);
  476. }
  477. }
  478. void GPBFile::moveAnimationChannels(Node* node, Animation* dstAnimation)
  479. {
  480. // Loop through the animations and channels backwards because they will be removed when found.
  481. int animationCount = _animations.getAnimationCount();
  482. for (int i = animationCount - 1; i >= 0; --i)
  483. {
  484. Animation* animation = _animations.getAnimation(i);
  485. int channelCount = animation->getAnimationChannelCount();
  486. for (int j = channelCount - 1; j >= 0; --j)
  487. {
  488. AnimationChannel* channel = animation->getAnimationChannel(j);
  489. if (equals(channel->getTargetId(), node->getId()))
  490. {
  491. animation->remove(channel);
  492. dstAnimation->add(channel);
  493. }
  494. }
  495. if (animation->getAnimationChannelCount() == 0)
  496. {
  497. _animations.removeAnimation(i);
  498. }
  499. }
  500. for (Node* child = node->getFirstChild(); child != NULL; child = child->getNextSibling())
  501. {
  502. moveAnimationChannels(child, dstAnimation);
  503. }
  504. }
  505. bool isAlmostOne(float value)
  506. {
  507. return (value - 1.0f) < EPSILON;
  508. }
  509. bool isAlmostZero(float value)
  510. {
  511. return std::fabs(value) < EPSILON;
  512. }
  513. Node* getCommonNodeAncestor(const std::vector<Node*>& nodes)
  514. {
  515. if (nodes.empty())
  516. return NULL;
  517. if (nodes.size() == 1)
  518. return nodes.front();
  519. std::list<Node*> ancestors;
  520. size_t minAncestorCount = INT_MAX;
  521. for (std::vector<Node*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it)
  522. {
  523. Node* node = *it;
  524. getNodeAncestors(node, ancestors);
  525. ancestors.push_back(node);
  526. minAncestorCount = std::min(minAncestorCount, ancestors.size());
  527. }
  528. ancestors.resize(minAncestorCount);
  529. return ancestors.back();
  530. }
  531. void getNodeAncestors(Node* node, std::list<Node*>& ancestors)
  532. {
  533. ancestors.clear();
  534. Node* parent = node->getParent();
  535. while (parent != NULL)
  536. {
  537. ancestors.push_front(parent);
  538. parent = parent->getParent();
  539. }
  540. }
  541. }