MeshSkin.cpp 14 KB

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