MeshSkin.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. #include "Base.h"
  2. #include "MeshSkin.h"
  3. #include "Node.h"
  4. #include "StringUtil.h"
  5. #include "Mesh.h"
  6. #include "GPBFile.h"
  7. #include "Animations.h"
  8. #include "Transform.h"
  9. #include "Curve.h"
  10. #include "Matrix.h"
  11. namespace gameplay
  12. {
  13. MeshSkin::MeshSkin(void) :
  14. _vertexInfluenceCount(0)
  15. {
  16. Matrix::setIdentity(_bindShape);
  17. }
  18. MeshSkin::~MeshSkin(void)
  19. {
  20. }
  21. unsigned int MeshSkin::getTypeId(void) const
  22. {
  23. return MESHPART_ID;
  24. }
  25. const char* MeshSkin::getElementName(void) const
  26. {
  27. return "MeshSkin";
  28. }
  29. void MeshSkin::writeBinary(FILE* file)
  30. {
  31. Object::writeBinary(file);
  32. write(_bindShape, 16, file);
  33. write((unsigned int)_joints.size(), file);
  34. for (std::vector<Node*>::const_iterator i = _joints.begin(); i != _joints.end(); ++i)
  35. {
  36. (*i)->writeBinaryXref(file);
  37. }
  38. write((unsigned int)_bindPoses.size() * 16, file);
  39. for (std::vector<Matrix>::const_iterator i = _bindPoses.begin(); i != _bindPoses.end(); ++i)
  40. {
  41. write(i->m, 16, file);
  42. }
  43. /*
  44. // Write joint bounding spheres
  45. write((unsigned int)_jointBounds.size(), file);
  46. for (unsigned int i = 0; i < _jointBounds.size(); ++i)
  47. {
  48. BoundingVolume& v = _jointBounds[i];
  49. write(v.center.x, file);
  50. write(v.center.y, file);
  51. write(v.center.z, file);
  52. write(v.radius, file);
  53. }
  54. */
  55. }
  56. void MeshSkin::writeText(FILE* file)
  57. {
  58. fprintElementStart(file);
  59. fprintf(file, "<bindShape>");
  60. fprintfMatrix4f(file, _bindShape);
  61. fprintf(file, "</bindShape>");
  62. fprintf(file, "<joints>");
  63. for (std::vector<std::string>::const_iterator i = _jointNames.begin(); i != _jointNames.end(); ++i)
  64. {
  65. fprintf(file, "%s ", i->c_str());
  66. }
  67. fprintf(file, "</joints>\n");
  68. fprintf(file, "<bindPoses count=\"%lu\">", _bindPoses.size() * 16);
  69. for (std::vector<Matrix>::const_iterator i = _bindPoses.begin(); i != _bindPoses.end(); ++i)
  70. {
  71. for (unsigned int j = 0; j < 16; ++j)
  72. {
  73. fprintf(file, "%f ", i->m[j]);
  74. }
  75. }
  76. fprintf(file, "</bindPoses>\n");
  77. fprintElementEnd(file);
  78. }
  79. unsigned int MeshSkin::getJointCount() const
  80. {
  81. return _joints.size();
  82. }
  83. void MeshSkin::setBindShape(const float data[])
  84. {
  85. for (int i = 0; i < 16; ++i)
  86. {
  87. _bindShape[i] = data[i];
  88. }
  89. }
  90. void MeshSkin::setVertexInfluenceCount(unsigned int count)
  91. {
  92. _vertexInfluenceCount = count;
  93. }
  94. void MeshSkin::setJointNames(const std::vector<std::string>& list)
  95. {
  96. _jointNames = list;
  97. }
  98. const std::vector<std::string>& MeshSkin::getJointNames()
  99. {
  100. return _jointNames;
  101. }
  102. const std::vector<Node*>& MeshSkin::getJoints() const
  103. {
  104. return _joints;
  105. }
  106. void MeshSkin::setJoints(const std::vector<Node*>& list)
  107. {
  108. _joints = list;
  109. }
  110. void MeshSkin::setBindPoses(std::vector<Matrix>& list)
  111. {
  112. for (std::vector<Matrix>::iterator i = list.begin(); i != list.end(); ++i)
  113. {
  114. _bindPoses.push_back(*i);
  115. }
  116. }
  117. bool MeshSkin::hasJoint(const char* id)
  118. {
  119. for (std::vector<std::string>::iterator i = _jointNames.begin(); i != _jointNames.end(); ++i)
  120. {
  121. if (equals(*i, id))
  122. {
  123. return true;
  124. }
  125. }
  126. return false;
  127. }
  128. void MeshSkin::computeBounds()
  129. {
  130. // Find the offset of the blend indices and blend weights within the mesh vertices
  131. int blendIndexOffset = -1;
  132. int blendWeightOffset = -1;
  133. for (unsigned int i = 0, count = _mesh->getVertexElementCount(); i < count; ++i)
  134. {
  135. const VertexElement& e = _mesh->getVertexElement(i);
  136. switch (e.usage)
  137. {
  138. case BLENDINDICES:
  139. blendIndexOffset = i;
  140. break;
  141. case BLENDWEIGHTS:
  142. blendWeightOffset = i;
  143. break;
  144. }
  145. }
  146. if (blendIndexOffset == -1 || blendWeightOffset == -1)
  147. {
  148. // Need blend indices and blend weights to calculate skinned bounding volume
  149. return;
  150. }
  151. LOG(2, "Computing bounds for skin of mesh: %s\n", _mesh->getId().c_str());
  152. // Get the root joint
  153. Node* rootJoint = _joints[0];
  154. Node* parent = rootJoint->getParent();
  155. while (parent)
  156. {
  157. // Is this parent in the list of joints that form the skeleton?
  158. // If not, then it's simply a parent node to the root joint
  159. if (find(_joints.begin(), _joints.end(), parent) != _joints.end())
  160. {
  161. rootJoint = parent;
  162. }
  163. parent = parent->getParent();
  164. }
  165. // If the root joint has a parent node, temporarily detach it so that its transform is
  166. // not included in the bounding volume calculation below
  167. Node* rootJointParent = rootJoint->getParent();
  168. if (rootJointParent)
  169. {
  170. rootJointParent->removeChild(rootJoint);
  171. }
  172. unsigned int jointCount = _joints.size();
  173. unsigned int vertexCount = _mesh->getVertexCount();
  174. LOG(3, " %u joints found.\n", jointCount);
  175. std::vector<AnimationChannel*> channels;
  176. std::vector<Node*> channelTargets;
  177. std::vector<Curve*> curves;
  178. std::vector<Vector3> vertices;
  179. _jointBounds.resize(jointCount);
  180. // Construct a list of all animation channels that target the joints affecting this mesh skin
  181. LOG(3, " Collecting animations...\n");
  182. LOG(3, " 0%%\r");
  183. for (unsigned int i = 0; i < jointCount; ++i)
  184. {
  185. Node* joint = _joints[i];
  186. // Find all animations that target this joint
  187. Animations* animations = GPBFile::getInstance()->getAnimations();
  188. for (unsigned int j = 0, animationCount = animations->getAnimationCount(); j < animationCount; ++j)
  189. {
  190. Animation* animation = animations->getAnimation(j);
  191. for (unsigned int k = 0, channelCount = animation->getAnimationChannelCount(); k < channelCount; ++k)
  192. {
  193. AnimationChannel* channel = animation->getAnimationChannel(k);
  194. if (channel->getTargetId() == joint->getId())
  195. {
  196. if (find(channels.begin(), channels.end(), channel) == channels.end())
  197. {
  198. channels.push_back(channel);
  199. channelTargets.push_back(joint);
  200. }
  201. }
  202. }
  203. }
  204. // Calculate the local bounding volume for this joint
  205. vertices.clear();
  206. BoundingVolume jointBounds;
  207. jointBounds.min.set(FLT_MAX, FLT_MAX, FLT_MAX);
  208. jointBounds.max.set(-FLT_MAX, -FLT_MAX, -FLT_MAX);
  209. for (unsigned int j = 0; j < vertexCount; ++j)
  210. {
  211. const Vertex& v = _mesh->getVertex(j);
  212. if ((v.blendIndices.x == i && !ISZERO(v.blendWeights.x)) ||
  213. (v.blendIndices.y == i && !ISZERO(v.blendWeights.y)) ||
  214. (v.blendIndices.z == i && !ISZERO(v.blendWeights.z)) ||
  215. (v.blendIndices.w == i && !ISZERO(v.blendWeights.w)))
  216. {
  217. vertices.push_back(v.position);
  218. // Update box min/max
  219. if (v.position.x < jointBounds.min.x)
  220. jointBounds.min.x = v.position.x;
  221. if (v.position.y < jointBounds.min.y)
  222. jointBounds.min.y = v.position.y;
  223. if (v.position.z < jointBounds.min.z)
  224. jointBounds.min.z = v.position.z;
  225. if (v.position.x > jointBounds.max.x)
  226. jointBounds.max.x = v.position.x;
  227. if (v.position.y > jointBounds.max.y)
  228. jointBounds.max.y = v.position.y;
  229. if (v.position.z > jointBounds.max.z)
  230. jointBounds.max.z = v.position.z;
  231. }
  232. }
  233. if (vertices.size() > 0)
  234. {
  235. // Compute center point
  236. Vector3::add(jointBounds.min, jointBounds.max, &jointBounds.center);
  237. jointBounds.center.scale(0.5f);
  238. // Compute radius
  239. for (unsigned int j = 0, jointVertexCount = vertices.size(); j < jointVertexCount; ++j)
  240. {
  241. float d = jointBounds.center.distanceSquared(vertices[j]);
  242. if (d > jointBounds.radius)
  243. jointBounds.radius = d;
  244. }
  245. jointBounds.radius = sqrt(jointBounds.radius);
  246. }
  247. _jointBounds[i] = jointBounds;
  248. LOG(3, " %d%%\r", (int)((float)(i+1) / (float)jointCount * 100.0f));
  249. }
  250. LOG(3, "\n");
  251. unsigned int channelCount = channels.size();
  252. // Create a Curve for each animation channel
  253. float maxDuration = 0.0f;
  254. LOG(3, " Building animation curves...\n");
  255. LOG(3, " 0%%\r");
  256. for (unsigned int i = 0; i < channelCount; ++i)
  257. {
  258. AnimationChannel* channel = channels[i];
  259. const std::vector<float>& keyTimes = channel->getKeyTimes();
  260. unsigned int keyCount = keyTimes.size();
  261. if (keyCount == 0)
  262. continue;
  263. // Create a curve for this animation channel
  264. Curve* curve = NULL;
  265. switch (channel->getTargetAttribute())
  266. {
  267. case Transform::ANIMATE_SCALE_ROTATE_TRANSLATE:
  268. curve = new Curve(keyCount, 10);
  269. curve->setQuaternionOffset(3);
  270. break;
  271. }
  272. if (curve == NULL)
  273. {
  274. // Unsupported/not implemented curve type
  275. continue;
  276. }
  277. // Copy key values into a temporary array
  278. unsigned int keyValuesCount = channel->getKeyValues().size();
  279. float* keyValues = new float[keyValuesCount];
  280. for (unsigned int j = 0; j < keyValuesCount; ++j)
  281. keyValues[j] = channel->getKeyValues()[j];
  282. // Determine animation duration
  283. float startTime = keyTimes[0];
  284. float duration = keyTimes[keyCount-1] - startTime;
  285. if (duration > maxDuration)
  286. maxDuration = duration;
  287. if (duration > 0.0f)
  288. {
  289. // Set curve points
  290. float* keyValuesPtr = keyValues;
  291. for (unsigned int j = 0; j < keyCount; ++j)
  292. {
  293. // Store time normalized, between 0-1
  294. float t = (keyTimes[j] - startTime) / duration;
  295. // Set the curve point
  296. // TODO: Handle other interpolation types
  297. curve->setPoint(j, t, keyValuesPtr, gameplay::Curve::LINEAR);
  298. // Move to the next point on the curve
  299. keyValuesPtr += curve->getComponentCount();
  300. }
  301. curves.push_back(curve);
  302. }
  303. delete[] keyValues;
  304. keyValues = NULL;
  305. LOG(3, " %d%%\r", (int)((float)(i+1) / (float)channelCount * 100.0f));
  306. }
  307. LOG(3, "\n");
  308. // Compute a total combined bounding volume for the MeshSkin that contains all possible
  309. // vertex positions for all animations targeting the skin. This rough approximation allows
  310. // us to store a volume that can be used for rough intersection tests (such as for visibility
  311. // determination) efficiently at runtime.
  312. // Backup existing node transforms so we can restore them when we are finished
  313. Matrix* oldTransforms = new Matrix[jointCount];
  314. for (unsigned int i = 0; i < jointCount; ++i)
  315. {
  316. memcpy(oldTransforms[i].m, _joints[i]->getTransformMatrix().m, 16 * sizeof(float));
  317. }
  318. float time = 0.0f;
  319. float srt[10];
  320. Matrix temp;
  321. Matrix* jointTransforms = new Matrix[jointCount];
  322. _mesh->bounds.min.set(FLT_MAX, FLT_MAX, FLT_MAX);
  323. _mesh->bounds.max.set(-FLT_MAX, -FLT_MAX, -FLT_MAX);
  324. _mesh->bounds.center.set(0, 0, 0);
  325. _mesh->bounds.radius = 0;
  326. Vector3 skinnedPos;
  327. Vector3 tempPos;
  328. LOG(3, " Evaluating joints...\n");
  329. LOG(3, " 0%%\r");
  330. BoundingVolume finalBounds;
  331. while (time <= maxDuration)
  332. {
  333. // Evaluate joint transforms at this time interval
  334. for (unsigned int i = 0, curveCount = curves.size(); i < curveCount; ++i)
  335. {
  336. Node* joint = channelTargets[i];
  337. Curve* curve = curves[i];
  338. // Evalulate the curve at this time to get the new value
  339. float tn = time / maxDuration;
  340. if (tn > 1.0f)
  341. tn = 1.0f;
  342. curve->evaluate(tn, srt);
  343. // Update the joint's local transform
  344. Matrix::createTranslation(srt[7], srt[8], srt[9], temp.m);
  345. temp.rotate(*((Quaternion*)&srt[3]));
  346. temp.scale(srt[0], srt[1], srt[2]);
  347. joint->setTransformMatrix(temp.m);
  348. }
  349. // Store the final matrix pallette of resovled world space joint matrices
  350. std::vector<Matrix>::const_iterator bindPoseItr = _bindPoses.begin();
  351. for (unsigned int i = 0; i < jointCount; ++i, bindPoseItr++)
  352. {
  353. BoundingVolume bounds = _jointBounds[i];
  354. if (ISZERO(bounds.radius))
  355. continue;
  356. Matrix& m = jointTransforms[i];
  357. Matrix::multiply(_joints[i]->getWorldMatrix().m, bindPoseItr->m, m.m);
  358. Matrix::multiply(m.m, _bindShape, m.m);
  359. // Get a world-space bounding volume for this joint
  360. bounds.transform(m);
  361. if (ISZERO(finalBounds.radius))
  362. finalBounds = bounds;
  363. else
  364. finalBounds.merge(bounds);
  365. }
  366. // Increment time by 1/30th of second (~ 33 ms)
  367. if (time < maxDuration && (time + 33.0f) > maxDuration)
  368. time = maxDuration;
  369. else
  370. time += 33.0f;
  371. LOG(3, " %d%%\r", (int)(time / maxDuration * 100.0f));
  372. }
  373. LOG(3, "\n");
  374. // Update the bounding sphere for the mesh
  375. _mesh->bounds = finalBounds;
  376. // Restore original joint transforms
  377. for (unsigned int i = 0; i < jointCount; ++i)
  378. {
  379. _joints[i]->setTransformMatrix(oldTransforms[i].m);
  380. }
  381. // Cleanup
  382. for (unsigned int i = 0, curveCount = curves.size(); i < curveCount; ++i)
  383. {
  384. delete curves[i];
  385. }
  386. delete[] oldTransforms;
  387. delete[] jointTransforms;
  388. // Restore removed joints
  389. if (rootJointParent)
  390. {
  391. rootJointParent->addChild(rootJoint);
  392. }
  393. }
  394. }