PuppetRig.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079
  1. #include "PuppetRig.h"
  2. #include <algorithm>
  3. #include <array>
  4. #include <cmath>
  5. #include <cstring>
  6. #include <limits>
  7. #include <set>
  8. #include <stdexcept>
  9. #include <string_view>
  10. #include <strings.h>
  11. #include <utility>
  12. #include <glm/gtc/matrix_transform.hpp>
  13. #include "WallpaperEngine/Data/Model/Project.h"
  14. #include "WallpaperEngine/Data/Parsers/ObjectParser.h"
  15. #include "WallpaperEngine/Data/Utils/BinaryReader.h"
  16. #include "WallpaperEngine/Data/Utils/MemoryStream.h"
  17. #include "WallpaperEngine/Logging/Log.h"
  18. #include "WallpaperEngine/Render/Objects/PuppetMeshFile.h"
  19. using namespace WallpaperEngine;
  20. using namespace WallpaperEngine::Render::Objects;
  21. using namespace WallpaperEngine::Data::Model;
  22. using namespace WallpaperEngine::Data::Parsers;
  23. using namespace WallpaperEngine::Data::Utils;
  24. extern float g_Time;
  25. extern float g_TimeLast;
  26. namespace {
  27. constexpr uint32_t PuppetClockMirror = 1;
  28. constexpr uint32_t PuppetClockSingle = 2;
  29. constexpr uint32_t PuppetClockFrameSet = 0x2000000;
  30. constexpr uint32_t PuppetClockPaused = 0x20000000;
  31. constexpr uint32_t PuppetClockStopped = 0x40000000;
  32. constexpr uint32_t PuppetClockBackwards = 0x80000000;
  33. // WE's timeline step (2.8.42 sub_1401A9F60, fmodf results taken from the asm): loops wrap, mirrors turn around at
  34. // either end, single clips stop on their end
  35. void stepPuppetClock (
  36. PuppetActiveAnimation& clock, float duration, float delta, std::vector<std::string>* fired = nullptr
  37. ) {
  38. if ((clock.flags & (PuppetClockPaused | PuppetClockStopped)) != 0
  39. || ((clock.flags & PuppetClockSingle) != 0 && clock.time >= duration) || duration <= 0.0f) {
  40. return;
  41. }
  42. if ((clock.flags & PuppetClockBackwards) != 0) {
  43. delta = -delta;
  44. }
  45. const float time = clock.time + delta;
  46. const auto fire = [&clock, fired] (const auto& passed) {
  47. if (fired == nullptr) {
  48. return;
  49. }
  50. for (const auto& event : clock.clip.events) {
  51. if (passed (event.time)) {
  52. fired->push_back (event.payload);
  53. }
  54. }
  55. };
  56. // events passed since the last time, including across a loop wrap (0x1401aa0b9)
  57. if (delta > 0.0f) {
  58. fire ([&clock, time] (float at) { return at >= clock.time && time > at; });
  59. } else {
  60. fire ([&clock, time] (float at) { return at > time && clock.time >= at; });
  61. }
  62. clock.time = time;
  63. if ((clock.flags & PuppetClockSingle) != 0) {
  64. if (time >= duration) {
  65. clock.flags |= PuppetClockStopped;
  66. clock.time = duration;
  67. }
  68. return;
  69. }
  70. if ((clock.flags & PuppetClockMirror) == 0) {
  71. if (time < 0.0f) {
  72. clock.time = std::fmod (time + duration, duration);
  73. if (clock.time >= 0.0f) {
  74. fire ([&clock, duration] (float at) { return at > clock.time && duration >= at; });
  75. }
  76. }
  77. if (clock.time >= duration) {
  78. clock.time = std::fmod (clock.time, duration);
  79. if (duration > clock.time) {
  80. fire ([&clock] (float at) { return at >= 0.0f && clock.time > at; });
  81. }
  82. }
  83. return;
  84. }
  85. if ((clock.flags & PuppetClockBackwards) != 0) {
  86. if (time <= 0.0f) {
  87. clock.time = -std::fmod (time, duration);
  88. clock.flags &= ~PuppetClockBackwards;
  89. }
  90. return;
  91. }
  92. if (time >= duration) {
  93. clock.flags |= PuppetClockBackwards;
  94. clock.time = duration - std::fmod (time, duration);
  95. }
  96. }
  97. // sub_14026C8B0: blend, faded in over the first min(duration / 2, blendtime) seconds and out over the last ones. A
  98. // clip that doesn't stop on its end drops the fade in once it is done
  99. float puppetLayerWeight (PuppetActiveAnimation& layer, float duration) {
  100. const float blendTime = layer.layer->blendTime;
  101. const float ramp = std::min (duration * 0.5f, blendTime);
  102. const bool canFade = std::min (duration, blendTime) > std::numeric_limits<float>::epsilon ();
  103. float weight = layer.layer->blend->value->getFloat ();
  104. if (layer.blendIn) {
  105. const float fade = canFade ? std::min (layer.time / ramp, 1.0f) : 1.0f;
  106. weight *= fade;
  107. if ((layer.flags & PuppetClockSingle) == 0 && fade >= 1.0f) {
  108. layer.blendIn = false;
  109. }
  110. }
  111. if (layer.blendOut && canFade) {
  112. weight *= std::min ((duration - layer.time) / ramp, 1.0f);
  113. }
  114. return weight;
  115. }
  116. struct PuppetBoneSet {
  117. std::vector<PuppetBone> bones;
  118. // the section after MDLS's second bone array: MDLA, or MDAT with attachment points; the caller checks which
  119. size_t nextSectionOffset = 0;
  120. // MDLS v2+ records after the bones, every MDLA clip carries one track per entry of each
  121. uint32_t extraCount = 0;
  122. uint32_t constraintCount = 0;
  123. std::vector<int> drawOrder;
  124. std::vector<int> hitOrder;
  125. std::vector<PuppetExtra> extras;
  126. PuppetIKRig ik;
  127. };
  128. void parsePuppetCapsules (const BinaryReader& reader, PuppetBoneSet& result, size_t nextSectionOffset);
  129. // MDLS bones (bind pose, parents, physics JSON) and the record counts sizing the MDLA tracks; inverse binds come from
  130. // the bind pose, the file's copy is skipped
  131. PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
  132. reader.base ().seekg (static_cast<std::streamoff> (mdlsOffset), std::ios::beg);
  133. char header[9];
  134. reader.next (header, sizeof (header));
  135. const uint32_t nextSectionOffset = reader.nextUInt32 ();
  136. const uint32_t boneCount = reader.nextUInt32 ();
  137. // only a garbage read gives this many
  138. constexpr uint32_t maxPlausibleBoneCount = 512;
  139. if (boneCount > maxPlausibleBoneCount) {
  140. sLog.error ("Puppet bone count (", boneCount, ") looks implausible, skipping puppet mesh skinning");
  141. return {};
  142. }
  143. PuppetBoneSet result;
  144. result.nextSectionOffset = nextSectionOffset;
  145. result.bones.reserve (boneCount);
  146. for (uint32_t i = 0; i < boneCount; i++) {
  147. // records start with a null-terminated name, empty for most rigs
  148. std::string name = reader.nextNullTerminatedString ();
  149. const uint32_t type = reader.nextUInt32 ();
  150. const int parent = reader.nextInt ();
  151. const uint32_t matrixBytes = reader.nextUInt32 ();
  152. glm::mat4 bindLocal (1.0f);
  153. if (matrixBytes == sizeof (float) * 16) {
  154. float m[16];
  155. for (float& value : m) {
  156. value = reader.nextFloat ();
  157. }
  158. // row-vector row-major in the file, glm's column-major constructor transposes it into the column-vector
  159. // matrix
  160. bindLocal = glm::mat4 (
  161. m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]
  162. );
  163. } else {
  164. // a bad decode, don't seek by an untrusted amount
  165. constexpr uint32_t maxPlausibleMatrixBytes = 4096;
  166. if (matrixBytes > maxPlausibleMatrixBytes) {
  167. sLog.error (
  168. "Puppet bone ", i, " has an implausible matrix byte count (", matrixBytes, "), stopping here (",
  169. result.bones.size (), " bone(s) kept)"
  170. );
  171. break;
  172. }
  173. reader.base ().seekg (static_cast<std::streamoff> (matrixBytes), std::ios::cur);
  174. }
  175. // trailing per-bone string, jiggle/physics JSON for some rigs
  176. const std::string physics = reader.nextNullTerminatedString ();
  177. result.bones.push_back (
  178. PuppetBone { .name = std::move (name),
  179. .parent = parent,
  180. .bindLocal = bindLocal,
  181. .restLocal = bindLocal,
  182. .physics = PuppetBonePhysics::parse (physics),
  183. .type = type,
  184. .ik = PuppetBoneIK::parse (physics) }
  185. );
  186. }
  187. // the reader returns garbage past the end instead of failing
  188. if (!reader.base ().good ()) {
  189. throw std::runtime_error ("the skeleton is cut short");
  190. }
  191. // the rest of MDLS as 2.8.42 reads it (sub_140261880), only the two counts matter here
  192. const int version = std::atoi (header + 4);
  193. if (version < 2 || result.bones.size () != boneCount) {
  194. return result;
  195. }
  196. uint16_t extraCount = 0;
  197. reader.next (reinterpret_cast<char*> (&extraCount), sizeof (extraCount));
  198. // name, bone, type (float, 0 target 1 pole), model space matrix
  199. const auto readMatrix = [&reader] () {
  200. float m[16];
  201. for (float& value : m) {
  202. value = reader.nextFloat ();
  203. }
  204. return glm::mat4 (
  205. m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]
  206. );
  207. };
  208. for (uint16_t i = 0; i < extraCount; i++) {
  209. (void)reader.nextNullTerminatedString ();
  210. PuppetExtra extra;
  211. extra.bone = reader.nextUInt32 ();
  212. extra.type = reader.nextUInt32 ();
  213. extra.restLocal = readMatrix ();
  214. result.extras.push_back (extra);
  215. }
  216. // a flag byte and then a matrix per bone and per extra record: the rest pose. The vertices and the inverse bind
  217. // matrices stay in the bone records' space (sub_1401FBAE0), the pose starts from these when they are there
  218. // (sub_1401FDF90), so a puppet whose parts sit apart in its texture's layout (3227072870) gets put together
  219. if (reader.next () != 0) {
  220. for (auto& bone : result.bones) {
  221. float m[16];
  222. for (float& value : m) {
  223. value = reader.nextFloat ();
  224. }
  225. bone.restLocal = glm::mat4 (
  226. m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]
  227. );
  228. }
  229. for (auto& extra : result.extras) {
  230. extra.restLocal = readMatrix ();
  231. }
  232. }
  233. const uint32_t constraintCount = reader.nextUInt32 ();
  234. result.ik.extraRules.resize (result.extras.size ());
  235. // blend rules go on an IK joint's target extra, otherwise on the bone
  236. for (uint32_t i = 0; i < constraintCount && reader.base ().good (); i++) {
  237. const uint32_t bone = reader.nextUInt32 ();
  238. PuppetConstraintRule rule;
  239. rule.weight = reader.nextUInt32 ();
  240. rule.target = reader.nextUInt32 ();
  241. rule.flags = version >= 4 ? reader.nextUInt32 () : 0;
  242. if (rule.flags & 2) {
  243. rule.start = reader.nextFloat ();
  244. rule.range = std::max (reader.nextFloat (), 0.00000011920929f);
  245. }
  246. if (bone >= result.bones.size ()) {
  247. continue;
  248. }
  249. if (result.bones[bone].type & 2) {
  250. for (size_t extra = 0; extra < result.extras.size (); extra++) {
  251. if (result.extras[extra].bone == bone && result.extras[extra].type == 0) {
  252. result.ik.extraRules[extra].push_back (rule);
  253. break;
  254. }
  255. }
  256. } else {
  257. result.bones[bone].rules.push_back (rule);
  258. }
  259. }
  260. if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) > nextSectionOffset) {
  261. reader.base ().clear ();
  262. sLog.error ("Puppet MDLS records after the bones don't fit the section, animation tracks may not line up");
  263. return result;
  264. }
  265. result.extraCount = extraCount;
  266. result.constraintCount = constraintCount;
  267. // sub_140261880 goes on with two more blocks before the per bone collision capsules
  268. const auto nextUInt16 = [&reader] () {
  269. uint16_t value = 0;
  270. reader.next (reinterpret_cast<char*> (&value), sizeof (value));
  271. return value;
  272. };
  273. // bone lengths and child rest directions (P+224, P+248)
  274. auto& ik = result.ik;
  275. const uint16_t groups = nextUInt16 ();
  276. ik.lengths.resize (groups);
  277. for (float& length : ik.lengths) {
  278. length = reader.nextFloat ();
  279. }
  280. ik.childDirections.resize (groups);
  281. for (uint16_t i = 0; i < groups && reader.base ().good (); i++) {
  282. const uint16_t children = nextUInt16 ();
  283. for (uint16_t j = 0; j < children && reader.base ().good (); j++) {
  284. const uint32_t child = reader.nextUInt32 ();
  285. const float x = reader.nextFloat ();
  286. const float y = reader.nextFloat ();
  287. const float z = reader.nextFloat ();
  288. ik.childDirections[i][child] = glm::vec3 (x, y, z);
  289. }
  290. }
  291. // IK chains (P+272)
  292. const uint16_t chains = nextUInt16 ();
  293. for (uint16_t i = 0; i < chains && reader.base ().good (); i++) {
  294. PuppetIKChain chain;
  295. chain.root = reader.nextUInt32 ();
  296. chain.extras.resize (reader.nextUInt32 ());
  297. for (uint32_t& extra : chain.extras) {
  298. extra = reader.nextUInt32 ();
  299. }
  300. const uint16_t links = nextUInt16 ();
  301. for (uint16_t j = 0; j < links && reader.base ().good (); j++) {
  302. PuppetIKLink link;
  303. link.bone = reader.nextUInt32 ();
  304. const uint16_t entries = nextUInt16 ();
  305. for (uint16_t k = 0; k < entries && reader.base ().good (); k++) {
  306. PuppetIKEntry entry;
  307. entry.endBone = reader.nextUInt32 ();
  308. entry.flags = reader.nextUInt32 ();
  309. entry.length = reader.nextFloat ();
  310. entry.minReach = reader.nextFloat ();
  311. entry.bones.resize (nextUInt16 ());
  312. for (int& bone : entry.bones) {
  313. bone = reader.nextInt ();
  314. }
  315. link.entries.push_back (std::move (entry));
  316. }
  317. chain.links.push_back (std::move (link));
  318. }
  319. ik.chains.push_back (std::move (chain));
  320. }
  321. // WE fastfails on bad bone indices, drop the chain instead
  322. const auto boneIndex
  323. = [&result] (int bone) { return bone >= 0 && static_cast<size_t> (bone) < result.bones.size (); };
  324. std::erase_if (ik.chains, [&boneIndex] (const PuppetIKChain& chain) {
  325. return !boneIndex (static_cast<int> (chain.root))
  326. || std::ranges::any_of (chain.links, [&boneIndex] (const PuppetIKLink& link) {
  327. return !boneIndex (static_cast<int> (link.bone))
  328. || std::ranges::any_of (link.entries, [&boneIndex] (const PuppetIKEntry& entry) {
  329. return !boneIndex (static_cast<int> (entry.endBone))
  330. || !std::ranges::all_of (entry.bones, boneIndex);
  331. });
  332. });
  333. });
  334. if (reader.base ().good ()) {
  335. for (size_t i = 0; i < ik.chains.size (); i++) {
  336. result.bones[ik.chains[i].root].chain = static_cast<int> (i);
  337. }
  338. for (uint32_t i = 0; i < result.extras.size (); i++) {
  339. ik.extraBones.push_back (result.extras[i].bone);
  340. auto& map = result.extras[i].type == 0 ? ik.targets : ik.poles;
  341. if (result.extras[i].type <= 1) {
  342. map[result.extras[i].bone] = i;
  343. }
  344. }
  345. } else {
  346. ik = {};
  347. }
  348. if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) >= nextSectionOffset) {
  349. reader.base ().clear ();
  350. return result;
  351. }
  352. if (reader.next () != 0) {
  353. parsePuppetCapsules (reader, result, nextSectionOffset);
  354. }
  355. // flag byte + cursor box test order (sub_1401FD690), MDLS v3+ another flag byte + bone draw order
  356. const auto atEnd = [&reader, nextSectionOffset] () {
  357. return !reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) >= nextSectionOffset;
  358. };
  359. if (!atEnd () && reader.next () != 0) {
  360. result.hitOrder.resize (result.bones.size ());
  361. for (int& bone : result.hitOrder) {
  362. bone = static_cast<int> (std::min<uint32_t> (reader.nextUInt32 (), result.bones.size () - 1));
  363. }
  364. }
  365. if (version >= 3 && !atEnd () && reader.next () != 0) {
  366. result.drawOrder.resize (result.bones.size ());
  367. for (int& order : result.drawOrder) {
  368. order = reader.nextInt ();
  369. }
  370. }
  371. if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) > nextSectionOffset) {
  372. reader.base ().clear ();
  373. result.drawOrder.clear ();
  374. result.hitOrder.clear ();
  375. }
  376. return result;
  377. }
  378. void parsePuppetCapsules (const BinaryReader& reader, PuppetBoneSet& result, size_t nextSectionOffset) {
  379. // a vec3 of extents and the capsule's frame in bone space (row-vector, row-major like the bind matrices)
  380. for (auto& bone : result.bones) {
  381. for (int axis = 0; axis < 3; axis++) {
  382. bone.capsuleExtents[axis] = reader.nextFloat ();
  383. }
  384. float m[16];
  385. for (float& value : m) {
  386. value = reader.nextFloat ();
  387. }
  388. bone.capsule = glm::mat4 (
  389. m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]
  390. );
  391. bone.hasCapsule = true;
  392. }
  393. if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) > nextSectionOffset) {
  394. reader.base ().clear ();
  395. sLog.error ("Puppet MDLS collision capsules don't fit the section, ignoring them");
  396. for (auto& bone : result.bones) {
  397. bone.hasCapsule = false;
  398. }
  399. }
  400. }
  401. // parents don't necessarily come before children (puppet eyes/eyebrows)
  402. void resolveBoneWorldTransform (
  403. size_t index, const std::vector<int>& parents, const std::vector<glm::mat4>& locals, std::vector<glm::mat4>& world,
  404. std::vector<bool>& resolved, std::vector<bool>& visiting
  405. ) {
  406. if (resolved[index]) {
  407. return;
  408. }
  409. const int parent = parents[index];
  410. // missing, out-of-range or cyclic parents count as roots
  411. if (parent < 0 || static_cast<size_t> (parent) >= parents.size () || visiting[index]) {
  412. world[index] = locals[index];
  413. } else {
  414. visiting[index] = true;
  415. resolveBoneWorldTransform (static_cast<size_t> (parent), parents, locals, world, resolved, visiting);
  416. visiting[index] = false;
  417. world[index] = world[static_cast<size_t> (parent)] * locals[index];
  418. }
  419. resolved[index] = true;
  420. }
  421. std::vector<glm::mat4>
  422. composeBoneWorldTransforms (const std::vector<int>& parents, const std::vector<glm::mat4>& locals) {
  423. std::vector<glm::mat4> world (locals.size ());
  424. std::vector<bool> resolved (locals.size (), false);
  425. std::vector<bool> visiting (locals.size (), false);
  426. for (size_t i = 0; i < locals.size (); i++) {
  427. resolveBoneWorldTransform (i, parents, locals, world, resolved, visiting);
  428. }
  429. return world;
  430. }
  431. struct PuppetAttachmentPointSet {
  432. std::vector<PuppetAttachmentPoint> points;
  433. size_t mdlaOffset = 0;
  434. };
  435. // Parses the optional MDAT section (named attachment points other objects can follow, e.g. scene.json's "attachment":
  436. // "orb"). 2.8.42 reads a u16 count, then per point a u16 bone, the name and a 64 byte matrix (sub_140261880). Keeps
  437. // the points parsed so far and stops at the first implausible entry
  438. PuppetAttachmentPointSet
  439. parsePuppetAttachmentPoints (const BinaryReader& reader, size_t mdatOffset, uint32_t boneCount) {
  440. reader.base ().seekg (static_cast<std::streamoff> (mdatOffset), std::ios::beg);
  441. char header[9];
  442. reader.next (header, sizeof (header));
  443. PuppetAttachmentPointSet result;
  444. result.mdlaOffset = reader.nextUInt32 ();
  445. uint16_t pointCount = 0;
  446. reader.next (reinterpret_cast<char*> (&pointCount), sizeof (pointCount));
  447. // every point starts with its bone, read one ahead
  448. uint16_t nextBoneIndex = 0;
  449. reader.next (reinterpret_cast<char*> (&nextBoneIndex), sizeof (nextBoneIndex));
  450. constexpr uint16_t maxPlausiblePointCount = 256;
  451. if (pointCount > maxPlausiblePointCount) {
  452. sLog.error ("Puppet attachment point count (", pointCount, ") looks implausible, ignoring attachment points");
  453. return result;
  454. }
  455. for (uint16_t i = 0; i < pointCount; i++) {
  456. const std::string name = reader.nextNullTerminatedString ();
  457. float m[16];
  458. for (float& value : m) {
  459. value = reader.nextFloat ();
  460. }
  461. const uint16_t boneIndex = nextBoneIndex;
  462. if (i + 1 < pointCount) {
  463. reader.next (reinterpret_cast<char*> (&nextBoneIndex), sizeof (nextBoneIndex));
  464. }
  465. if (name.empty () || boneIndex >= boneCount) {
  466. sLog.error (
  467. "Puppet attachment point ", i, " (name=", name, ", bone=", boneIndex,
  468. ") looks implausible, stopping here (", result.points.size (), " point(s) kept)"
  469. );
  470. break;
  471. }
  472. // same row-major-to-column-major transpose trick used for PuppetBone::bindLocal
  473. const glm::mat4 localTransform (
  474. m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]
  475. );
  476. result.points.push_back (
  477. PuppetAttachmentPoint { .name = name, .boneIndex = boneIndex, .localTransform = localTransform }
  478. );
  479. }
  480. return result;
  481. }
  482. // Parses every baked animation clip out of the MDLA section (see docs/rendering/MDL_FILES.md), laid out like
  483. // 2.8.42 reads it (sub_140261880). Only the bone tracks are used, everything after them is skipped by its size.
  484. std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
  485. const BinaryReader& reader, size_t mdlaOffset, uint32_t expectedBoneCount, const PuppetBoneSet& rig,
  486. uint32_t meshCount
  487. ) {
  488. reader.base ().seekg (static_cast<std::streamoff> (mdlaOffset), std::ios::beg);
  489. char header[9];
  490. reader.next (header, sizeof (header));
  491. const int version = std::atoi (header + 4);
  492. const uint32_t sectionEnd = reader.nextUInt32 ();
  493. const uint32_t clipCount = reader.nextUInt32 ();
  494. constexpr uint32_t maxPlausibleClipCount = 64;
  495. if (clipCount > maxPlausibleClipCount) {
  496. sLog.error ("Puppet animation clip count (", clipCount, ") looks implausible, skipping animation entirely");
  497. return {};
  498. }
  499. std::vector<PuppetAnimationClip> clips;
  500. clips.reserve (clipCount);
  501. for (uint32_t clipIndex = 0; clipIndex < clipCount; clipIndex++) {
  502. PuppetAnimationClip clip;
  503. reader.next (reinterpret_cast<char*> (&clip.id), sizeof (clip.id));
  504. clip.name = reader.nextNullTerminatedString ();
  505. clip.mode = reader.nextNullTerminatedString ();
  506. clip.fps = reader.nextFloat ();
  507. clip.frameCount = reader.nextUInt32 ();
  508. const uint32_t flags = reader.nextUInt32 ();
  509. const uint32_t boneCount = reader.nextUInt32 ();
  510. constexpr uint32_t maxPlausibleFrameCount = 100000;
  511. if (clip.frameCount > maxPlausibleFrameCount || boneCount != expectedBoneCount) {
  512. sLog.error (
  513. "Puppet animation clip ", clipIndex, " has an implausible frame/bone count (frames=", clip.frameCount,
  514. ", bones=", boneCount, ", expected ", expectedBoneCount, "), stopping here"
  515. );
  516. break;
  517. }
  518. const uint32_t sampleCount = clip.frameCount + 1;
  519. bool valid = true;
  520. clip.boneTracks.resize (boneCount);
  521. clip.boneAnimated.assign (boneCount, true);
  522. clip.boneFlags.assign (boneCount, 0);
  523. for (uint32_t boneIndex = 0; boneIndex < boneCount && valid; boneIndex++) {
  524. // bit 0 keeps the bone out of this clip, the blend masks it (2.8.42 sub_140261880)
  525. clip.boneFlags[boneIndex] = reader.nextUInt32 ();
  526. clip.boneAnimated[boneIndex] = (clip.boneFlags[boneIndex] & 1) == 0;
  527. const uint32_t trackBytes = reader.nextUInt32 ();
  528. if (trackBytes != sampleCount * 9 * sizeof (float)) {
  529. valid = false;
  530. break;
  531. }
  532. auto& track = clip.boneTracks[boneIndex];
  533. track.reserve (sampleCount);
  534. for (uint32_t sample = 0; sample < sampleCount; sample++) {
  535. PuppetKeyframe keyframe;
  536. keyframe.position = { reader.nextFloat (), reader.nextFloat (), reader.nextFloat () };
  537. keyframe.rotation = { reader.nextFloat (), reader.nextFloat (), reader.nextFloat () };
  538. keyframe.scale = { reader.nextFloat (), reader.nextFloat (), reader.nextFloat () };
  539. // the loader turns the euler angles into a quaternion right away, same order as the matrices
  540. keyframe.orientation = glm::angleAxis (keyframe.rotation.z, glm::vec3 (0.0f, 0.0f, 1.0f))
  541. * glm::angleAxis (keyframe.rotation.y, glm::vec3 (0.0f, 1.0f, 0.0f))
  542. * glm::angleAxis (keyframe.rotation.x, glm::vec3 (1.0f, 0.0f, 0.0f));
  543. track.push_back (keyframe);
  544. }
  545. }
  546. if (version >= 2) {
  547. clip.extraTracks.resize (rig.extraCount);
  548. clip.extraAnimated.assign (rig.extraCount, true);
  549. for (uint32_t extra = 0; extra < rig.extraCount && valid; extra++) {
  550. clip.extraAnimated[extra] = (reader.nextUInt32 () & 1) == 0;
  551. if (reader.nextUInt32 () != sampleCount * 9 * sizeof (float)) {
  552. valid = false;
  553. break;
  554. }
  555. auto& track = clip.extraTracks[extra];
  556. track.reserve (sampleCount);
  557. for (uint32_t sample = 0; sample < sampleCount; sample++) {
  558. PuppetKeyframe keyframe;
  559. keyframe.position = { reader.nextFloat (), reader.nextFloat (), reader.nextFloat () };
  560. keyframe.rotation = { reader.nextFloat (), reader.nextFloat (), reader.nextFloat () };
  561. keyframe.scale = { reader.nextFloat (), reader.nextFloat (), reader.nextFloat () };
  562. keyframe.orientation = glm::angleAxis (keyframe.rotation.z, glm::vec3 (0.0f, 0.0f, 1.0f))
  563. * glm::angleAxis (keyframe.rotation.y, glm::vec3 (0.0f, 1.0f, 0.0f))
  564. * glm::angleAxis (keyframe.rotation.x, glm::vec3 (1.0f, 0.0f, 0.0f));
  565. track.push_back (keyframe);
  566. }
  567. }
  568. clip.constraintTracks.resize (rig.constraintCount);
  569. clip.constraintFlags.assign (rig.constraintCount, 0);
  570. for (uint32_t constraint = 0; constraint < rig.constraintCount && valid; constraint++) {
  571. clip.constraintFlags[constraint] = reader.nextUInt32 ();
  572. if (reader.nextUInt32 () != sampleCount * sizeof (float)) {
  573. valid = false;
  574. break;
  575. }
  576. clip.constraintTracks[constraint].resize (sampleCount);
  577. for (float& sample : clip.constraintTracks[constraint]) {
  578. sample = reader.nextFloat ();
  579. }
  580. }
  581. }
  582. if (version >= 3 && valid) {
  583. // g_BlendMap tracks (clip +216)
  584. const uint32_t blendTracks = reader.nextUInt32 ();
  585. clip.blendTracks.resize (blendTracks);
  586. for (uint32_t track = 0; track < blendTracks && valid; track++) {
  587. (void)reader.nextUInt32 ();
  588. if (reader.nextUInt32 () != sampleCount * sizeof (float)) {
  589. valid = false;
  590. break;
  591. }
  592. clip.blendTracks[track].resize (sampleCount);
  593. for (float& sample : clip.blendTracks[track]) {
  594. sample = reader.nextFloat ();
  595. }
  596. }
  597. // bone alpha tracks (clip +240)
  598. if (valid && reader.next () != 0) {
  599. clip.boneAlphaTracks.resize (boneCount);
  600. for (uint32_t boneIndex = 0; boneIndex < boneCount && valid; boneIndex++) {
  601. (void)reader.nextUInt32 ();
  602. const uint32_t trackBytes = reader.nextUInt32 ();
  603. if (trackBytes != sampleCount * sizeof (float)) {
  604. valid = false;
  605. break;
  606. }
  607. auto& track = clip.boneAlphaTracks[boneIndex];
  608. track.resize (sampleCount);
  609. for (float& sample : track) {
  610. sample = reader.nextFloat ();
  611. }
  612. }
  613. if (!valid) {
  614. clip.boneAlphaTracks.clear ();
  615. }
  616. }
  617. }
  618. // per mesh morph weight tracks: a u32 whose bit 0 enables them, a u32, a u16 count and per track the target
  619. // and its samples
  620. if (version >= 4 && valid && reader.next () != 0) {
  621. clip.morphTracks.resize (meshCount);
  622. for (uint32_t mesh = 0; mesh < meshCount && valid; mesh++) {
  623. if ((reader.nextUInt32 () & 1) == 0) {
  624. continue;
  625. }
  626. auto& meshTracks = clip.morphTracks[mesh];
  627. meshTracks.enabled = true;
  628. (void)reader.nextUInt32 ();
  629. uint16_t count = 0;
  630. reader.next (reinterpret_cast<char*> (&count), sizeof (count));
  631. for (uint16_t i = 0; i < count && valid; i++) {
  632. PuppetAnimationClip::MorphTrack track;
  633. reader.next (reinterpret_cast<char*> (&track.target), sizeof (track.target));
  634. const uint32_t trackBytes = reader.nextUInt32 ();
  635. if (trackBytes != sampleCount * sizeof (float)) {
  636. valid = false;
  637. break;
  638. }
  639. track.samples.resize (sampleCount);
  640. for (float& sample : track.samples) {
  641. sample = reader.nextFloat ();
  642. }
  643. meshTracks.tracks.push_back (std::move (track));
  644. }
  645. }
  646. }
  647. if (version >= 5 && valid) {
  648. for (int axis = 0; axis < 3; axis++) {
  649. clip.boundsMin[axis] = reader.nextFloat ();
  650. }
  651. for (int axis = 0; axis < 3; axis++) {
  652. clip.boundsMax[axis] = reader.nextFloat ();
  653. }
  654. }
  655. // a flag byte and one float track per bone, the bones' draw order offsets (clip +264)
  656. if (version >= 6 && valid && reader.next () != 0) {
  657. clip.drawOrderTracks.resize (boneCount);
  658. for (uint32_t boneIndex = 0; boneIndex < boneCount && valid; boneIndex++) {
  659. (void)reader.nextUInt32 ();
  660. const uint32_t trackBytes = reader.nextUInt32 ();
  661. if (trackBytes != sampleCount * sizeof (float)) {
  662. valid = false;
  663. break;
  664. }
  665. auto& track = clip.drawOrderTracks[boneIndex];
  666. track.resize (sampleCount);
  667. for (float& sample : track) {
  668. sample = reader.nextFloat ();
  669. }
  670. }
  671. if (!valid) {
  672. clip.drawOrderTracks.clear ();
  673. }
  674. }
  675. clip.flags = flags;
  676. if ((flags & 1) && valid) {
  677. PuppetAnimationClip::RootMotion record;
  678. reader.next (reinterpret_cast<char*> (&record.clip), sizeof (record.clip));
  679. record.frameStart = reader.nextUInt32 ();
  680. record.frameEnd = reader.nextUInt32 ();
  681. record.startOffset = reader.nextUInt32 ();
  682. record.bone = static_cast<int> (reader.nextUInt32 ());
  683. // the clip it plays has to come before it; WE stops loading the file otherwise
  684. if (record.clip >= clips.size ()) {
  685. sLog.error ("Animation clip ", clip.name, " refers to clip ", record.clip, " which isn't loaded yet");
  686. } else {
  687. // with root motion the loader samples the root bone at the first and the last frame: the ones the
  688. // record names in the clip it plays, or with 0x400 frame 0 and the end of this clip's own samples
  689. if ((flags & 0x1F800) != 0) {
  690. const bool own = (flags & 0x400) != 0;
  691. const PuppetAnimationClip& source = own ? clip : clips[record.clip];
  692. const uint32_t first = own ? 0 : record.frameStart;
  693. const uint32_t last = own ? clip.frameCount : record.frameEnd;
  694. record.frames.first = samplePuppetBoneChain (rig.bones, source, record.bone, first, first, 0.0f);
  695. record.frames.inverseFirst = glm::inverse (glm::mat3 (record.frames.first));
  696. record.frames.last = samplePuppetBoneChain (rig.bones, source, record.bone, last, last, 0.0f);
  697. }
  698. clip.rootMotion = record;
  699. }
  700. }
  701. if (valid) {
  702. const uint32_t eventCount = reader.nextUInt32 ();
  703. for (uint32_t i = 0; i < eventCount && reader.base ().good (); i++) {
  704. PuppetClipEvent event;
  705. event.time = reader.nextFloat ();
  706. event.payload = reader.nextNullTerminatedString ();
  707. clip.events.push_back (std::move (event));
  708. }
  709. }
  710. if (!valid || !reader.base ().good ()) {
  711. reader.base ().clear ();
  712. sLog.error ("Puppet animation clip ", clip.name, " doesn't match the MDLA layout, stopping here");
  713. if (!valid) {
  714. break;
  715. }
  716. }
  717. clips.push_back (std::move (clip));
  718. }
  719. if (clips.size () == clipCount && static_cast<size_t> (reader.base ().tellg ()) != sectionEnd) {
  720. sLog.error (
  721. "Puppet MDLA clips end at ", static_cast<size_t> (reader.base ().tellg ()), " but the section ends at ",
  722. sectionEnd
  723. );
  724. }
  725. return clips;
  726. }
  727. glm::vec3 lerp (const glm::vec3& a, const glm::vec3& b, float alpha) { return a + (b - a) * alpha; }
  728. // glm::slerp as WE's sample code has it inlined: the shorter way round, plain lerp once the angle gets tiny
  729. glm::quat slerp (const glm::quat& a, glm::quat b, float alpha) {
  730. float cosine = glm::dot (a, b);
  731. if (cosine < 0.0f) {
  732. b = -b;
  733. cosine = -cosine;
  734. }
  735. if (cosine > 1.0f - std::numeric_limits<float>::epsilon ()) {
  736. return a * (1.0f - alpha) + b * alpha;
  737. }
  738. const float angle = std::acos (cosine);
  739. return (a * std::sin ((1.0f - alpha) * angle) + b * std::sin (alpha * angle)) / std::sin (angle);
  740. }
  741. } // namespace
  742. glm::mat4 WallpaperEngine::Render::Objects::samplePuppetBoneChain (
  743. const std::vector<PuppetBone>& bones, const PuppetAnimationClip& clip, int bone, uint32_t frame0, uint32_t frame1,
  744. float alpha
  745. ) {
  746. // sub_140267F00 (sub_140267580 for one frame): the bone's local matrices up the parent chain, translate * rotate
  747. // without the scale, the rotation slerped
  748. glm::mat4 result (1.0f);
  749. for (size_t depth = 0; bone >= 0 && static_cast<size_t> (bone) < bones.size () && depth < bones.size (); depth++) {
  750. if (static_cast<size_t> (bone) >= clip.boneTracks.size ()) {
  751. break;
  752. }
  753. const auto& track = clip.boneTracks[bone];
  754. if (frame0 >= track.size () || frame1 >= track.size ()) {
  755. break;
  756. }
  757. const glm::vec3 position = track[frame0].position * (1.0f - alpha) + track[frame1].position * alpha;
  758. const glm::quat orientation = slerp (track[frame0].orientation, track[frame1].orientation, alpha);
  759. result = glm::translate (glm::mat4 (1.0f), position) * glm::mat4_cast (orientation) * result;
  760. bone = bones[bone].parent;
  761. }
  762. return result;
  763. }
  764. void PuppetRig::clear () { *this = PuppetRig (); }
  765. void PuppetRig::load (const std::vector<char>& data, size_t sections, uint32_t meshCount, const std::string& name) {
  766. this->clear ();
  767. // MDLS first, the bones size everything else
  768. const auto mdlsOffset = findMdlSection (data, sections, "MDLS");
  769. if (!mdlsOffset.has_value ()) {
  770. throw std::runtime_error ("the file has no skeleton");
  771. }
  772. auto buffer = std::make_unique<char[]> (data.size ());
  773. std::copy (data.begin (), data.end (), buffer.get ());
  774. const BinaryReader reader (std::make_shared<MemoryStream> (std::move (buffer), data.size ()));
  775. auto boneSet = parsePuppetBones (reader, *mdlsOffset);
  776. std::vector<int> bindParents (boneSet.bones.size ());
  777. std::vector<glm::mat4> bindLocals (boneSet.bones.size ());
  778. for (size_t i = 0; i < boneSet.bones.size (); i++) {
  779. bindParents[i] = boneSet.bones[i].parent;
  780. bindLocals[i] = boneSet.bones[i].bindLocal;
  781. }
  782. const std::vector<glm::mat4> worldBind = composeBoneWorldTransforms (bindParents, bindLocals);
  783. for (size_t i = 0; i < boneSet.bones.size (); i++) {
  784. boneSet.bones[i].inverseBindWorld = glm::inverse (worldBind[i]);
  785. }
  786. this->bones = std::move (boneSet.bones);
  787. this->boneDrawOrder = std::move (boneSet.drawOrder);
  788. this->boneHitOrder = std::move (boneSet.hitOrder);
  789. this->boneModel = worldBind;
  790. this->bindModel = worldBind;
  791. this->extras = boneSet.extras;
  792. this->ik = std::move (boneSet.ik);
  793. this->hasIK = !this->ik.chains.empty ();
  794. this->extraModel.resize (this->extras.size ());
  795. for (size_t i = 0; i < this->extras.size (); i++) {
  796. this->extraModel[i] = this->extras[i].restLocal;
  797. }
  798. this->physicsState.assign (this->bones.size (), {});
  799. this->ropeJoints.assign (this->bones.size (), {});
  800. this->constraintWeights.assign (boneSet.constraintCount, 0.0f);
  801. this->hasPhysics
  802. = std::ranges::any_of (this->bones, [] (const PuppetBone& bone) { return bone.physics.simulated (); });
  803. this->hasRestPose
  804. = std::ranges::any_of (this->bones, [] (const PuppetBone& bone) { return bone.restLocal != bone.bindLocal; });
  805. // sub_140261880 walks the sections after the meshes in whatever order they come: every one is "TAGnnnn\0" and the
  806. // absolute offset of the next one, an empty tag or the end of the file ends it. MDAT holds attachment points, MDMP
  807. // morph targets (read by the model), MDLA the clips
  808. size_t offset = sections;
  809. std::set<size_t> visited;
  810. while (offset + 13 <= data.size () && data[offset] != 0 && visited.insert (offset).second) {
  811. const std::string tag (data.data () + offset, 4);
  812. uint32_t next = 0;
  813. std::memcpy (&next, data.data () + offset + 9, sizeof (next));
  814. if (tag == "MDAT") {
  815. auto attachmentSet
  816. = parsePuppetAttachmentPoints (reader, offset, static_cast<uint32_t> (this->bones.size ()));
  817. this->attachmentPoints = std::move (attachmentSet.points);
  818. } else if (tag == "MDMP") {
  819. this->morphSection = offset;
  820. } else if (tag == "MDLE" && std::string_view (data.data () + offset, 8) == "MDLE0002") {
  821. // skipped byte size, then a row-major matrix per bone
  822. const size_t matrices = offset + 17;
  823. if (matrices + this->bones.size () * 64 <= data.size ()) {
  824. this->layerImageBindLocal.resize (this->bones.size ());
  825. for (size_t bone = 0; bone < this->bones.size (); bone++) {
  826. float m[16];
  827. std::memcpy (m, data.data () + matrices + bone * 64, sizeof (m));
  828. this->layerImageBindLocal[bone] = glm::mat4 (
  829. m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14],
  830. m[15]
  831. );
  832. }
  833. }
  834. } else if (tag == "MDLA") {
  835. this->clips = parsePuppetAnimationClips (
  836. reader, offset, static_cast<uint32_t> (this->bones.size ()), boneSet, meshCount
  837. );
  838. }
  839. if (next <= offset) {
  840. sLog.error ("Section ", tag, " of ", name, " doesn't point past itself, the sections after it are skipped");
  841. break;
  842. }
  843. offset = next;
  844. }
  845. if (!this->attachmentPoints.empty ()) {
  846. std::string names;
  847. for (const auto& point : this->attachmentPoints) {
  848. names += (names.empty () ? "" : ", ") + point.name;
  849. }
  850. sLog.out ("Found ", this->attachmentPoints.size (), " attachment point(s) on ", name, ": ", names);
  851. }
  852. }
  853. void PuppetRig::addSceneLayers (const std::vector<ImageAnimationLayerUniquePtr>& sceneLayers) {
  854. // a layer plays the clip whose id is its "animation" value, layers without a match are dropped (2.8.42
  855. // sub_1401FCC20); layer and clip names don't have to agree (3521337568's "j" plays "动画 1")
  856. for (size_t index = 0; index < sceneLayers.size (); index++) {
  857. this->addLayer (*sceneLayers[index], nullptr, index, false);
  858. }
  859. this->nextLayerSerial = sceneLayers.size ();
  860. for (const auto& active : this->layers) {
  861. sLog.out (
  862. "Playing animation ", active.clip.name, " (", active.clip.mode, ", ", active.clip.fps, " fps, ",
  863. active.clip.frameCount, " frames)"
  864. );
  865. }
  866. }
  867. std::vector<glm::mat4> PuppetRig::skinMatrices () const {
  868. std::vector<glm::mat4> skin (this->bones.size ());
  869. for (size_t i = 0; i < this->bones.size (); i++) {
  870. skin[i]
  871. = (i < this->boneModel.size () ? this->boneModel[i] : glm::mat4 (1.0f)) * this->bones[i].inverseBindWorld;
  872. }
  873. return skin;
  874. }
  875. bool PuppetRig::clipBounds (glm::vec3& min, glm::vec3& max) const {
  876. glm::vec3 lower (std::numeric_limits<float>::max ());
  877. glm::vec3 upper (-std::numeric_limits<float>::max ());
  878. bool found = false;
  879. for (const auto& layer : this->layers) {
  880. if (layer.layer == nullptr || !layer.layer->visible->value->getBool ()) {
  881. continue;
  882. }
  883. found = found || layer.clip.boundsMax.x > layer.clip.boundsMin.x;
  884. lower = glm::min (lower, layer.clip.boundsMin);
  885. upper = glm::max (upper, layer.clip.boundsMax);
  886. }
  887. if (found) {
  888. min = lower;
  889. max = upper;
  890. }
  891. return found;
  892. }
  893. PuppetActiveAnimation* PuppetRig::findLayer (size_t serial) {
  894. const auto it = std::ranges::find (this->layers, serial, &PuppetActiveAnimation::serial);
  895. return it == this->layers.end () ? nullptr : &*it;
  896. }
  897. // sub_1401FCC20: the layer plays the clip whose id is its "animation", without one it isn't created. autosort puts it
  898. // after the last non-additive layer, "index" at that position (never past the last one), otherwise it goes last
  899. bool PuppetRig::addLayer (
  900. const ImageAnimationLayer& layer, ImageAnimationLayerUniquePtr owned, size_t serial, bool autoRemove
  901. ) {
  902. if (!layer.animation) {
  903. return false;
  904. }
  905. const auto id = static_cast<uint64_t> (layer.animation->value->getInt ());
  906. const auto match = std::ranges::find (this->clips, id, &PuppetAnimationClip::id);
  907. if (match == this->clips.end ()) {
  908. return false;
  909. }
  910. // sub_1401A8C10: "mirror" sets flag 1, "single" flag 2, anything else loops; starts at 0, playing
  911. uint32_t flags = 0;
  912. if (strcasecmp (match->mode.c_str (), "mirror") == 0) {
  913. flags |= PuppetClockMirror;
  914. } else if (strcasecmp (match->mode.c_str (), "single") == 0) {
  915. flags |= PuppetClockSingle;
  916. }
  917. PuppetActiveAnimation entry {
  918. .clip = *match,
  919. .layer = &layer,
  920. .ownedLayer = std::move (owned),
  921. .serial = serial,
  922. .blendIn = layer.blendIn,
  923. // only a clip that stops on its end fades out
  924. .blendOut = layer.blendOut && (flags & PuppetClockSingle) != 0,
  925. .autoRemove = autoRemove,
  926. .flags = flags,
  927. };
  928. auto& list = this->layers;
  929. auto position = list.end ();
  930. if (layer.autosort) {
  931. position = std::find_if (list.rbegin (), list.rend (), [] (const PuppetActiveAnimation& other) {
  932. return !other.layer->additive;
  933. }).base ();
  934. } else if (layer.index.has_value () && !list.empty ()) {
  935. const auto index = std::clamp<int64_t> (*layer.index, 0, static_cast<int64_t> (list.size ()) - 1);
  936. position = list.begin () + index;
  937. }
  938. list.insert (position, std::move (entry));
  939. return true;
  940. }
  941. size_t PuppetRig::getLayerCount () const { return this->layers.size (); }
  942. std::optional<size_t> PuppetRig::getLayerAt (int64_t index) const {
  943. if (index < 0 || index >= static_cast<int64_t> (this->layers.size ())) {
  944. return std::nullopt;
  945. }
  946. return this->layers[static_cast<size_t> (index)].serial;
  947. }
  948. std::optional<size_t> PuppetRig::findLayerByName (const std::string& name) const {
  949. // sub_14020E910 keeps the last layer with that name
  950. std::optional<size_t> result = std::nullopt;
  951. if (name.empty ()) {
  952. return result;
  953. }
  954. for (const auto& layer : this->layers) {
  955. if (layer.layer->name == name) {
  956. result = layer.serial;
  957. }
  958. }
  959. return result;
  960. }
  961. // sub_14020EA30: a config without blendin/blendout fades both ways. A clip name looks the clip up by name and puts its
  962. // id into the config, an object is the layer JSON itself with the config's keys written over it
  963. std::optional<size_t> PuppetRig::createLayer (
  964. const Data::JSON::JSON& animation, const Data::JSON::JSON& config, bool autoRemove, const Project& project
  965. ) {
  966. if (this->clips.empty ()) {
  967. return std::nullopt;
  968. }
  969. auto settings = config.is_object () ? config : Data::JSON::JSON::object ();
  970. if (!settings.contains ("blendin")) {
  971. settings["blendin"] = true;
  972. }
  973. if (!settings.contains ("blendout")) {
  974. settings["blendout"] = true;
  975. }
  976. Data::JSON::JSON layerJson;
  977. if (animation.is_string ()) {
  978. const auto name = animation.get<std::string> ();
  979. const auto clip = std::ranges::find (this->clips, name, &PuppetAnimationClip::name);
  980. if (name.empty () || clip == this->clips.end () || clip->id == 0) {
  981. return std::nullopt;
  982. }
  983. layerJson = std::move (settings);
  984. layerJson["animation"] = clip->id;
  985. } else if (animation.is_object ()) {
  986. layerJson = animation;
  987. for (const auto& [key, value] : settings.items ()) {
  988. layerJson[key] = value;
  989. }
  990. } else {
  991. return std::nullopt;
  992. }
  993. if (!layerJson.contains ("animation") || !layerJson["animation"].is_number ()) {
  994. return std::nullopt;
  995. }
  996. const size_t serial = this->nextLayerSerial++;
  997. // sub_1401A38F0 hands out a fresh id when the config has none
  998. if (!layerJson.contains ("id") || !layerJson["id"].is_number ()) {
  999. layerJson["id"] = static_cast<int> (serial);
  1000. }
  1001. ImageAnimationLayerUniquePtr owned;
  1002. try {
  1003. owned = ObjectParser::parseAnimationLayer (layerJson, project);
  1004. } catch (const std::exception& ex) {
  1005. sLog.error ("createAnimationLayer: invalid layer config: ", ex.what ());
  1006. return std::nullopt;
  1007. }
  1008. const auto& layer = *owned;
  1009. if (!this->addLayer (layer, std::move (owned), serial, autoRemove)) {
  1010. return std::nullopt;
  1011. }
  1012. return serial;
  1013. }
  1014. bool PuppetRig::destroyLayersByName (const std::string& name) {
  1015. if (name.empty ()) {
  1016. return false;
  1017. }
  1018. return this->removeLayers ([&name] (const PuppetActiveAnimation& layer) { return layer.layer->name == name; }) > 0;
  1019. }
  1020. bool PuppetRig::destroyLayer (size_t serial) {
  1021. return this->removeLayers ([serial] (const PuppetActiveAnimation& layer) { return layer.serial == serial; }) > 0;
  1022. }
  1023. // sub_1401FDF90, after the pose: a layer that ended runs its ended callbacks, a playSingleAnimation() one is removed
  1024. std::vector<std::string> PuppetRig::takeFiredEvents () { return std::exchange (this->firedEvents, {}); }
  1025. void PuppetRig::finishEndedLayers (const std::function<void (size_t)>& dispatch) {
  1026. std::vector<size_t> ended;
  1027. for (const auto& layer : this->layers) {
  1028. if (layer.ended) {
  1029. ended.push_back (layer.serial);
  1030. }
  1031. }
  1032. // callbacks may create or destroy layers, so layers are looked up again by serial
  1033. for (const size_t serial : ended) {
  1034. dispatch (serial);
  1035. }
  1036. this->removeLayers ([&ended] (const PuppetActiveAnimation& layer) {
  1037. return layer.autoRemove && std::ranges::find (ended, layer.serial) != ended.end ();
  1038. });
  1039. }
  1040. size_t PuppetRig::removeLayers (const std::function<bool (const PuppetActiveAnimation&)>& predicate) {
  1041. const auto removed = std::ranges::stable_partition (this->layers, std::not_fn (predicate));
  1042. const auto count = static_cast<size_t> (std::ranges::distance (removed));
  1043. for (auto& layer : removed) {
  1044. if (layer.ownedLayer != nullptr) {
  1045. this->removedLayers.push_back (std::move (layer));
  1046. }
  1047. }
  1048. this->layers.erase (removed.begin (), removed.end ());
  1049. return count;
  1050. }
  1051. std::vector<glm::mat4> PuppetRig::layerImageBindModel () const {
  1052. const bool own = this->layerImageBindLocal.size () == this->bones.size ();
  1053. std::vector<glm::mat4> result (this->bones.size (), glm::mat4 (1.0f));
  1054. // a parent listed later is still unset, WE reads it uninitialised
  1055. for (size_t i = 0; i < this->bones.size (); i++) {
  1056. const glm::mat4& local = own ? this->layerImageBindLocal[i] : this->bones[i].bindLocal;
  1057. const int parent = this->bones[i].parent;
  1058. result[i] = parent >= 0 && static_cast<size_t> (parent) < result.size () ? result[parent] * local : local;
  1059. }
  1060. return result;
  1061. }
  1062. std::vector<PuppetActiveAnimation> PuppetRig::takeRemovedLayers () { return std::exchange (this->removedLayers, {}); }
  1063. void PuppetRig::updateMorphWeights (const std::vector<PuppetLayerSample>& samples) {
  1064. // sub_14021C480: every mesh's weights start at zero each frame, then the layers apply theirs in order. A layer at
  1065. // full weight sets them (a weight of about 0 switches the target off), additive ones add theirs kept between
  1066. // the two values, the others blend towards theirs and clamp to 0..1. Layers at zero weight are skipped
  1067. for (auto& mesh : this->morphWeights) {
  1068. mesh.active = 0;
  1069. std::ranges::fill (mesh.weights, 0.0f);
  1070. }
  1071. constexpr float epsilon = 1.1920929e-7f;
  1072. for (const auto& sample : samples) {
  1073. if (sample.weight == 0.0f) {
  1074. continue;
  1075. }
  1076. const bool direct = sample.weight == 1.0f && !sample.additive;
  1077. const auto& meshes = sample.clip->morphTracks;
  1078. if (this->morphWeights.size () < meshes.size ()) {
  1079. this->morphWeights.resize (meshes.size ());
  1080. }
  1081. for (size_t mesh = 0; mesh < meshes.size (); mesh++) {
  1082. if (!meshes[mesh].enabled) {
  1083. continue;
  1084. }
  1085. auto& state = this->morphWeights[mesh];
  1086. for (const auto& track : meshes[mesh].tracks) {
  1087. if (track.target >= 64 || track.samples.size () <= sample.frame1) {
  1088. continue;
  1089. }
  1090. if (state.weights.size () <= track.target) {
  1091. state.weights.resize (track.target + 1, 0.0f);
  1092. }
  1093. const float value = (1.0f - sample.alpha) * track.samples[sample.frame0]
  1094. + sample.alpha * track.samples[sample.frame1];
  1095. const uint64_t bit = uint64_t (1) << track.target;
  1096. float& weight = state.weights[track.target];
  1097. if (direct) {
  1098. if (std::abs (value) < epsilon) {
  1099. state.active &= ~bit;
  1100. } else {
  1101. state.active |= bit;
  1102. weight = value;
  1103. }
  1104. } else if (sample.additive) {
  1105. if (std::abs (value) >= epsilon) {
  1106. const float added = value * sample.weight;
  1107. state.active |= bit;
  1108. weight = std::clamp (weight + added, std::min (weight, added), std::max (weight, added));
  1109. }
  1110. } else {
  1111. if (std::abs (value) >= epsilon) {
  1112. state.active |= bit;
  1113. }
  1114. weight = (1.0f - sample.weight) * weight + sample.weight * value;
  1115. if (this->morphBlendClamped) {
  1116. weight = std::clamp (weight, 0.0f, 1.0f);
  1117. }
  1118. }
  1119. }
  1120. }
  1121. }
  1122. }
  1123. void PuppetRig::updatePose (const glm::mat4& objectWorld, PuppetRootMotionHost* host) {
  1124. if (this->bones.empty ()) {
  1125. return;
  1126. }
  1127. // WE's layer blend (2.8.42 sub_1401FDF90, models sub_14021C480): bones start at the MDLS rest pose, each visible
  1128. // layer steps its clock (dt * rate) and blends towards its clip's sample (sub_1401F9020) or adds its difference
  1129. // from rest when additive (sub_1401F9820); bones flagged off in a clip keep what they have
  1130. const float dt = this->clockTime < 0.0f ? 0.0f : std::max (g_Time - this->clockTime, 0.0f);
  1131. this->clockTime = g_Time;
  1132. const size_t count = this->bones.size ();
  1133. std::vector<glm::vec3> positions (count);
  1134. std::vector<glm::vec3> scales (count);
  1135. std::vector<glm::quat> orientations (count);
  1136. std::vector<glm::quat> restOrientations (count);
  1137. for (size_t i = 0; i < count; i++) {
  1138. const glm::mat4& rest = this->bones[i].restLocal;
  1139. positions[i] = glm::vec3 (rest[3]);
  1140. scales[i] = glm::vec3 (
  1141. glm::length (glm::vec3 (rest[0])), glm::length (glm::vec3 (rest[1])), glm::length (glm::vec3 (rest[2]))
  1142. );
  1143. restOrientations[i] = glm::normalize (
  1144. glm::quat_cast (
  1145. glm::mat3 (
  1146. glm::vec3 (rest[0]) / scales[i].x, glm::vec3 (rest[1]) / scales[i].y,
  1147. glm::vec3 (rest[2]) / scales[i].z
  1148. )
  1149. )
  1150. );
  1151. orientations[i] = restOrientations[i];
  1152. }
  1153. // extras (P+576/P+584)
  1154. const size_t extraCount = this->extras.size ();
  1155. std::vector<glm::vec3> extraPositions (extraCount);
  1156. std::vector<glm::vec3> extraScales (extraCount);
  1157. std::vector<glm::quat> extraOrientations (extraCount);
  1158. std::vector<glm::quat> extraRestOrientations (extraCount);
  1159. for (size_t i = 0; i < extraCount; i++) {
  1160. const glm::mat4& rest = this->extras[i].restLocal;
  1161. extraPositions[i] = glm::vec3 (rest[3]);
  1162. extraScales[i] = glm::vec3 (
  1163. glm::length (glm::vec3 (rest[0])), glm::length (glm::vec3 (rest[1])), glm::length (glm::vec3 (rest[2]))
  1164. );
  1165. extraRestOrientations[i] = glm::normalize (
  1166. glm::quat_cast (
  1167. glm::mat3 (
  1168. glm::vec3 (rest[0]) / extraScales[i].x, glm::vec3 (rest[1]) / extraScales[i].y,
  1169. glm::vec3 (rest[2]) / extraScales[i].z
  1170. )
  1171. )
  1172. );
  1173. extraOrientations[i] = extraRestOrientations[i];
  1174. }
  1175. // q and -q are the same rotation, blends take the one on the same side
  1176. const auto nlerp = [] (const glm::quat& a, glm::quat b, float t) {
  1177. if (glm::dot (a, b) < 0.0f) {
  1178. b = -b;
  1179. }
  1180. return glm::normalize (a * (1.0f - t) + b * t);
  1181. };
  1182. const auto blend = [&] (const PuppetLayerSample& sample) {
  1183. const auto& clip = *sample.clip;
  1184. for (size_t i = 0; i < count; i++) {
  1185. if (i >= clip.boneTracks.size () || clip.boneTracks[i].size () <= sample.frame1
  1186. || (i < clip.boneAnimated.size () && !clip.boneAnimated[i])) {
  1187. continue;
  1188. }
  1189. const auto& from = clip.boneTracks[i][sample.frame0];
  1190. const auto& to = clip.boneTracks[i][sample.frame1];
  1191. const glm::vec3 samplePosition = lerp (from.position, to.position, sample.alpha);
  1192. const glm::vec3 sampleScale = lerp (from.scale, to.scale, sample.alpha);
  1193. const glm::quat sampleOrientation = nlerp (from.orientation, to.orientation, sample.alpha);
  1194. const float weight = sample.weight;
  1195. if (sample.additive) {
  1196. const glm::vec3 restPosition (this->bones[i].restLocal[3]);
  1197. const glm::vec3 restScale (
  1198. glm::length (glm::vec3 (this->bones[i].restLocal[0])),
  1199. glm::length (glm::vec3 (this->bones[i].restLocal[1])),
  1200. glm::length (glm::vec3 (this->bones[i].restLocal[2]))
  1201. );
  1202. positions[i] += (samplePosition - restPosition) * weight;
  1203. scales[i] += (sampleScale - restScale) * weight;
  1204. const glm::quat delta = glm::conjugate (restOrientations[i]) * sampleOrientation;
  1205. orientations[i] = orientations[i] * nlerp (glm::quat (1.0f, 0.0f, 0.0f, 0.0f), delta, weight);
  1206. } else {
  1207. positions[i] = positions[i] * (1.0f - weight) + samplePosition * weight;
  1208. scales[i] = scales[i] * (1.0f - weight) + sampleScale * weight;
  1209. orientations[i] = nlerp (orientations[i], sampleOrientation, weight);
  1210. }
  1211. }
  1212. for (size_t i = 0; i < extraCount; i++) {
  1213. if (i >= clip.extraTracks.size () || clip.extraTracks[i].size () <= sample.frame1
  1214. || (i < clip.extraAnimated.size () && !clip.extraAnimated[i])) {
  1215. continue;
  1216. }
  1217. const auto& from = clip.extraTracks[i][sample.frame0];
  1218. const auto& to = clip.extraTracks[i][sample.frame1];
  1219. const glm::vec3 samplePosition = lerp (from.position, to.position, sample.alpha);
  1220. const glm::vec3 sampleScale = lerp (from.scale, to.scale, sample.alpha);
  1221. const glm::quat sampleOrientation = nlerp (from.orientation, to.orientation, sample.alpha);
  1222. const float weight = sample.weight;
  1223. if (sample.additive) {
  1224. const glm::mat4& rest = this->extras[i].restLocal;
  1225. extraPositions[i] += (samplePosition - glm::vec3 (rest[3])) * weight;
  1226. extraScales[i] += (sampleScale
  1227. - glm::vec3 (
  1228. glm::length (glm::vec3 (rest[0])), glm::length (glm::vec3 (rest[1])),
  1229. glm::length (glm::vec3 (rest[2]))
  1230. ))
  1231. * weight;
  1232. const glm::quat delta = glm::conjugate (extraRestOrientations[i]) * sampleOrientation;
  1233. extraOrientations[i] = extraOrientations[i] * nlerp (glm::quat (1.0f, 0.0f, 0.0f, 0.0f), delta, weight);
  1234. } else {
  1235. extraPositions[i] = extraPositions[i] * (1.0f - weight) + samplePosition * weight;
  1236. extraScales[i] = extraScales[i] * (1.0f - weight) + sampleScale * weight;
  1237. extraOrientations[i] = nlerp (extraOrientations[i], sampleOrientation, weight);
  1238. }
  1239. }
  1240. };
  1241. std::vector<PuppetLayerSample> samples;
  1242. for (size_t index = 0; index < this->layers.size (); index++) {
  1243. auto& candidate = this->layers[index];
  1244. candidate.ended = false;
  1245. if (candidate.layer == nullptr || !candidate.layer->visible->value->getBool ()) {
  1246. continue;
  1247. }
  1248. const auto& clip = candidate.clip;
  1249. if (clip.fps <= 0.0f || clip.frameCount == 0) {
  1250. continue;
  1251. }
  1252. const float frameTime = 1.0f / clip.fps;
  1253. const float duration = static_cast<float> (clip.frameCount) * frameTime;
  1254. const uint32_t previousFlags = candidate.flags;
  1255. const float previousTime = candidate.time;
  1256. stepPuppetClock (candidate, duration, dt * candidate.layer->rate->value->getFloat (), &this->firedEvents);
  1257. // a layer ends when a single clip stops, a mirror turns around or a loop wraps, unless it was paused, stopped
  1258. // or moved by setFrame() since the last step
  1259. if ((previousFlags & (PuppetClockFrameSet | PuppetClockPaused | PuppetClockStopped)) == 0) {
  1260. if ((candidate.flags & PuppetClockSingle) != 0) {
  1261. candidate.ended = (candidate.flags & PuppetClockStopped) != 0;
  1262. } else if ((candidate.flags & PuppetClockMirror) != 0) {
  1263. candidate.ended = (previousFlags & PuppetClockBackwards) != (candidate.flags & PuppetClockBackwards);
  1264. } else {
  1265. candidate.ended = previousTime > candidate.time;
  1266. }
  1267. }
  1268. candidate.flags &= ~PuppetClockFrameSet;
  1269. const float time = candidate.time;
  1270. // sub_140170580
  1271. const int lastFrame = static_cast<int> (clip.frameCount) - 1;
  1272. const int frame0 = std::clamp (static_cast<int> (time / frameTime), 0, lastFrame);
  1273. PuppetLayerSample sample { .clip = &clip,
  1274. .frame0 = static_cast<uint32_t> (frame0),
  1275. .frame1 = std::min (static_cast<uint32_t> (frame0 + 1), clip.frameCount),
  1276. .alpha = std::fmod (time, frameTime) / frameTime,
  1277. .weight = puppetLayerWeight (candidate, duration),
  1278. .additive = candidate.layer->additive };
  1279. // models only (sub_14021C480): a clip with flags & 1 and without 0x400 plays the frames of the clip its record
  1280. // names, from frameStart on
  1281. if (host != nullptr && (clip.flags & 0x401) == 1 && clip.rootMotion.has_value ()
  1282. && clip.rootMotion->clip < this->clips.size ()) {
  1283. sample.clip = &this->clips[clip.rootMotion->clip];
  1284. sample.frame0 += clip.rootMotion->frameStart;
  1285. sample.frame1 += clip.rootMotion->frameStart;
  1286. }
  1287. samples.push_back (sample);
  1288. if (sample.weight == 0.0f) {
  1289. candidate.rootMotion.started = false;
  1290. continue;
  1291. }
  1292. blend (sample);
  1293. if (host == nullptr || !host->rootMotionEnabled () || (clip.flags & 0x1F800) == 0
  1294. || !clip.rootMotion.has_value ()) {
  1295. candidate.rootMotion.started = false;
  1296. continue;
  1297. }
  1298. // what the visible normal layers above this one leave of it
  1299. float rest = 1.0f;
  1300. for (size_t above = index + 1; above < this->layers.size (); above++) {
  1301. auto& layer = this->layers[above];
  1302. if (layer.layer == nullptr || !layer.layer->visible->value->getBool () || layer.layer->additive) {
  1303. continue;
  1304. }
  1305. const float aboveDuration
  1306. = layer.clip.fps > 0.0f ? static_cast<float> (layer.clip.frameCount) * (1.0f / layer.clip.fps) : 0.0f;
  1307. rest *= 1.0f - puppetLayerWeight (layer, aboveDuration);
  1308. }
  1309. if (rest > 0.0001f) {
  1310. this->applyRootMotion (candidate, sample, positions, orientations, rest, *host);
  1311. }
  1312. candidate.rootMotion.started = true;
  1313. candidate.rootMotion.time = candidate.time;
  1314. }
  1315. this->poseAnimated
  1316. = !samples.empty () || this->hasPhysics || this->poseScripted || this->hasRestPose || this->hasIK;
  1317. // no scale (~0x1402012a0)
  1318. for (size_t i = 0; i < extraCount; i++) {
  1319. this->extraModel[i]
  1320. = glm::translate (glm::mat4 (1.0f), extraPositions[i]) * glm::mat4_cast (extraOrientations[i]);
  1321. }
  1322. std::vector<int> animatedParents (count);
  1323. std::vector<glm::mat4> animatedLocals (count);
  1324. for (size_t i = 0; i < count; i++) {
  1325. animatedParents[i] = this->bones[i].parent;
  1326. // no animation layer playing, physics runs on the rest pose like WE
  1327. if (samples.empty ()) {
  1328. animatedLocals[i] = this->bones[i].restLocal;
  1329. continue;
  1330. }
  1331. animatedLocals[i] = glm::translate (glm::mat4 (1.0f), positions[i]) * glm::mat4_cast (orientations[i])
  1332. * glm::scale (glm::mat4 (1.0f), scales[i]);
  1333. }
  1334. // root motion may have moved the object, WE takes the world matrix again for the bones
  1335. this->composePose (animatedParents, animatedLocals, host != nullptr ? host->rootMotionWorld () : objectWorld);
  1336. this->updateMorphWeights (samples);
  1337. this->updateDrawOrder (samples);
  1338. this->updateBoneAlpha (samples);
  1339. this->updateBlendMap (samples);
  1340. this->updateConstraintWeights (samples);
  1341. }
  1342. void PuppetRig::updateConstraintWeights (const std::vector<PuppetLayerSample>& samples) {
  1343. // puppet +592 persists across frames, zeroed only by a first layer that isn't a full weight set
  1344. // (0x1401fee2e..0x1401fee87)
  1345. for (size_t layer = 0; layer < samples.size (); layer++) {
  1346. const auto& sample = samples[layer];
  1347. const auto& tracks = sample.clip->constraintTracks;
  1348. const bool direct = sample.weight == 1.0f && !sample.additive;
  1349. if (layer == 0 && !direct) {
  1350. std::ranges::fill (this->constraintWeights, 0.0f);
  1351. }
  1352. for (size_t track = 0; track < tracks.size () && track < this->constraintWeights.size (); track++) {
  1353. if ((sample.clip->constraintFlags[track] & 1) != 0 || sample.frame1 >= tracks[track].size ()) {
  1354. continue;
  1355. }
  1356. const float value
  1357. = (1.0f - sample.alpha) * tracks[track][sample.frame0] + sample.alpha * tracks[track][sample.frame1];
  1358. float& current = this->constraintWeights[track];
  1359. if (direct) {
  1360. current = value;
  1361. } else if (!sample.additive) {
  1362. current = (1.0f - sample.weight) * current + sample.weight * value;
  1363. } else {
  1364. current += value * sample.weight;
  1365. }
  1366. }
  1367. }
  1368. }
  1369. void PuppetRig::updateBlendMap (const std::vector<PuppetLayerSample>& samples) {
  1370. // instance +848 persists across frames: set, lerp or add per layer (0x1401ff041..0x1401ffa18)
  1371. for (const auto& sample : samples) {
  1372. const auto& tracks = sample.clip->blendTracks;
  1373. const bool direct = sample.weight == 1.0f && !sample.additive;
  1374. for (size_t track = 0; track < tracks.size () && track < this->blendMap.size (); track++) {
  1375. if (sample.frame1 >= tracks[track].size ()) {
  1376. continue;
  1377. }
  1378. const float value
  1379. = (1.0f - sample.alpha) * tracks[track][sample.frame0] + sample.alpha * tracks[track][sample.frame1];
  1380. float& current = this->blendMap[track];
  1381. if (direct) {
  1382. current = value;
  1383. } else if (!sample.additive) {
  1384. current = (1.0f - sample.weight) * current + sample.weight * value;
  1385. } else {
  1386. current += value * sample.weight;
  1387. }
  1388. }
  1389. }
  1390. }
  1391. void PuppetRig::updateBoneAlpha (const std::vector<PuppetLayerSample>& samples) {
  1392. if (!this->boneAlphaEnabled) {
  1393. return;
  1394. }
  1395. // starts at 1 every frame; additive layers move by (value - 1) * weight, bones with (flags & 3) == 1 are skipped
  1396. this->boneAlpha.assign (this->bones.size (), 1.0f);
  1397. for (const auto& sample : samples) {
  1398. const auto& tracks = sample.clip->boneAlphaTracks;
  1399. const bool direct = sample.weight == 1.0f && !sample.additive;
  1400. for (size_t bone = 0; bone < tracks.size () && bone < this->boneAlpha.size (); bone++) {
  1401. if (bone < sample.clip->boneFlags.size () && (sample.clip->boneFlags[bone] & 3) == 1) {
  1402. continue;
  1403. }
  1404. if (sample.frame1 >= tracks[bone].size ()) {
  1405. continue;
  1406. }
  1407. const float value
  1408. = (1.0f - sample.alpha) * tracks[bone][sample.frame0] + sample.alpha * tracks[bone][sample.frame1];
  1409. float& alpha = this->boneAlpha[bone];
  1410. if (direct) {
  1411. alpha = value;
  1412. } else if (!sample.additive) {
  1413. alpha = (1.0f - sample.weight) * alpha + sample.weight * value;
  1414. } else {
  1415. alpha = std::clamp (
  1416. alpha + (value - 1.0f) * sample.weight, std::min (alpha, value), std::max (alpha, value)
  1417. );
  1418. }
  1419. }
  1420. }
  1421. }
  1422. void PuppetRig::updateDrawOrder (const std::vector<PuppetLayerSample>& samples) {
  1423. this->drawOrderTouched = false;
  1424. if (!this->drawOrderEnabled) {
  1425. return;
  1426. }
  1427. // every frame starts from the MDLS orders; a layer at full weight sets its clip's value for the frame it is on
  1428. // (no interpolation), a blended one lerps towards it by its weight, an additive one moves by (value - MDLS
  1429. // order) * weight without passing the value
  1430. this->drawOrder.assign (this->bones.size (), 0.0f);
  1431. for (size_t bone = 0; bone < this->bones.size () && bone < this->boneDrawOrder.size (); bone++) {
  1432. this->drawOrder[bone] = static_cast<float> (this->boneDrawOrder[bone]);
  1433. }
  1434. for (const auto& sample : samples) {
  1435. const auto& tracks = sample.clip->drawOrderTracks;
  1436. const bool direct = sample.weight == 1.0f && !sample.additive;
  1437. for (size_t bone = 0; bone < tracks.size () && bone < this->drawOrder.size (); bone++) {
  1438. if (bone < sample.clip->boneFlags.size () && (sample.clip->boneFlags[bone] & 3) == 1) {
  1439. continue;
  1440. }
  1441. if (sample.frame0 >= tracks[bone].size ()) {
  1442. continue;
  1443. }
  1444. const float value = tracks[bone][sample.frame0];
  1445. float& order = this->drawOrder[bone];
  1446. if (direct) {
  1447. order = value;
  1448. } else if (!sample.additive) {
  1449. order = (1.0f - sample.weight) * order + sample.weight * value;
  1450. } else {
  1451. const float rest
  1452. = bone < this->boneDrawOrder.size () ? static_cast<float> (this->boneDrawOrder[bone]) : 0.0f;
  1453. order = std::clamp (
  1454. order + (value - rest) * sample.weight, std::min (order, value), std::max (order, value)
  1455. );
  1456. }
  1457. this->drawOrderTouched = true;
  1458. }
  1459. }
  1460. }
  1461. void PuppetRig::applyRootMotion (
  1462. PuppetActiveAnimation& layer, const PuppetLayerSample& sample, std::vector<glm::vec3>& positions,
  1463. std::vector<glm::quat>& orientations, const float rest, PuppetRootMotionHost& host
  1464. ) {
  1465. const auto& clip = layer.clip;
  1466. const auto& record = *clip.rootMotion;
  1467. if (record.bone < 0 || static_cast<size_t> (record.bone) >= this->bones.size ()) {
  1468. return;
  1469. }
  1470. // the root bone from the clip that is playing, and when the layer starts what it counts from: the record's start
  1471. // offset (frame 0 with 0x400), the first frame without one
  1472. const auto& source = *sample.clip;
  1473. const glm::mat4 current
  1474. = samplePuppetBoneChain (this->bones, source, record.bone, sample.frame0, sample.frame1, sample.alpha);
  1475. glm::mat4 start = record.frames.first;
  1476. if (!layer.rootMotion.started && record.startOffset != 0) {
  1477. const uint32_t frame = (clip.flags & 0x400) != 0 ? 0 : record.startOffset + record.frameStart;
  1478. start = samplePuppetBoneChain (this->bones, source, record.bone, frame, frame, 0.0f);
  1479. }
  1480. const auto step = stepPuppetRootMotion (
  1481. clip.flags, record.frames, current, start, layer.time, sample.weight, rest, glm::mat3 (host.rootMotionWorld ()),
  1482. layer.rootMotion, positions[record.bone], orientations[record.bone]
  1483. );
  1484. if (step.moves) {
  1485. host.rootMotionMove (step.offset);
  1486. }
  1487. if (step.turns) {
  1488. host.rootMotionTurn (turnPuppetRootMotion (host.rootMotionAngles (), step.yaw));
  1489. }
  1490. }
  1491. void PuppetRig::composePose (
  1492. const std::vector<int>& parents, const std::vector<glm::mat4>& locals, const glm::mat4& objectWorld
  1493. ) {
  1494. const size_t count = parents.size ();
  1495. const float dt = std::max (g_Time - g_TimeLast, 0.0f);
  1496. // sub_1401FDF90 swaps the current and previous scene matrices first, so whatever a script wrote into the current
  1497. // ones last frame is what the physics compares against
  1498. const bool hasPrevious = this->boneScene.size () == count;
  1499. if (hasPrevious) {
  1500. this->physicsPreviousScene = this->boneScene;
  1501. }
  1502. // WE runs the physics on the bones' scene transforms (object world * bone)
  1503. const glm::mat4& object = objectWorld;
  1504. const float objectScale = (glm::length (glm::vec3 (object[0])) + glm::length (glm::vec3 (object[1]))
  1505. + glm::length (glm::vec3 (object[2])))
  1506. / 3.0f;
  1507. // model matrices (P+712) persist across frames like WE, the solver starts from last frame
  1508. std::vector<glm::mat4> model = this->boneModel.size () == count ? this->boneModel : this->bindModel;
  1509. model.resize (count, glm::mat4 (1.0f));
  1510. std::vector<glm::mat4> scene (count);
  1511. std::vector<glm::mat4> local = locals;
  1512. std::vector<uint8_t> resolved (count, 0);
  1513. std::vector<int> ikParents (count);
  1514. std::vector<PuppetBoneIK> ikSettings (count);
  1515. for (size_t i = 0; i < count; i++) {
  1516. ikParents[i] = this->bones[i].parent;
  1517. ikSettings[i] = this->bones[i].ik;
  1518. }
  1519. // parents first, a simulated parent moves its children
  1520. const auto resolve = [&] (const auto& self, size_t index) -> void {
  1521. if (resolved[index] != 0) {
  1522. return;
  1523. }
  1524. resolved[index] = 1;
  1525. const int parent = parents[index];
  1526. const bool parented = parent >= 0 && static_cast<size_t> (parent) < count;
  1527. if (parented && resolved[parent] != 1) {
  1528. self (self, static_cast<size_t> (parent));
  1529. }
  1530. // posed by the solver (~0x140201300)
  1531. if ((this->bones[index].type & 2) && this->bones[index].chain < 0) {
  1532. scene[index] = object * model[index];
  1533. local[index] = parented ? glm::inverse (model[parent]) * model[index] : model[index];
  1534. resolved[index] = 2;
  1535. return;
  1536. }
  1537. model[index] = parented ? model[parent] * locals[index] : locals[index];
  1538. // the bone's blend rules, before physics
  1539. for (const auto& rule : this->bones[index].rules) {
  1540. if (rule.target < count) {
  1541. const float weight
  1542. = rule.weight < this->constraintWeights.size () ? this->constraintWeights[rule.weight] : 0.0f;
  1543. model[index] = blendPuppetTransform (model[index], model[rule.target], weight);
  1544. }
  1545. }
  1546. scene[index] = object * model[index];
  1547. const auto& physics = this->bones[index].physics;
  1548. // the first frame has nothing to compare against and only records where the bones are
  1549. if (physics.simulated () && hasPrevious) {
  1550. model[index] = model[index]
  1551. * stepPuppetBonePhysics (
  1552. physics, this->physicsState[index], scene[index], this->physicsPreviousScene[index], dt,
  1553. objectScale
  1554. );
  1555. scene[index] = object * model[index];
  1556. }
  1557. // solve the chain this bone starts, its scene matrix keeps the unsolved pose
  1558. if (const int chain = this->bones[index].chain;
  1559. chain >= 0 && static_cast<size_t> (chain) < this->ik.chains.size ()) {
  1560. const auto& solved = this->ik.chains[chain];
  1561. const bool rope = std::ranges::any_of (solved.links, [] (const PuppetIKLink& link) {
  1562. return std::ranges::any_of (link.entries, [] (const PuppetIKEntry& entry) {
  1563. return (entry.flags & 4) != 0;
  1564. });
  1565. });
  1566. // sub_14026F4C0
  1567. applyPuppetChainConstraints (this->ik, solved, this->constraintWeights, model, this->extraModel);
  1568. if (rope) {
  1569. stepPuppetRopeChain (
  1570. this->ik, solved, ikSettings, model, this->extraModel, object, this->ropeJoints,
  1571. this->ropeEnvironment, dt
  1572. );
  1573. }
  1574. solvePuppetIKChain (
  1575. this->ik, solved, ikParents, ikSettings, model, this->extraModel, this->bindModel, object,
  1576. this->ropeJoints
  1577. );
  1578. }
  1579. resolved[index] = 2;
  1580. };
  1581. for (size_t i = 0; i < count; i++) {
  1582. resolve (resolve, i);
  1583. }
  1584. this->boneLocal = std::move (local);
  1585. this->boneModel = std::move (model);
  1586. this->boneScene = std::move (scene);
  1587. }
  1588. bool PuppetRig::hasPose () const { return !this->bones.empty () && this->boneScene.size () == this->bones.size (); }
  1589. int PuppetRig::findBone (const std::string& name) const {
  1590. for (size_t i = 0; i < this->bones.size (); i++) {
  1591. if (this->bones[i].name == name) {
  1592. return static_cast<int> (i);
  1593. }
  1594. }
  1595. return -1;
  1596. }
  1597. int PuppetRig::findAttachment (const std::string& name) const {
  1598. const auto point = std::ranges::find (this->attachmentPoints, name, &PuppetAttachmentPoint::name);
  1599. return point == this->attachmentPoints.end () ? -1 : static_cast<int> (point - this->attachmentPoints.begin ());
  1600. }
  1601. std::optional<glm::mat4> PuppetRig::attachmentMatrix (int index) const {
  1602. if (index < 0 || static_cast<size_t> (index) >= this->attachmentPoints.size ()) {
  1603. return std::nullopt;
  1604. }
  1605. const auto& point = this->attachmentPoints[index];
  1606. if (point.boneIndex < 0 || static_cast<size_t> (point.boneIndex) >= this->boneModel.size ()) {
  1607. return std::nullopt;
  1608. }
  1609. return this->boneModel[point.boneIndex] * point.localTransform;
  1610. }
  1611. const glm::mat4& PuppetRig::getBoneTransform (int bone) const { return this->boneScene[bone]; }
  1612. namespace {
  1613. // sub_1401853C0, no t >= 0 check
  1614. bool lineHitsBox (const glm::vec3& origin, const glm::vec3& direction, const glm::vec3& extents, float& enter) {
  1615. float leave = std::numeric_limits<float>::max ();
  1616. enter = std::numeric_limits<float>::lowest ();
  1617. for (int axis = 0; axis < 3; axis++) {
  1618. const float a = (extents[axis] - origin[axis]) / direction[axis];
  1619. const float b = (-extents[axis] - origin[axis]) / direction[axis];
  1620. enter = std::max (enter, std::min (a, b));
  1621. leave = std::min (leave, std::max (a, b));
  1622. }
  1623. return leave >= enter;
  1624. }
  1625. } // namespace
  1626. std::string PuppetRig::hitBoxName (int bone) const {
  1627. return this->bones[bone].name.empty () ? std::to_string (bone) : this->bones[bone].name;
  1628. }
  1629. std::optional<std::string> PuppetRig::imageHitBox (const glm::vec3& origin, const glm::vec3& direction) const {
  1630. if (!this->hasPose () || this->boneHitOrder.empty () || !this->bones.front ().hasCapsule) {
  1631. return std::nullopt;
  1632. }
  1633. for (auto it = this->boneHitOrder.rbegin (); it != this->boneHitOrder.rend (); ++it) {
  1634. const int bone = *it;
  1635. const glm::mat4 toBox = glm::inverse (this->boneScene[bone] * this->bones[bone].capsule);
  1636. const glm::vec3 localOrigin = toBox * glm::vec4 (origin, 1.0f);
  1637. const glm::vec3 localDirection = glm::normalize (glm::vec3 (toBox * glm::vec4 (direction, 0.0f)));
  1638. float enter;
  1639. if (lineHitsBox (localOrigin, localDirection, this->bones[bone].capsuleExtents, enter)) {
  1640. return this->hitBoxName (bone);
  1641. }
  1642. }
  1643. return std::nullopt;
  1644. }
  1645. std::optional<std::string> PuppetRig::modelHitBox (
  1646. const glm::vec3& origin, const glm::vec3& direction, const glm::mat4& objectWorld, glm::vec3& local
  1647. ) const {
  1648. if (this->bones.empty () || !this->bones.front ().hasCapsule || this->boneModel.size () != this->bones.size ()) {
  1649. return std::nullopt;
  1650. }
  1651. std::optional<std::string> name;
  1652. float nearest = std::numeric_limits<float>::max ();
  1653. for (size_t bone = 0; bone < this->bones.size (); bone++) {
  1654. const glm::mat4 toBox = glm::inverse (objectWorld * this->boneModel[bone] * this->bones[bone].capsule);
  1655. const glm::vec3 localOrigin = toBox * glm::vec4 (origin, 1.0f);
  1656. const glm::vec3 localDirection = glm::normalize (glm::vec3 (toBox * glm::vec4 (direction, 0.0f)));
  1657. float enter;
  1658. if (lineHitsBox (localOrigin, localDirection, this->bones[bone].capsuleExtents, enter) && enter < nearest) {
  1659. nearest = enter;
  1660. local = localOrigin + localDirection * enter;
  1661. name = this->hitBoxName (static_cast<int> (bone));
  1662. }
  1663. }
  1664. return name;
  1665. }
  1666. void PuppetRig::setBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld) {
  1667. // sub_14020F350: only this bone, its children keep their matrices until the next update
  1668. this->boneScene[bone] = transform;
  1669. this->boneModel[bone] = glm::inverse (objectWorld) * transform;
  1670. this->poseScripted = true;
  1671. this->poseAnimated = true;
  1672. }
  1673. const glm::mat4& PuppetRig::getLocalBoneTransform (int bone) const { return this->boneLocal[bone]; }
  1674. void PuppetRig::setLocalBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld) {
  1675. this->boneLocal[bone] = transform;
  1676. // sub_14020DB40: the bone and every later bone whose parent was touched, in index order
  1677. const glm::mat4& object = objectWorld;
  1678. std::set<int> touched;
  1679. const int count = static_cast<int> (this->bones.size ());
  1680. for (int index = bone; index < count; index++) {
  1681. const int parent = this->bones[index].parent;
  1682. if (index != bone && !touched.contains (parent)) {
  1683. continue;
  1684. }
  1685. touched.insert (index);
  1686. this->boneModel[index]
  1687. = parent < 0 || parent >= count ? this->boneLocal[index] : this->boneModel[parent] * this->boneLocal[index];
  1688. this->boneScene[index] = object * this->boneModel[index];
  1689. }
  1690. this->poseScripted = true;
  1691. this->poseAnimated = true;
  1692. }
  1693. void PuppetRig::applyBonePhysicsImpulse (int bone, const glm::vec3& directional, const glm::vec3& angularDegrees) {
  1694. if (bone >= 0 && static_cast<size_t> (bone) < this->physicsState.size ()) {
  1695. applyPuppetBoneImpulse (this->physicsState[bone], directional, angularDegrees);
  1696. }
  1697. }
  1698. void PuppetRig::resetBonePhysics (int bone) {
  1699. // sub_140210E10, rope joints included
  1700. if (bone >= 0 && static_cast<size_t> (bone) < this->physicsState.size ()) {
  1701. this->physicsState[bone] = {};
  1702. }
  1703. if (bone >= 0 && static_cast<size_t> (bone) < this->ropeJoints.size ()) {
  1704. this->ropeJoints[bone] = {};
  1705. }
  1706. }