PuppetPhysics.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. #include "PuppetPhysics.h"
  2. #include "WallpaperEngine/Data/JSON.h"
  3. #include <algorithm>
  4. #include <cmath>
  5. #include <cstdlib>
  6. using JSON = WallpaperEngine::Data::JSON::JSON;
  7. // Ported from wallpaper64.exe 2.8.42. The math keeps WE's row-vector convention: a 3x3 is three rows, points
  8. // transform as v * M, and quaternions are w, x, y, z.
  9. namespace WallpaperEngine::Render::Objects {
  10. namespace {
  11. constexpr float kDegToRad = 0.017453292f;
  12. constexpr float kRadToDeg = 57.29578f;
  13. constexpr float kPi = 3.1415927f;
  14. constexpr float kTwoPi = 6.2831855f;
  15. struct Rows {
  16. glm::vec3 r[3];
  17. };
  18. // w, x, y, z in the vec4's x, y, z, w
  19. using Quat = glm::vec4;
  20. const Quat kIdentity { 1.0f, 0.0f, 0.0f, 0.0f };
  21. glm::vec3 mulRow (const glm::vec3& v, const Rows& m) { return v.x * m.r[0] + v.y * m.r[1] + v.z * m.r[2]; }
  22. // sub_140215380
  23. Quat multiply (const Quat& a, const Quat& b) {
  24. return {
  25. b.x * a.x - b.y * a.y - b.z * a.z - b.w * a.w,
  26. b.y * a.x + a.y * b.x + b.w * a.z - a.w * b.z,
  27. b.z * a.x + a.z * b.x + a.w * b.y - b.w * a.y,
  28. b.w * a.x + a.w * b.x + b.z * a.y - a.z * b.y,
  29. };
  30. }
  31. // sub_140216070
  32. Quat slerp (const Quat& a, Quat b, float t) {
  33. float cosine = glm::dot (a, b);
  34. if (cosine < 0.0f) {
  35. b = -b;
  36. cosine = -cosine;
  37. }
  38. if (cosine > 0.99999988f) {
  39. return a * (1.0f - t) + b * t;
  40. }
  41. const float angle = std::acos (cosine);
  42. const float sine = std::sin (angle);
  43. return (a * std::sin ((1.0f - t) * angle) + b * std::sin (angle * t)) / sine;
  44. }
  45. // sub_140217AC0
  46. Quat normalize (const Quat& q) {
  47. const float length = std::sqrt (glm::dot (q, q));
  48. return length > 0.0f ? q * (1.0f / length) : kIdentity;
  49. }
  50. // sub_1402167C0, the shortest rotation taking direction `from` onto `to`
  51. Quat rotationArc (const glm::vec3& from, const glm::vec3& to) {
  52. const float cosine = glm::dot (from, to);
  53. if (cosine >= 0.99999988f) {
  54. return kIdentity;
  55. }
  56. if (cosine < -0.99999988f) {
  57. glm::vec3 axis (-from.y, from.x, 0.0f);
  58. if (glm::dot (axis, axis) < 0.00000011920929f) {
  59. axis = glm::vec3 (0.0f, -from.z, from.y);
  60. }
  61. axis *= 1.0f / std::sqrt (glm::dot (axis, axis));
  62. return { std::cos (1.5707964f), axis.x, axis.y, axis.z };
  63. }
  64. const float s = std::sqrt ((cosine + 1.0f) + (cosine + 1.0f));
  65. const glm::vec3 axis = glm::cross (from, to) * (1.0f / s);
  66. return { s * 0.5f, axis.x, axis.y, axis.z };
  67. }
  68. // quaternion of the Euler angles, as built inline all over sub_1401FDF90
  69. Quat fromEuler (const glm::vec3& angles) {
  70. const glm::vec3 half = angles * 0.5f;
  71. const float c1 = std::cos (half.x), s1 = std::sin (half.x);
  72. const float c2 = std::cos (half.y), s2 = std::sin (half.y);
  73. const float c3 = std::cos (half.z), s3 = std::sin (half.z);
  74. return {
  75. s2 * s1 * s3 + c2 * c1 * c3,
  76. c2 * s1 * c3 - s2 * c1 * s3,
  77. c2 * s1 * s3 + s2 * c1 * c3,
  78. c2 * c1 * s3 - s2 * s1 * c3,
  79. };
  80. }
  81. Rows eulerRows (const glm::vec3& angles) {
  82. const float cx = std::cos (angles.x), sx = std::sin (angles.x);
  83. const float cy = std::cos (angles.y), sy = std::sin (angles.y);
  84. const float cz = std::cos (angles.z), sz = std::sin (angles.z);
  85. return { {
  86. { cy * cz, cy * sz, -sy },
  87. { sy * cz * sx - cx * sz, sy * sz * sx + cx * cz, sx * cy },
  88. { cx * cz * sy + sx * sz, cx * sz * sy - sx * cz, cx * cy },
  89. } };
  90. }
  91. // sub_140216280
  92. Rows quatRows (const Quat& q) {
  93. const float w = q.x, x = q.y, y = q.z, z = q.w;
  94. return { {
  95. { 1.0f - 2.0f * (z * z + y * y), 2.0f * (z * w + x * y), 2.0f * (x * z - y * w) },
  96. { 2.0f * (x * y - z * w), 1.0f - 2.0f * (z * z + x * x), 2.0f * (x * w + y * z) },
  97. { 2.0f * (y * w + x * z), 2.0f * (y * z - x * w), 1.0f - 2.0f * (y * y + x * x) },
  98. } };
  99. }
  100. glm::vec3 eulerFromRows (const Rows& n) {
  101. const float z = std::atan2 (n.r[0].y, n.r[0].x);
  102. const float y = std::atan2 (-n.r[0].z, std::sqrt (n.r[2].z * n.r[2].z + n.r[1].z * n.r[1].z));
  103. const float sz = std::sin (z), cz = std::cos (z);
  104. const float x = std::atan2 (sz * n.r[2].x - cz * n.r[2].y, cz * n.r[1].y - sz * n.r[1].x);
  105. return { x, y, z };
  106. }
  107. float wrapAngle (float angle, bool locked) {
  108. if (locked) {
  109. return 0.0f;
  110. }
  111. if (angle < 0.0f) {
  112. return std::fmod (angle - kPi, kTwoPi) + kPi;
  113. }
  114. return std::fmod (angle + kPi, kTwoPi) - kPi;
  115. }
  116. glm::vec3 parseVector (const std::string& text) {
  117. glm::vec3 result (0.0f);
  118. const char* cursor = text.c_str ();
  119. for (int i = 0; i < 3 && *cursor != '\0'; i++) {
  120. char* end = nullptr;
  121. result[i] = std::strtof (cursor, &end);
  122. if (end == cursor) {
  123. break;
  124. }
  125. cursor = end;
  126. }
  127. return result;
  128. }
  129. } // namespace
  130. PuppetBonePhysics PuppetBonePhysics::parse (const std::string& text) {
  131. PuppetBonePhysics result;
  132. const JSON json = JSON::parse (text, nullptr, false);
  133. if (!json.is_object ()) {
  134. return result;
  135. }
  136. const auto isTrue = [&json] (const char* key) {
  137. const auto it = json.find (key);
  138. return it != json.end () && it->is_boolean () && it->get<bool> ();
  139. };
  140. const auto number = [&json] (const char* key, float& out) {
  141. const auto it = json.find (key);
  142. if (it != json.end () && it->is_number ()) {
  143. out = it->get<float> ();
  144. }
  145. };
  146. const auto vector = [&json] (const char* key, glm::vec3& out) {
  147. const auto it = json.find (key);
  148. if (it != json.end () && it->is_string ()) {
  149. out = parseVector (it->get<std::string> ());
  150. return true;
  151. }
  152. return false;
  153. };
  154. uint32_t flags = 0;
  155. flags |= isTrue ("ik") ? InverseKinematics : 0;
  156. flags |= isTrue ("r") ? Rotation : 0;
  157. flags |= isTrue ("t") ? Translation : 0;
  158. flags |= isTrue ("se") ? Simulate : 0;
  159. flags |= isTrue ("re") ? SimulateRelative : 0;
  160. // only "se" bones are ported: WE takes its "re" branch first when that is set, and IK chains are separate. No
  161. // installed wallpaper uses either
  162. if ((flags & Simulate) == 0 || (flags & SimulateRelative) != 0 || (flags & (Rotation | Translation)) == 0) {
  163. return result;
  164. }
  165. flags |= isTrue ("ge") ? Gravity : 0;
  166. vector ("gd", result.gravityDirection);
  167. number ("m", result.mass);
  168. number ("tf", result.translationFriction);
  169. number ("rs", result.rotationStiffness);
  170. number ("ts", result.translationStiffness);
  171. number ("rf", result.rotationFriction);
  172. vector ("tp", result.target);
  173. number ("tm", result.maxTranslation);
  174. float inertia = 0.0f;
  175. if (json.contains ("ri") && json["ri"].is_number ()) {
  176. number ("ri", inertia);
  177. result.rotationInertia = 1.0f - inertia / 100.0f;
  178. }
  179. if (json.contains ("ti") && json["ti"].is_number ()) {
  180. number ("ti", inertia);
  181. result.translationInertia = 1.0f - inertia / 100.0f;
  182. }
  183. if (isTrue ("la")) {
  184. flags |= AngleLimits;
  185. vector ("lamin", result.angleMin);
  186. vector ("lamax", result.angleMax);
  187. }
  188. if (isTrue ("lt")) {
  189. flags |= TotalAngleLimit;
  190. number ("ltmax", result.maxAngle);
  191. }
  192. // axis locks only count when all three keys are there, an axis set to false is locked
  193. const auto locks = [&json, &flags] (const char* x, const char* y, const char* z, uint32_t firstFlag) {
  194. const char* keys[] = { x, y, z };
  195. for (const char* key : keys) {
  196. if (!json.contains (key) || !json[key].is_boolean ()) {
  197. return;
  198. }
  199. }
  200. for (int i = 0; i < 3; i++) {
  201. if (!json[keys[i]].get<bool> ()) {
  202. flags |= firstFlag << i;
  203. }
  204. }
  205. };
  206. locks ("rax", "ray", "raz", LockRotationX);
  207. locks ("tax", "tay", "taz", LockTranslationX);
  208. result.flags = flags;
  209. return result;
  210. }
  211. glm::mat4 stepPuppetBonePhysics (
  212. const PuppetBonePhysics& physics, PuppetBonePhysicsState& state, const glm::mat4& world,
  213. const glm::mat4& previousWorld, float dt, float objectScale
  214. ) {
  215. const uint32_t flags = physics.flags;
  216. const Rows current { { glm::vec3 (world[0]), glm::vec3 (world[1]), glm::vec3 (world[2]) } };
  217. const Rows previous { { glm::vec3 (previousWorld[0]), glm::vec3 (previousWorld[1]), glm::vec3 (previousWorld[2]) } };
  218. const glm::vec3 currentOrigin (world[3]);
  219. const glm::vec3 previousOrigin (previousWorld[3]);
  220. // v * inverse, from world space into this bone's space
  221. const glm::mat3 inverse = glm::inverse (glm::mat3 (world));
  222. const auto toBone = [&inverse] (const glm::vec3& v) { return inverse * v; };
  223. // where the target point was last frame, seen from the bone as it is now
  224. const glm::vec3 previousTarget = toBone (mulRow (physics.target, previous) + previousOrigin - currentOrigin);
  225. const glm::vec3 previousDirection = glm::normalize (previousTarget);
  226. glm::vec3 localOffset = toBone (state.offset);
  227. const glm::vec3 rotatedTarget = mulRow (physics.target, eulerRows (state.angles));
  228. glm::vec3 predicted = rotatedTarget + localOffset;
  229. if (flags & PuppetBonePhysics::Gravity) {
  230. const glm::vec3 gravity = toBone (physics.gravityDirection) * (physics.mass * objectScale);
  231. const glm::vec3 direction = glm::normalize (rotatedTarget);
  232. predicted -= gravity - glm::dot (direction, gravity) * direction;
  233. if (flags & PuppetBonePhysics::Translation) {
  234. state.velocity += physics.gravityDirection * (physics.mass * dt * 1000.0f);
  235. }
  236. }
  237. const float distance = std::min (glm::length (predicted - previousTarget), dt * 900.0f);
  238. const Quat arc = rotationArc (glm::normalize (predicted), previousDirection);
  239. if ((flags & PuppetBonePhysics::Simulate) && (flags & PuppetBonePhysics::Rotation)) {
  240. Quat& velocity = state.angularVelocity;
  241. velocity = multiply (velocity, slerp (kIdentity, arc, std::min (distance * physics.rotationInertia * kDegToRad, 1.0f)));
  242. velocity = multiply (
  243. velocity,
  244. slerp (kIdentity, fromEuler (-state.angles), std::min (physics.rotationStiffness * kDegToRad * dt, 1.0f))
  245. );
  246. if (flags & PuppetBonePhysics::TotalAngleLimit) {
  247. const float w = velocity.x;
  248. velocity = { 1.0f, velocity.y / w, velocity.z / w, velocity.w / w };
  249. for (int i = 1; i < 4; i++) {
  250. float angle = std::atan (velocity[i]) * kRadToDeg * 2.0f;
  251. angle = std::max (std::min (angle, physics.maxAngle), -physics.maxAngle);
  252. velocity[i] = std::tan (angle * kDegToRad * 0.5f);
  253. }
  254. velocity = normalize (velocity);
  255. }
  256. // velocity is per 60 Hz frame
  257. const Quat step = slerp (kIdentity, velocity, std::min (dt / 0.016666668f, 1.0f));
  258. const Rows angles = eulerRows (state.angles);
  259. const Rows rotation = quatRows (step);
  260. const Rows combined { { mulRow (angles.r[0], rotation), mulRow (angles.r[1], rotation),
  261. mulRow (angles.r[2], rotation) } };
  262. const glm::vec3 next = eulerFromRows (combined);
  263. state.angles = {
  264. wrapAngle (next.x, flags & PuppetBonePhysics::LockRotationX),
  265. wrapAngle (next.y, flags & PuppetBonePhysics::LockRotationY),
  266. wrapAngle (next.z, flags & PuppetBonePhysics::LockRotationZ),
  267. };
  268. if (flags & PuppetBonePhysics::AngleLimits) {
  269. const glm::vec3 clamped = glm::min (glm::max (state.angles, physics.angleMin), physics.angleMax);
  270. const Quat overshoot = fromEuler (state.angles - clamped);
  271. state.angles = clamped;
  272. velocity = multiply ({ overshoot.x, -overshoot.y, -overshoot.z, -overshoot.w }, velocity);
  273. }
  274. velocity = slerp (velocity, kIdentity, std::min (dt * physics.rotationFriction, 1.0f));
  275. }
  276. if ((flags & PuppetBonePhysics::Simulate) && (flags & PuppetBonePhysics::Translation)) {
  277. const glm::vec3 pulled
  278. = state.offset - (state.offset + currentOrigin - previousOrigin) * physics.translationInertia;
  279. glm::vec3 velocity = state.velocity - (dt * physics.translationStiffness) * pulled;
  280. glm::vec3 offset = pulled + dt * velocity;
  281. for (int axis = 0; axis < 3; axis++) {
  282. if (flags & (PuppetBonePhysics::LockTranslationX << axis)) {
  283. const glm::vec3& direction = current.r[axis];
  284. offset -= glm::dot (offset, direction) / glm::dot (direction, direction) * direction;
  285. }
  286. }
  287. const float limit = objectScale * physics.maxTranslation;
  288. if (limit > 0.0f && limit * limit < glm::dot (offset, offset)) {
  289. offset *= limit / glm::length (offset);
  290. }
  291. velocity -= std::min (dt * physics.translationFriction, 1.0f) * velocity;
  292. state.offset = offset;
  293. state.velocity = velocity;
  294. localOffset = toBone (offset);
  295. }
  296. // rows of the Euler rotation plus the offset, glm columns hold WE's rows
  297. const Rows rotation = eulerRows (state.angles);
  298. return {
  299. glm::vec4 (rotation.r[0], 0.0f),
  300. glm::vec4 (rotation.r[1], 0.0f),
  301. glm::vec4 (rotation.r[2], 0.0f),
  302. glm::vec4 (localOffset, 1.0f),
  303. };
  304. }
  305. } // namespace WallpaperEngine::Render::Objects