PuppetIK.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. #include "PuppetIK.h"
  2. #include "PuppetPhysics.h"
  3. #include "WallpaperEngine/Data/JSON.h"
  4. #include "WallpaperEngine/Render/Utils/NoiseUtils.h"
  5. #include <algorithm>
  6. #include <bit>
  7. #include <cmath>
  8. #include <glm/gtc/quaternion.hpp>
  9. #include <glm/gtc/type_ptr.hpp>
  10. using JSON = WallpaperEngine::Data::JSON::JSON;
  11. // wallpaper64.exe 2.8.42 sub_140271910. glm columns hold WE's rows
  12. namespace WallpaperEngine::Render::Objects {
  13. namespace {
  14. glm::vec3 position (const glm::mat4& m) { return glm::vec3 (m[3]); }
  15. void setPosition (glm::mat4& m, const glm::vec3& p) { m[3] = glm::vec4 (p, m[3].w); }
  16. // sub_140214EB0, fast inverse sqrt
  17. glm::vec4 fastNormalize (const glm::vec4& row) {
  18. const float squared = row.w * row.w + row.z * row.z + (row.y * row.y + row.x * row.x);
  19. const float guess = std::bit_cast<float> (0x5F375A86u - (std::bit_cast<uint32_t> (squared) >> 1));
  20. const float inverse = (1.5f - squared * 0.5f * guess * guess) * guess;
  21. return row * inverse;
  22. }
  23. // shortest arc, w x y z
  24. glm::vec4 arc (const glm::vec3& from, const glm::vec3& to) {
  25. const float cosine = glm::dot (from, to);
  26. if (cosine >= 0.99999988f) {
  27. return { 1.0f, 0.0f, 0.0f, 0.0f };
  28. }
  29. if (cosine < -0.99999988f) {
  30. return puppetRotationArc (from, to);
  31. }
  32. const float s = std::sqrt ((cosine + 1.0f) + (cosine + 1.0f));
  33. return {
  34. s * 0.5f,
  35. (from.y * to.z - from.z * to.y) * (1.0f / s),
  36. (from.z * to.x - from.x * to.z) * (1.0f / s),
  37. (from.x * to.y - from.y * to.x) * (1.0f / s),
  38. };
  39. }
  40. // rows of Q * bind
  41. void rotateRows (glm::mat4& out, const glm::vec4& q, const glm::mat4& bind) {
  42. const glm::mat3 rows = puppetQuatRows (q);
  43. for (int j = 0; j < 3; j++) {
  44. out[j] = rows[j].x * bind[0] + rows[j].y * bind[1] + rows[j].z * bind[2];
  45. }
  46. }
  47. glm::vec4 quatFromRows (const glm::mat4& m) {
  48. const glm::quat q = glm::quat_cast (glm::mat3 (glm::vec3 (m[0]), glm::vec3 (m[1]), glm::vec3 (m[2])));
  49. return { q.w, q.x, q.y, q.z };
  50. }
  51. const glm::vec3* childDirection (const PuppetIKRig& rig, int bone, int child) {
  52. if (bone < 0 || static_cast<size_t> (bone) >= rig.childDirections.size ()) {
  53. return nullptr;
  54. }
  55. const auto& map = rig.childDirections[bone];
  56. const auto it = map.find (static_cast<uint32_t> (child));
  57. return it == map.end () ? nullptr : &it->second;
  58. }
  59. float length (const PuppetIKRig& rig, int bone) {
  60. return bone >= 0 && static_cast<size_t> (bone) < rig.lengths.size () ? rig.lengths[bone] : 0.0f;
  61. }
  62. glm::vec3 transformPoint (const glm::mat4& m, const glm::vec3& p) { return glm::vec3 (m * glm::vec4 (p, 1.0f)); }
  63. const PuppetBoneIK& endSettings (const std::vector<PuppetBoneIK>& ik, uint32_t bone) {
  64. static const PuppetBoneIK none;
  65. return bone < ik.size () ? ik[bone] : none;
  66. }
  67. // sub_14026E340: one length constraint sweep over a rope; "ikse" stretches every bone alike
  68. void constrainRope (
  69. const PuppetIKRig& rig, const PuppetIKEntry& entry, const PuppetBoneIK& end, const glm::mat4& world,
  70. const glm::mat4& inverse, std::vector<PuppetRopeJoint>& joints, bool forward
  71. ) {
  72. const auto& bones = entry.bones;
  73. const glm::vec3 span = joints[entry.endBone].current - joints[bones[0]].current;
  74. const float distance = std::sqrt ((span.x * span.x + span.y * span.y) + span.z * span.z);
  75. float scale = 1.0f;
  76. if (distance > entry.length && (end.flags & PuppetBoneIK::SolveEnd)) {
  77. scale = distance / entry.length;
  78. }
  79. const bool freeEnd = (end.flags & PuppetBoneIK::FollowParent) != 0;
  80. const int count = static_cast<int> (bones.size ()) - (freeEnd ? 0 : 1);
  81. for (int i = 1; i < count; i++) {
  82. int child;
  83. int parent;
  84. if (forward) {
  85. child = bones[i];
  86. parent = bones[i - 1];
  87. } else {
  88. const int k = count - i;
  89. child = bones[freeEnd ? k : k + 1];
  90. parent = bones[freeEnd ? k - 1 : k];
  91. }
  92. const float rest = scale * length (rig, child);
  93. const glm::vec3 from = transformPoint (inverse, joints[parent].current);
  94. const glm::vec3 to = transformPoint (inverse, joints[child].current);
  95. const glm::vec3 offset = to - from;
  96. const float current = std::sqrt ((offset.y * offset.y + offset.x * offset.x) + offset.z * offset.z);
  97. const float miss = rest - current;
  98. if (std::fabs (miss) <= 0.001f) {
  99. continue;
  100. }
  101. const glm::vec3 direction = current <= 0.0099999998f ? glm::vec3 (0.707f, 0.707f, 0.0f) : offset / current;
  102. if (forward && i == 1) {
  103. joints[child].current = transformPoint (world, to + direction * miss);
  104. } else if (!forward && i == 1) {
  105. joints[parent].current = transformPoint (world, from - direction * miss);
  106. } else {
  107. const float half = miss * 0.5f;
  108. joints[child].current = transformPoint (world, to + direction * half);
  109. joints[parent].current = transformPoint (world, from - direction * half);
  110. }
  111. }
  112. }
  113. // WE's row major helpers
  114. struct Euler {
  115. float a, b, c;
  116. };
  117. // sub_1401E23D0
  118. Euler eulerOf (const glm::mat4& matrix) {
  119. const float* m = glm::value_ptr (matrix);
  120. const float a = std::atan2 (m[1], m[0]);
  121. const float b = std::atan2 (-m[2], std::sqrt (m[6] * m[6] + m[10] * m[10]));
  122. const float s = std::sin (a);
  123. const float c = std::cos (a);
  124. return { a, b, std::atan2 (s * m[8] - c * m[9], c * m[5] - s * m[4]) };
  125. }
  126. // sub_140215020, rows only
  127. glm::mat4 rotationOf (const Euler& e) {
  128. const float ca = std::cos (e.a), sa = std::sin (e.a);
  129. const float cb = std::cos (e.b), sb = std::sin (e.b);
  130. const float cc = std::cos (e.c), sc = std::sin (e.c);
  131. glm::mat4 out (0.0f);
  132. float* m = glm::value_ptr (out);
  133. m[0] = cb * ca;
  134. m[1] = cb * sa;
  135. m[2] = -sb;
  136. m[4] = sb * ca * sc - cc * sa;
  137. m[5] = sb * sa * sc + cc * ca;
  138. m[6] = sc * cb;
  139. m[8] = cc * ca * sb + sc * sa;
  140. m[9] = cc * sa * sb - sc * ca;
  141. m[10] = cc * cb;
  142. m[15] = 1.0f;
  143. return out;
  144. }
  145. // sub_1401E24B0
  146. float rowLength (const glm::vec4& r) { return std::sqrt ((r.w * r.w + r.z * r.z) + (r.y * r.y + r.x * r.x)); }
  147. glm::mat4 withPosition (glm::mat4 m, const glm::vec3& p) {
  148. m[3] = glm::vec4 (p, 1.0f);
  149. return m;
  150. }
  151. // sub_14026DCE0, false when parallel
  152. bool closestPoints (
  153. const glm::vec3& p1, const glm::vec3& d1, const glm::vec3& p2, const glm::vec3& d2, glm::vec3& onSecond
  154. ) {
  155. const float a = (d1.x * d1.x + d1.y * d1.y) + d1.z * d1.z;
  156. const float b = (d1.x * d2.x + d1.y * d2.y) + d1.z * d2.z;
  157. const float c = (d2.x * d2.x + d2.y * d2.y) + d2.z * d2.z;
  158. const float det = a * c - b * b;
  159. if (det == 0.0f) {
  160. return false;
  161. }
  162. const glm::vec3 r = p1 - p2;
  163. const float d = (d1.x * r.x + d1.y * r.y) + d1.z * r.z;
  164. const float e = (d2.y * r.y + d2.x * r.x) + d2.z * r.z;
  165. onSecond = p2 + d2 * ((e * a - d * b) / det);
  166. return true;
  167. }
  168. } // namespace
  169. glm::mat4 blendPuppetTransform (const glm::mat4& from, const glm::mat4& to, float weight) {
  170. constexpr float twoPi = 6.2831855f;
  171. constexpr float pi = 3.1415927f;
  172. Euler e = eulerOf (from);
  173. Euler t = eulerOf (to);
  174. for (float* angle : { &e.a, &e.b, &e.c, &t.a, &t.b, &t.c }) {
  175. *angle = std::fmod (*angle, twoPi);
  176. }
  177. // WE only subtracts pi
  178. if (t.c - e.c > pi) {
  179. t.c -= pi;
  180. }
  181. if (t.b - e.b > pi) {
  182. t.b -= pi;
  183. }
  184. if (t.a - e.a > pi) {
  185. t.a -= pi;
  186. }
  187. const float keep = 1.0f - weight;
  188. const glm::mat4 rotation = rotationOf (
  189. {
  190. e.a * keep + t.a * weight,
  191. e.b * keep + t.b * weight,
  192. e.c * keep + t.c * weight,
  193. }
  194. );
  195. glm::mat4 out (1.0f);
  196. for (int i = 0; i < 3; i++) {
  197. out[i] = rotation[i] * (rowLength (from[i]) * keep + rowLength (to[i]) * weight);
  198. }
  199. out[3] = glm::vec4 (position (from) * keep + position (to) * weight, 1.0f);
  200. return out;
  201. }
  202. void applyPuppetChainConstraints (
  203. const PuppetIKRig& rig, const PuppetIKChain& chain, const std::vector<float>& weights,
  204. std::vector<glm::mat4>& model, std::vector<glm::mat4>& extras
  205. ) {
  206. const auto validBone = [&model] (int bone) { return bone >= 0 && static_cast<size_t> (bone) < model.size (); };
  207. for (const uint32_t extra : chain.extras) {
  208. if (extra >= extras.size () || extra >= rig.extraRules.size () || extra >= rig.extraBones.size ()) {
  209. continue;
  210. }
  211. for (const auto& rule : rig.extraRules[extra]) {
  212. if (!validBone (static_cast<int> (rule.target))) {
  213. continue;
  214. }
  215. const float weight = rule.weight < weights.size () ? weights[rule.weight] : 0.0f;
  216. const glm::mat4& target = model[rule.target];
  217. glm::mat4& controller = extras[extra];
  218. if ((rule.flags & 0x10000) == 0 && (rule.flags & 2) == 0) {
  219. if (rule.flags & 1) {
  220. setPosition (controller, position (controller) * (1.0f - weight) + position (target) * weight);
  221. } else {
  222. controller = blendPuppetTransform (controller, target, weight);
  223. }
  224. continue;
  225. }
  226. // once per entry ending at the extra's bone
  227. const glm::vec3 axis = glm::vec3 (target[0]) * (1.0f / rowLength (target[0]));
  228. const glm::vec3 origin = position (target);
  229. for (const auto& link : chain.links) {
  230. for (const auto& entry : link.entries) {
  231. if (entry.endBone != rig.extraBones[extra] || entry.bones.empty ()
  232. || std::ranges::any_of (entry.bones, [&validBone] (int bone) { return !validBone (bone); })) {
  233. continue;
  234. }
  235. const glm::vec3 offset = position (controller) - origin;
  236. const float along = (offset.y * axis.y + offset.x * axis.x) + offset.z * axis.z;
  237. if (rule.flags & 0x10000) {
  238. // "chainalignaxis"
  239. const glm::vec3 fromRoot = origin - position (model[entry.bones[0]]);
  240. const float reach
  241. = std::sqrt ((fromRoot.x * fromRoot.x + fromRoot.y * fromRoot.y) + fromRoot.z * fromRoot.z);
  242. if (reach >= entry.length || along < 0.0f) {
  243. controller = blendPuppetTransform (controller, withPosition (controller, origin), weight);
  244. continue;
  245. }
  246. float distance = std::min (entry.length - reach, along);
  247. controller = blendPuppetTransform (
  248. controller, withPosition (target, origin + axis * distance), weight
  249. );
  250. float remaining = along;
  251. for (int i = static_cast<int> (entry.bones.size ()) - 2; i > 0; i--) {
  252. const float next = length (rig, entry.bones[i + 1]);
  253. remaining -= next;
  254. if (remaining < 0.0f) {
  255. break;
  256. }
  257. const float past = std::max (remaining - rule.start, 0.0f);
  258. const float ramp = past / rule.range >= 1.0f ? 1.0f : past / rule.range;
  259. if (ramp <= 0.0f) {
  260. break;
  261. }
  262. distance -= next;
  263. if (distance < 0.0f) {
  264. break;
  265. }
  266. glm::mat4& joint = model[entry.bones[i]];
  267. joint = blendPuppetTransform (
  268. joint, withPosition (target, origin + axis * distance), ramp * weight
  269. );
  270. }
  271. } else {
  272. // "axis"
  273. const glm::vec3 across = offset - axis * along;
  274. const glm::vec3 direction = across
  275. * (1.0f / std::sqrt ((across.x * across.x + across.y * across.y) + across.z * across.z));
  276. glm::vec3 onAxis;
  277. if (closestPoints (position (controller), direction, origin, axis, onAxis)) {
  278. controller = blendPuppetTransform (controller, withPosition (controller, onAxis), weight);
  279. }
  280. }
  281. }
  282. }
  283. }
  284. }
  285. }
  286. void limitPuppetJointDirection (
  287. const PuppetBoneIK& settings, const glm::vec3& joint, const glm::vec3& parent, glm::vec3& direction
  288. ) {
  289. const glm::vec3 fromParent = joint - parent;
  290. const float parentLength
  291. = std::sqrt ((fromParent.y * fromParent.y + fromParent.x * fromParent.x) + fromParent.z * fromParent.z);
  292. glm::mat4 frame (1.0f);
  293. const glm::mat3 rows
  294. = puppetQuatRows (puppetRotationArc (glm::vec3 (1.0f, 0.0f, 0.0f), fromParent * (1.0f / parentLength)));
  295. for (int i = 0; i < 3; i++) {
  296. frame[i] = glm::vec4 (rows[i], 0.0f);
  297. }
  298. const float flat = std::sqrt ((direction.x * direction.x + direction.y * direction.y) + 0.0f);
  299. const glm::vec3 local
  300. = glm::vec3 (glm::inverse (frame) * glm::vec4 (direction.x / flat, direction.y / flat, 0.0f / flat, 1.0f));
  301. const float angle = std::atan2 (local.y, local.x);
  302. float turn = settings.minAngle > angle ? -(angle - settings.minAngle) : 0.0f;
  303. if (angle > settings.maxAngle) {
  304. const float back = settings.maxAngle - angle;
  305. if (turn == 0.0f || std::fabs (turn) > std::fabs (back)) {
  306. turn = back;
  307. }
  308. }
  309. if (turn == 0.0f) {
  310. return;
  311. }
  312. const float c = std::cos (turn);
  313. const float s = std::sin (turn);
  314. const glm::vec3 turned (c * local.x - s * local.y, s * local.x + c * local.y, local.z);
  315. const glm::vec3 world = glm::vec3 (frame * glm::vec4 (turned, 1.0f)) * flat;
  316. direction.x = world.x;
  317. direction.y = world.y;
  318. }
  319. bool PuppetRopeEnvironment::windAt (const glm::vec3& position, glm::vec3& force) const {
  320. if (!this->wind) {
  321. return false;
  322. }
  323. // zero width: every simplex corner fails in WE (sub_140198910)
  324. float noise = 0.0f;
  325. if (this->width > 0.0f) {
  326. noise = std::max (0.0f, Utils::simplexNoise2D (this->clock, position.x / this->width * 10.0f));
  327. }
  328. force = noise * this->windDirection * this->windStrength;
  329. return true;
  330. }
  331. void stepPuppetRopeChain (
  332. const PuppetIKRig& rig, const PuppetIKChain& chain, const std::vector<PuppetBoneIK>& ik,
  333. std::vector<glm::mat4>& model, const std::vector<glm::mat4>& extras, const glm::mat4& world,
  334. std::vector<PuppetRopeJoint>& joints, const PuppetRopeEnvironment& environment, float dt
  335. ) {
  336. const auto valid = [&model, &joints] (int bone) {
  337. return bone >= 0 && static_cast<size_t> (bone) < model.size () && static_cast<size_t> (bone) < joints.size ();
  338. };
  339. const glm::mat4 inverse = glm::inverse (world);
  340. const float dt2 = dt * dt;
  341. for (auto link = chain.links.rbegin (); link != chain.links.rend (); ++link) {
  342. for (const auto& entry : link->entries) {
  343. if ((entry.flags & 4) == 0 || entry.bones.empty () || !valid (static_cast<int> (link->bone))
  344. || !valid (static_cast<int> (entry.endBone))
  345. || std::ranges::any_of (entry.bones, [&valid] (int bone) { return !valid (bone); })) {
  346. continue;
  347. }
  348. const PuppetBoneIK& end = endSettings (ik, entry.endBone);
  349. const glm::vec3 root = position (model[link->bone]);
  350. glm::vec3 target = position (model[entry.endBone]);
  351. if (entry.flags & 1) {
  352. if (const auto it = rig.targets.find (entry.endBone);
  353. it != rig.targets.end () && it->second < extras.size ()) {
  354. target = position (extras[it->second]);
  355. }
  356. }
  357. // without "ikse" the rope can't stretch
  358. if ((end.flags & PuppetBoneIK::SolveEnd) == 0) {
  359. const glm::vec3 offset = target - root;
  360. const float distance = std::sqrt ((offset.x * offset.x + offset.y * offset.y) + offset.z * offset.z);
  361. if (distance > entry.length) {
  362. target = offset / distance * entry.length + root;
  363. }
  364. }
  365. joints[link->bone].current = transformPoint (world, root);
  366. int count = static_cast<int> (entry.bones.size ());
  367. if ((end.flags & PuppetBoneIK::FollowParent) == 0) {
  368. setPosition (model[entry.endBone], target);
  369. joints[entry.endBone].current = transformPoint (world, target);
  370. count--;
  371. }
  372. if (!joints[link->bone].started) {
  373. joints[link->bone].started = true;
  374. for (int i = 1; i < count; i++) {
  375. auto& joint = joints[entry.bones[i]];
  376. joint.current = transformPoint (world, position (model[entry.bones[i]]));
  377. joint.previous = joint.current;
  378. }
  379. }
  380. for (int i = 1; i < count; i++) {
  381. const int bone = entry.bones[i];
  382. auto& joint = joints[bone];
  383. const glm::vec3 current = joint.current;
  384. const glm::vec3 back = joint.previous - current;
  385. glm::vec3 next = (current + current) - joint.previous;
  386. // "tf" damping
  387. if (dt2 > 0.00000011920929f && end.friction > 0.0099999998f
  388. && (back.x * back.x + back.y * back.y) + back.z * back.z > 0.000099999997f) {
  389. next += back * dt2 * (1.0f / dt2) * end.friction;
  390. }
  391. glm::vec3 force (0.0f);
  392. if (end.flags & PuppetBoneIK::Gravity) {
  393. force = end.mass * environment.gravity;
  394. }
  395. if (glm::vec3 wind; environment.windAt (next, wind)) {
  396. force += wind;
  397. }
  398. next += force * dt2;
  399. joint.previous = current;
  400. joint.current = next;
  401. setPosition (model[bone], transformPoint (inverse, next));
  402. }
  403. }
  404. }
  405. }
  406. PuppetBoneIK PuppetBoneIK::parse (const std::string& text) {
  407. PuppetBoneIK result;
  408. const JSON json = JSON::parse (text, nullptr, false);
  409. if (!json.is_object ()) {
  410. return result;
  411. }
  412. const auto isTrue = [&json] (const char* key) {
  413. const auto it = json.find (key);
  414. return it != json.end () && it->is_boolean () && it->get<bool> ();
  415. };
  416. // only "ik" bones, except the "ikce" flag
  417. if (isTrue ("ikce")) {
  418. result.flags |= Constrained;
  419. }
  420. if (!isTrue ("ik")) {
  421. // no limits for simulated bones
  422. if ((result.flags & Constrained) && !((isTrue ("se") || isTrue ("re")) && (isTrue ("r") || isTrue ("t")))) {
  423. if (const auto it = json.find ("ikrminl"); it != json.end () && it->is_number ()) {
  424. result.minAngle = it->get<float> ();
  425. }
  426. if (const auto it = json.find ("ikrmaxl"); it != json.end () && it->is_number ()) {
  427. result.maxAngle = it->get<float> ();
  428. }
  429. }
  430. return result;
  431. }
  432. result.flags |= Enabled;
  433. result.flags |= isTrue ("ge") ? Gravity : 0;
  434. if (const auto it = json.find ("m"); it != json.end () && it->is_number ()) {
  435. result.mass = it->get<float> ();
  436. }
  437. if (const auto it = json.find ("tf"); it != json.end () && it->is_number ()) {
  438. result.friction = it->get<float> ();
  439. }
  440. // non-simulated bones use (tf / 100)^2
  441. if (!((isTrue ("se") || isTrue ("re")) && (isTrue ("r") || isTrue ("t")))) {
  442. const float scaled = (result.friction / 100.0f) * (result.friction / 100.0f);
  443. result.friction = scaled >= 0.0f ? std::min (scaled, 1.0f) : 0.0f;
  444. }
  445. if (const auto it = json.find ("ikd"); it != json.end () && it->is_number ()) {
  446. result.depth = std::max (it->get<int> (), 1);
  447. }
  448. result.flags |= isTrue ("ikg") ? Grounded : 0;
  449. if (isTrue ("ikr")) {
  450. result.flags |= RotateToTarget;
  451. if (const auto it = json.find ("ikrd"); it != json.end () && it->is_number ()) {
  452. result.rotateDistance = std::max (it->get<float> (), 1.0f);
  453. }
  454. }
  455. result.flags |= isTrue ("ikse") ? SolveEnd : 0;
  456. result.flags |= isTrue ("ikfe") ? FollowParent : 0;
  457. return result;
  458. }
  459. void solvePuppetIKChain (
  460. const PuppetIKRig& rig, const PuppetIKChain& chain, const std::vector<int>& parents,
  461. const std::vector<PuppetBoneIK>& ik, std::vector<glm::mat4>& model, const std::vector<glm::mat4>& extras,
  462. const std::vector<glm::mat4>& bindModel, const glm::mat4& world, std::vector<PuppetRopeJoint>& joints
  463. ) {
  464. const auto valid = [&model, &joints] (int bone) {
  465. return bone >= 0 && static_cast<size_t> (bone) < model.size () && static_cast<size_t> (bone) < joints.size ();
  466. };
  467. const auto extraOf = [&extras] (const std::unordered_map<uint32_t, uint32_t>& map, uint32_t bone) {
  468. const auto it = map.find (bone);
  469. return it != map.end () && it->second < extras.size () ? &extras[it->second] : nullptr;
  470. };
  471. for (const auto& link : chain.links) {
  472. for (const auto& entry : link.entries) {
  473. if (!valid (static_cast<int> (link.bone)) || !valid (static_cast<int> (entry.endBone))
  474. || std::ranges::any_of (entry.bones, [&valid] (int bone) { return !valid (bone); })) {
  475. return;
  476. }
  477. }
  478. }
  479. if (!valid (static_cast<int> (chain.root))) {
  480. return;
  481. }
  482. const glm::vec3 root = position (model[chain.root]);
  483. const glm::mat4 inverse = glm::inverse (world);
  484. for (int iteration = 0; iteration < 10; iteration++) {
  485. // forward pass
  486. for (auto link = chain.links.rbegin (); link != chain.links.rend (); ++link) {
  487. glm::vec3 sum (0.0f);
  488. float count = 0.0f;
  489. for (auto entry = link->entries.rbegin (); entry != link->entries.rend (); ++entry) {
  490. if (entry->flags & 4) {
  491. constrainRope (rig, *entry, endSettings (ik, entry->endBone), world, inverse, joints, false);
  492. continue;
  493. }
  494. const glm::vec3 start = position (model[link->bone]);
  495. const glm::mat4* targetExtra = (entry->flags & 1) ? extraOf (rig.targets, entry->endBone) : nullptr;
  496. glm::vec3 target = targetExtra != nullptr ? position (*targetExtra) : position (model[entry->endBone]);
  497. const glm::vec3 offset = target - start;
  498. float distance = std::sqrt (glm::dot (offset, offset));
  499. const glm::vec3 direction = offset / distance;
  500. if (entry->minReach > 0.0f && entry->minReach > distance) {
  501. target += (entry->minReach - distance) * direction;
  502. distance = entry->minReach;
  503. }
  504. glm::vec3 pole (0.0f);
  505. if (const auto* poleExtra = extraOf (rig.poles, entry->endBone); poleExtra != nullptr) {
  506. const glm::vec3 toPole = position (*poleExtra) - target;
  507. pole = toPole - direction * glm::dot (toPole, direction);
  508. }
  509. setPosition (model[entry->endBone], target);
  510. const int last = static_cast<int> (entry->bones.size ()) - 1;
  511. if (distance < entry->length || (entry->flags & 2)) {
  512. // bend in the plane of the target and the pole
  513. const float poleSquared = glm::dot (pole, pole);
  514. const glm::vec3 normal (
  515. direction.y * pole.z - direction.z * pole.y, direction.z * pole.x - direction.x * pole.z,
  516. direction.x * pole.y - direction.y * pole.x
  517. );
  518. const float normalLength = std::sqrt (glm::dot (normal, normal));
  519. float walked = 0.0f;
  520. for (int i = last; i > 0; i--) {
  521. const int bone = entry->bones[i];
  522. const int joint = entry->bones[i - 1];
  523. const glm::vec3 base = position (model[bone]);
  524. glm::vec3 toJoint = position (model[joint]) - base;
  525. if (i > 1 && static_cast<size_t> (joint) < ik.size ()
  526. && (ik[joint].flags & PuppetBoneIK::Constrained) && valid (parents[joint])) {
  527. const float squared
  528. = (toJoint.x * toJoint.x + toJoint.y * toJoint.y) + toJoint.z * toJoint.z;
  529. glm::vec3 forward = -(toJoint * (1.0f / std::sqrt (squared)));
  530. limitPuppetJointDirection (
  531. ik[joint], position (model[joint]), position (model[parents[joint]]), forward
  532. );
  533. toJoint = -forward;
  534. }
  535. if (i == last || entry->length * 0.5f > walked + length (rig, bone)) {
  536. if (poleSquared > 0.0099999998f) {
  537. const glm::vec3 axis = normal * (1.0f / normalLength);
  538. toJoint -= glm::dot (toJoint, axis) * axis;
  539. }
  540. const float side = glm::dot (toJoint, pole);
  541. if (side < 0.0f) {
  542. toJoint -= (pole + pole) * side;
  543. }
  544. }
  545. const float jointLength = std::sqrt (glm::dot (toJoint, toJoint));
  546. setPosition (model[joint], toJoint * (1.0f / jointLength) * length (rig, bone) + base);
  547. walked += length (rig, bone);
  548. }
  549. } else {
  550. // out of reach
  551. for (int i = last; i > 0; i--) {
  552. const int bone = entry->bones[i];
  553. setPosition (
  554. model[entry->bones[i - 1]], position (model[bone]) - length (rig, bone) * direction
  555. );
  556. }
  557. }
  558. count += 1.0f;
  559. sum += position (model[link->bone]);
  560. }
  561. if (count > 0.0f) {
  562. setPosition (model[link->bone], sum / count);
  563. }
  564. }
  565. // first pass: "chainalignaxis" mirrors joints on the wrong side of the axis plane, 32 steps max
  566. if (iteration == 0) {
  567. for (const uint32_t extra : chain.extras) {
  568. if (extra >= rig.extraRules.size () || extra >= rig.extraBones.size ()) {
  569. continue;
  570. }
  571. for (const auto& rule : rig.extraRules[extra]) {
  572. if ((rule.flags & 0x10000) == 0 || !valid (static_cast<int> (rule.target))) {
  573. continue;
  574. }
  575. const glm::mat4& target = model[rule.target];
  576. const float inverse = 1.0f
  577. / std::sqrt ((target[0].w * target[0].w + target[0].z * target[0].z)
  578. + (target[0].y * target[0].y + target[0].x * target[0].x));
  579. const glm::vec3 axis = glm::vec3 (target[0]) * inverse;
  580. for (const auto& link : chain.links) {
  581. for (const auto& entry : link.entries) {
  582. const int n = static_cast<int> (entry.bones.size ());
  583. if (entry.endBone != rig.extraBones[extra] || n <= 2) {
  584. continue;
  585. }
  586. const glm::vec3 fromRoot = position (target) - position (model[entry.bones[0]]);
  587. const float full = std::sqrt (
  588. (fromRoot.x * fromRoot.x + fromRoot.y * fromRoot.y) + fromRoot.z * fromRoot.z
  589. );
  590. float distance = full;
  591. for (int k = 1, budget = 32; budget > 0; budget--) {
  592. distance -= length (rig, entry.bones[k]);
  593. if (distance < 0.0f) {
  594. break;
  595. }
  596. const glm::vec3 previous = position (model[entry.bones[k - 1]]);
  597. const glm::vec3 span = position (model[entry.bones[k + 1]]) - previous;
  598. const glm::vec3 side (
  599. axis.z * span.y - axis.y * span.z, axis.x * span.z - axis.z * span.x,
  600. axis.y * span.x - axis.x * span.y
  601. );
  602. const glm::vec3 normal (
  603. side.y * span.z - side.z * span.y, side.z * span.x - side.x * span.z,
  604. side.x * span.y - side.y * span.x
  605. );
  606. const float squared = normal.z * normal.z + (normal.x * normal.x + normal.y * normal.y);
  607. if (squared >= 0.0099999998f) {
  608. const glm::vec3 unit = normal * (1.0f / std::sqrt (squared));
  609. const glm::vec3 point = position (model[entry.bones[k]]);
  610. const glm::vec3 offset = point - previous;
  611. const float depth = (unit.x * offset.x + unit.y * offset.y) + offset.z * unit.z;
  612. if (depth > 0.00000011920929f) {
  613. setPosition (model[entry.bones[k]], point - (unit * depth + unit * depth));
  614. distance = full;
  615. k = 1;
  616. }
  617. }
  618. if (k++ + 2 >= n) {
  619. break;
  620. }
  621. }
  622. }
  623. }
  624. }
  625. }
  626. }
  627. // backward pass, done within sqrt (0.1)
  628. bool reached = true;
  629. for (const auto& link : chain.links) {
  630. for (const auto& entry : link.entries) {
  631. if (entry.flags & 4) {
  632. constrainRope (rig, entry, endSettings (ik, entry.endBone), world, inverse, joints, true);
  633. continue;
  634. }
  635. const bool fixedRoot = link.bone == chain.root && parents[chain.root] != -1;
  636. setPosition (model[link.bone], fixedRoot ? root : position (model[link.bone]));
  637. for (size_t i = 0; i + 1 < entry.bones.size (); i++) {
  638. const glm::vec3 base = position (model[entry.bones[i]]);
  639. const glm::vec3 toNext = position (model[entry.bones[i + 1]]) - base;
  640. glm::vec3 direction = toNext * (1.0f / std::sqrt (glm::dot (toNext, toNext)));
  641. const int bone = entry.bones[i];
  642. // sub_14026DF30
  643. if (i > 0 && static_cast<size_t> (bone) < ik.size () && (ik[bone].flags & PuppetBoneIK::Constrained)
  644. && valid (parents[bone])) {
  645. limitPuppetJointDirection (ik[bone], base, position (model[parents[bone]]), direction);
  646. }
  647. setPosition (model[entry.bones[i + 1]], length (rig, entry.bones[i + 1]) * direction + base);
  648. }
  649. if (entry.flags & 1) {
  650. if (const auto* target = extraOf (rig.targets, entry.endBone); target != nullptr) {
  651. const glm::vec3 miss = position (model[entry.endBone]) - position (*target);
  652. if (glm::dot (miss, miss) > 0.1f) {
  653. reached = false;
  654. }
  655. }
  656. }
  657. }
  658. }
  659. if (reached) {
  660. break;
  661. }
  662. }
  663. // rotate joints from bind pose onto the solved directions
  664. for (const auto& link : chain.links) {
  665. const bool shared = link.entries.size () != 1;
  666. for (const auto& entry : link.entries) {
  667. for (size_t i = shared ? 1 : 0; i + 1 < entry.bones.size (); i++) {
  668. const int bone = entry.bones[i];
  669. const int child = entry.bones[i + 1];
  670. const glm::vec3* rest = childDirection (rig, bone, child);
  671. if (rest == nullptr) {
  672. continue;
  673. }
  674. const glm::vec3 toChild = position (model[child]) - position (model[bone]);
  675. const glm::vec3 direction = toChild * (1.0f / std::sqrt (glm::dot (toChild, toChild)));
  676. rotateRows (model[bone], arc (*rest, direction), bindModel[bone]);
  677. }
  678. if ((entry.flags & 1) == 0) {
  679. continue;
  680. }
  681. const uint32_t end = entry.endBone;
  682. const uint32_t endFlags = end < ik.size () ? ik[end].flags : 0;
  683. if (endFlags & PuppetBoneIK::FollowParent) {
  684. if (entry.bones.size () > 2) {
  685. const glm::mat4& before = model[entry.bones[entry.bones.size () - 2]];
  686. model[end][0] = before[0];
  687. model[end][1] = before[1];
  688. model[end][2] = before[2];
  689. }
  690. continue;
  691. }
  692. const glm::mat4* target = extraOf (rig.targets, end);
  693. if (target == nullptr) {
  694. continue;
  695. }
  696. glm::mat4 rows (1.0f);
  697. rows[0] = fastNormalize ((*target)[0]);
  698. rows[1] = fastNormalize ((*target)[1]);
  699. rows[2] = fastNormalize ((*target)[2]);
  700. // "ikr": turn short ends towards the target
  701. if (endFlags & PuppetBoneIK::RotateToTarget) {
  702. const glm::vec3 miss = position (*target) - position (model[end]);
  703. const float squared = glm::dot (miss, miss);
  704. if (squared > 1.0f) {
  705. const float distance = std::sqrt (squared);
  706. const float t = std::min ((distance - 1.0f) / ik[end].rotateDistance, 1.0f);
  707. const glm::vec4 towards = puppetRotationArc (glm::vec3 (1.0f, 0.0f, 0.0f), miss / distance);
  708. const glm::mat3 turned = puppetQuatRows (puppetSlerp (quatFromRows (rows), towards, t));
  709. rows[0] = glm::vec4 (turned[0], 0.0f);
  710. rows[1] = glm::vec4 (turned[1], 0.0f);
  711. rows[2] = glm::vec4 (turned[2], 0.0f);
  712. }
  713. }
  714. model[end][0] = rows[0];
  715. model[end][1] = rows[1];
  716. model[end][2] = rows[2];
  717. }
  718. // average the arcs of several entries
  719. if (!shared || link.entries.empty ()) {
  720. continue;
  721. }
  722. glm::vec4 average (1.0f, 0.0f, 0.0f, 0.0f);
  723. const float weight = 1.0f / static_cast<float> (link.entries.size ());
  724. for (const auto& entry : link.entries) {
  725. if (entry.bones.size () < 2) {
  726. continue;
  727. }
  728. const glm::vec3* rest = childDirection (rig, static_cast<int> (link.bone), entry.bones[1]);
  729. if (rest == nullptr) {
  730. continue;
  731. }
  732. const glm::vec3 toChild = position (model[entry.bones[1]]) - position (model[link.bone]);
  733. const glm::vec3 direction = toChild * (1.0f / std::sqrt (glm::dot (toChild, toChild)));
  734. average = puppetSlerp (average, puppetRotationArc (*rest, direction), weight);
  735. }
  736. rotateRows (model[link.bone], average, bindModel[link.bone]);
  737. }
  738. }
  739. } // namespace WallpaperEngine::Render::Objects