PuppetRig.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  1. #include "PuppetRig.h"
  2. #include <algorithm>
  3. #include <array>
  4. #include <cmath>
  5. #include <cstring>
  6. #include <limits>
  7. #include <set>
  8. #include <strings.h>
  9. #include <glm/gtc/matrix_transform.hpp>
  10. #include "WallpaperEngine/Data/Model/Project.h"
  11. #include "WallpaperEngine/Data/Parsers/ObjectParser.h"
  12. #include "WallpaperEngine/Data/Utils/BinaryReader.h"
  13. #include "WallpaperEngine/Data/Utils/MemoryStream.h"
  14. #include "WallpaperEngine/Logging/Log.h"
  15. using namespace WallpaperEngine;
  16. using namespace WallpaperEngine::Render::Objects;
  17. using namespace WallpaperEngine::Data::Model;
  18. using namespace WallpaperEngine::Data::Parsers;
  19. using namespace WallpaperEngine::Data::Utils;
  20. extern float g_Time;
  21. extern float g_TimeLast;
  22. namespace {
  23. constexpr uint32_t PuppetClockMirror = 1;
  24. constexpr uint32_t PuppetClockSingle = 2;
  25. constexpr uint32_t PuppetClockFrameSet = 0x2000000;
  26. constexpr uint32_t PuppetClockPaused = 0x20000000;
  27. constexpr uint32_t PuppetClockStopped = 0x40000000;
  28. constexpr uint32_t PuppetClockBackwards = 0x80000000;
  29. // WE's timeline step (2.8.42 sub_1401A9F60, fmodf results taken from the asm): loops wrap, mirrors turn around at
  30. // either end, single clips stop on their end
  31. void stepPuppetClock (PuppetActiveAnimation& clock, float duration, float delta) {
  32. if ((clock.flags & (PuppetClockPaused | PuppetClockStopped)) != 0
  33. || ((clock.flags & PuppetClockSingle) != 0 && clock.time >= duration) || duration <= 0.0f) {
  34. return;
  35. }
  36. if ((clock.flags & PuppetClockBackwards) != 0) {
  37. delta = -delta;
  38. }
  39. const float time = clock.time + delta;
  40. clock.time = time;
  41. if ((clock.flags & PuppetClockSingle) != 0) {
  42. if (time >= duration) {
  43. clock.flags |= PuppetClockStopped;
  44. clock.time = duration;
  45. }
  46. return;
  47. }
  48. if ((clock.flags & PuppetClockMirror) == 0) {
  49. if (time < 0.0f) {
  50. clock.time = std::fmod (time + duration, duration);
  51. }
  52. if (clock.time >= duration) {
  53. clock.time = std::fmod (clock.time, duration);
  54. }
  55. return;
  56. }
  57. if ((clock.flags & PuppetClockBackwards) != 0) {
  58. if (time <= 0.0f) {
  59. clock.time = -std::fmod (time, duration);
  60. clock.flags &= ~PuppetClockBackwards;
  61. }
  62. return;
  63. }
  64. if (time >= duration) {
  65. clock.flags |= PuppetClockBackwards;
  66. clock.time = duration - std::fmod (time, duration);
  67. }
  68. }
  69. // sub_14026C8B0: blend, faded in over the first min(duration / 2, blendtime) seconds and out over the last ones. A
  70. // clip that doesn't stop on its end drops the fade in once it is done
  71. float puppetLayerWeight (PuppetActiveAnimation& layer, float duration) {
  72. const float blendTime = layer.layer->blendTime;
  73. const float ramp = std::min (duration * 0.5f, blendTime);
  74. const bool canFade = std::min (duration, blendTime) > std::numeric_limits<float>::epsilon ();
  75. float weight = layer.layer->blend->value->getFloat ();
  76. if (layer.blendIn) {
  77. const float fade = canFade ? std::min (layer.time / ramp, 1.0f) : 1.0f;
  78. weight *= fade;
  79. if ((layer.flags & PuppetClockSingle) == 0 && fade >= 1.0f) {
  80. layer.blendIn = false;
  81. }
  82. }
  83. if (layer.blendOut && canFade) {
  84. weight *= std::min ((duration - layer.time) / ramp, 1.0f);
  85. }
  86. return weight;
  87. }
  88. struct PuppetBoneSet {
  89. std::vector<PuppetBone> bones;
  90. // Points at whatever section comes right after MDLS's second bone array: MDLA directly for
  91. // puppets with no attachment points, or MDAT (attachment points) otherwise - the caller has to
  92. // check which one it actually is.
  93. size_t nextSectionOffset = 0;
  94. // MDLS v2+ records after the bones, every MDLA clip carries one track per entry of each
  95. uint32_t extraCount = 0;
  96. uint32_t constraintCount = 0;
  97. };
  98. // Parses the MDLS bones (local bind-pose transforms, parent hierarchy and the per-bone physics JSON) and the
  99. // counts of the records after them that size the MDLA tracks. Inverse-bind matrices are derived from the bind
  100. // pose by walking the parent chain; the file's own copy is skipped.
  101. PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
  102. reader.base ().seekg (static_cast<std::streamoff> (mdlsOffset), std::ios::beg);
  103. char header[9];
  104. reader.next (header, sizeof (header));
  105. const uint32_t nextSectionOffset = reader.nextUInt32 ();
  106. const uint32_t boneCount = reader.nextUInt32 ();
  107. // A bone count this large can only be a garbage read (wrong mdlsOffset or an unrecognized MDLS
  108. // layout), not a real rig
  109. constexpr uint32_t maxPlausibleBoneCount = 512;
  110. if (boneCount > maxPlausibleBoneCount) {
  111. sLog.error ("Puppet bone count (", boneCount, ") looks implausible, skipping puppet mesh skinning");
  112. return {};
  113. }
  114. PuppetBoneSet result;
  115. result.nextSectionOffset = nextSectionOffset;
  116. result.bones.reserve (boneCount);
  117. for (uint32_t i = 0; i < boneCount; i++) {
  118. // records start with a null-terminated name, empty for most rigs
  119. std::string name = reader.nextNullTerminatedString ();
  120. (void)reader.nextUInt32 (); // type, unused
  121. const int parent = reader.nextInt ();
  122. const uint32_t matrixBytes = reader.nextUInt32 ();
  123. glm::mat4 bindLocal (1.0f);
  124. if (matrixBytes == sizeof (float) * 16) {
  125. float m[16];
  126. for (float& value : m) {
  127. value = reader.nextFloat ();
  128. }
  129. // the file stores a row-vector-convention, row-major matrix; feeding the 16 values straight
  130. // into glm's column-major constructor produces exactly its transpose, which is the
  131. // column-vector matrix glm needs to compute M * v
  132. bindLocal = glm::mat4 (
  133. 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]
  134. );
  135. } else {
  136. // an implausible byte count here means this bone record wasn't decoded correctly; bail out
  137. // rather than seeking by an untrusted amount and reading whatever garbage follows as bones
  138. constexpr uint32_t maxPlausibleMatrixBytes = 4096;
  139. if (matrixBytes > maxPlausibleMatrixBytes) {
  140. sLog.error (
  141. "Puppet bone ", i, " has an implausible matrix byte count (", matrixBytes, "), stopping here (",
  142. result.bones.size (), " bone(s) kept)"
  143. );
  144. break;
  145. }
  146. reader.base ().seekg (static_cast<std::streamoff> (matrixBytes), std::ios::cur);
  147. }
  148. // trailing per-bone string, jiggle/physics JSON for some rigs
  149. const std::string physics = reader.nextNullTerminatedString ();
  150. result.bones.push_back (
  151. PuppetBone { .name = std::move (name),
  152. .parent = parent,
  153. .bindLocal = bindLocal,
  154. .physics = PuppetBonePhysics::parse (physics) }
  155. );
  156. }
  157. // the rest of MDLS as 2.8.42 reads it (sub_140261880), only the two counts matter here
  158. const int version = std::atoi (header + 4);
  159. if (version < 2 || result.bones.size () != boneCount) {
  160. return result;
  161. }
  162. uint16_t extraCount = 0;
  163. reader.next (reinterpret_cast<char*> (&extraCount), sizeof (extraCount));
  164. for (uint16_t i = 0; i < extraCount; i++) {
  165. (void)reader.nextNullTerminatedString ();
  166. reader.base ().seekg (sizeof (uint32_t) * 2 + sizeof (float) * 16, std::ios::cur);
  167. }
  168. // a flag byte and then a matrix per bone and per extra record. Not the inverse bind matrices: bone 0 holds its bind
  169. // world and the others their bind locals (makima.body_puppet.mdl), what WE does with them isn't traced
  170. if (reader.next () != 0) {
  171. reader.base ().seekg (static_cast<std::streamoff> ((boneCount + extraCount) * sizeof (float) * 16), std::ios::cur);
  172. }
  173. const uint32_t constraintCount = reader.nextUInt32 ();
  174. for (uint32_t i = 0; i < constraintCount && reader.base ().good (); i++) {
  175. reader.base ().seekg (sizeof (uint32_t) * 3, std::ios::cur);
  176. const uint32_t flags = version >= 4 ? reader.nextUInt32 () : 0;
  177. if (flags & 2) {
  178. reader.base ().seekg (sizeof (uint32_t) + sizeof (float), std::ios::cur);
  179. }
  180. }
  181. if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) > nextSectionOffset) {
  182. reader.base ().clear ();
  183. sLog.error ("Puppet MDLS records after the bones don't fit the section, animation tracks may not line up");
  184. return result;
  185. }
  186. result.extraCount = extraCount;
  187. result.constraintCount = constraintCount;
  188. // sub_140261880 goes on with two more blocks before the per bone collision capsules
  189. const auto skip = [&reader] (std::streamoff bytes) { reader.base ().seekg (bytes, std::ios::cur); };
  190. const auto nextUInt16 = [&reader] () {
  191. uint16_t value = 0;
  192. reader.next (reinterpret_cast<char*> (&value), sizeof (value));
  193. return value;
  194. };
  195. const uint16_t groups = nextUInt16 ();
  196. skip (sizeof (uint32_t) * groups);
  197. for (uint16_t i = 0; i < groups && reader.base ().good (); i++) {
  198. skip ((sizeof (uint32_t) + sizeof (float) * 3) * nextUInt16 ());
  199. }
  200. const uint16_t chains = nextUInt16 ();
  201. for (uint16_t i = 0; i < chains && reader.base ().good (); i++) {
  202. (void)reader.nextUInt32 ();
  203. skip (sizeof (uint32_t) * reader.nextUInt32 ());
  204. const uint16_t links = nextUInt16 ();
  205. for (uint16_t j = 0; j < links && reader.base ().good (); j++) {
  206. (void)reader.nextUInt32 ();
  207. const uint16_t entries = nextUInt16 ();
  208. for (uint16_t k = 0; k < entries && reader.base ().good (); k++) {
  209. skip (sizeof (uint32_t) * 4);
  210. skip (sizeof (uint32_t) * nextUInt16 ());
  211. }
  212. }
  213. }
  214. if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) >= nextSectionOffset
  215. || reader.next () == 0) {
  216. reader.base ().clear ();
  217. return result;
  218. }
  219. // a vec3 of extents and the capsule's frame in bone space (row-vector, row-major like the bind matrices)
  220. for (auto& bone : result.bones) {
  221. for (int axis = 0; axis < 3; axis++) {
  222. bone.capsuleExtents[axis] = reader.nextFloat ();
  223. }
  224. float m[16];
  225. for (float& value : m) {
  226. value = reader.nextFloat ();
  227. }
  228. bone.capsule = glm::mat4 (
  229. 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]
  230. );
  231. bone.hasCapsule = true;
  232. }
  233. if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) > nextSectionOffset) {
  234. reader.base ().clear ();
  235. sLog.error ("Puppet MDLS collision capsules don't fit the section, ignoring them");
  236. for (auto& bone : result.bones) {
  237. bone.hasCapsule = false;
  238. }
  239. }
  240. return result;
  241. }
  242. // Resolves each bone's world transform by walking up the parent chain: the MDL format doesn't
  243. // guarantee parents come before their children, and some rigs (puppet eyes/eyebrows) break that order
  244. void resolveBoneWorldTransform (
  245. size_t index, const std::vector<int>& parents, const std::vector<glm::mat4>& locals, std::vector<glm::mat4>& world,
  246. std::vector<bool>& resolved, std::vector<bool>& visiting
  247. ) {
  248. if (resolved[index]) {
  249. return;
  250. }
  251. const int parent = parents[index];
  252. // a missing parent, an out-of-range index, or a cycle back onto a bone still being resolved are
  253. // all treated the same way a genuine root bone would be: no parent transform to fold in
  254. if (parent < 0 || static_cast<size_t> (parent) >= parents.size () || visiting[index]) {
  255. world[index] = locals[index];
  256. } else {
  257. visiting[index] = true;
  258. resolveBoneWorldTransform (static_cast<size_t> (parent), parents, locals, world, resolved, visiting);
  259. visiting[index] = false;
  260. world[index] = world[static_cast<size_t> (parent)] * locals[index];
  261. }
  262. resolved[index] = true;
  263. }
  264. std::vector<glm::mat4>
  265. composeBoneWorldTransforms (const std::vector<int>& parents, const std::vector<glm::mat4>& locals) {
  266. std::vector<glm::mat4> world (locals.size ());
  267. std::vector<bool> resolved (locals.size (), false);
  268. std::vector<bool> visiting (locals.size (), false);
  269. for (size_t i = 0; i < locals.size (); i++) {
  270. resolveBoneWorldTransform (i, parents, locals, world, resolved, visiting);
  271. }
  272. return world;
  273. }
  274. struct PuppetAttachmentPointSet {
  275. std::vector<PuppetAttachmentPoint> points;
  276. size_t mdlaOffset = 0;
  277. };
  278. // Parses the optional MDAT section (named attachment points other objects can follow, e.g.
  279. // scene.json's "attachment": "orb" - see docs/rendering/MDL_FILES.md). Keeps the points parsed so far
  280. // and stops at the first implausible entry, the tail of this section isn't fully understood
  281. PuppetAttachmentPointSet
  282. parsePuppetAttachmentPoints (const BinaryReader& reader, size_t mdatOffset, uint32_t boneCount) {
  283. reader.base ().seekg (static_cast<std::streamoff> (mdatOffset), std::ios::beg);
  284. char header[9];
  285. reader.next (header, sizeof (header));
  286. PuppetAttachmentPointSet result;
  287. result.mdlaOffset = reader.nextUInt32 ();
  288. uint16_t pointCount = 0;
  289. reader.next (reinterpret_cast<char*> (&pointCount), sizeof (pointCount));
  290. // The WORD trailing every point's matrix is the NEXT point's bone index: point 0's comes right
  291. // after pointCount and the last point has no trailing WORD, which consumes exactly the section's
  292. // declared length
  293. uint16_t nextBoneIndex = 0;
  294. reader.next (reinterpret_cast<char*> (&nextBoneIndex), sizeof (nextBoneIndex));
  295. constexpr uint16_t maxPlausiblePointCount = 256;
  296. if (pointCount > maxPlausiblePointCount) {
  297. sLog.error ("Puppet attachment point count (", pointCount, ") looks implausible, ignoring attachment points");
  298. return result;
  299. }
  300. for (uint16_t i = 0; i < pointCount; i++) {
  301. const std::string name = reader.nextNullTerminatedString ();
  302. float m[16];
  303. for (float& value : m) {
  304. value = reader.nextFloat ();
  305. }
  306. const uint16_t boneIndex = nextBoneIndex;
  307. if (i + 1 < pointCount) {
  308. reader.next (reinterpret_cast<char*> (&nextBoneIndex), sizeof (nextBoneIndex));
  309. }
  310. if (name.empty () || boneIndex >= boneCount) {
  311. sLog.error (
  312. "Puppet attachment point ", i, " (name=", name, ", bone=", boneIndex,
  313. ") looks implausible, stopping here (", result.points.size (), " point(s) kept)"
  314. );
  315. break;
  316. }
  317. // same row-major-to-column-major transpose trick used for PuppetBone::bindLocal
  318. const glm::mat4 localTransform (
  319. 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]
  320. );
  321. result.points.push_back (
  322. PuppetAttachmentPoint { .name = name, .boneIndex = boneIndex, .localTransform = localTransform }
  323. );
  324. }
  325. return result;
  326. }
  327. // Parses every baked animation clip out of the MDLA section (see docs/rendering/MDL_FILES.md), laid out like
  328. // 2.8.42 reads it (sub_140261880). Only the bone tracks are used, everything after them is skipped by its size.
  329. std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
  330. const BinaryReader& reader, size_t mdlaOffset, uint32_t expectedBoneCount, const PuppetBoneSet& rig,
  331. uint32_t meshCount
  332. ) {
  333. reader.base ().seekg (static_cast<std::streamoff> (mdlaOffset), std::ios::beg);
  334. char header[9];
  335. reader.next (header, sizeof (header));
  336. const int version = std::atoi (header + 4);
  337. const uint32_t sectionEnd = reader.nextUInt32 ();
  338. const uint32_t clipCount = reader.nextUInt32 ();
  339. constexpr uint32_t maxPlausibleClipCount = 64;
  340. if (clipCount > maxPlausibleClipCount) {
  341. sLog.error ("Puppet animation clip count (", clipCount, ") looks implausible, skipping animation entirely");
  342. return {};
  343. }
  344. std::vector<PuppetAnimationClip> clips;
  345. clips.reserve (clipCount);
  346. for (uint32_t clipIndex = 0; clipIndex < clipCount; clipIndex++) {
  347. PuppetAnimationClip clip;
  348. reader.next (reinterpret_cast<char*> (&clip.id), sizeof (clip.id));
  349. clip.name = reader.nextNullTerminatedString ();
  350. clip.mode = reader.nextNullTerminatedString ();
  351. clip.fps = reader.nextFloat ();
  352. clip.frameCount = reader.nextUInt32 ();
  353. const uint32_t flags = reader.nextUInt32 ();
  354. const uint32_t boneCount = reader.nextUInt32 ();
  355. constexpr uint32_t maxPlausibleFrameCount = 100000;
  356. if (clip.frameCount > maxPlausibleFrameCount || boneCount != expectedBoneCount) {
  357. sLog.error (
  358. "Puppet animation clip ", clipIndex, " has an implausible frame/bone count (frames=", clip.frameCount,
  359. ", bones=", boneCount, ", expected ", expectedBoneCount, "), stopping here"
  360. );
  361. break;
  362. }
  363. const uint32_t sampleCount = clip.frameCount + 1;
  364. bool valid = true;
  365. // every track is a length-prefixed block of one value (or one 9-float transform) per sample
  366. const auto skipTrack = [&] (uint32_t sampleBytes) {
  367. const uint32_t trackBytes = reader.nextUInt32 ();
  368. if (trackBytes != sampleCount * sampleBytes) {
  369. valid = false;
  370. return;
  371. }
  372. reader.base ().seekg (static_cast<std::streamoff> (trackBytes), std::ios::cur);
  373. };
  374. const auto skipFlaggedTracks = [&] (uint32_t count, uint32_t sampleBytes) {
  375. for (uint32_t i = 0; i < count && valid; i++) {
  376. (void)reader.nextUInt32 ();
  377. skipTrack (sampleBytes);
  378. }
  379. };
  380. clip.boneTracks.resize (boneCount);
  381. clip.boneAnimated.assign (boneCount, true);
  382. for (uint32_t boneIndex = 0; boneIndex < boneCount && valid; boneIndex++) {
  383. // bit 0 keeps the bone out of this clip, the blend masks it (2.8.42 sub_140261880)
  384. clip.boneAnimated[boneIndex] = (reader.nextUInt32 () & 1) == 0;
  385. const uint32_t trackBytes = reader.nextUInt32 ();
  386. if (trackBytes != sampleCount * 9 * sizeof (float)) {
  387. valid = false;
  388. break;
  389. }
  390. auto& track = clip.boneTracks[boneIndex];
  391. track.reserve (sampleCount);
  392. for (uint32_t sample = 0; sample < sampleCount; sample++) {
  393. PuppetKeyframe keyframe;
  394. keyframe.position = { reader.nextFloat (), reader.nextFloat (), reader.nextFloat () };
  395. keyframe.rotation = { reader.nextFloat (), reader.nextFloat (), reader.nextFloat () };
  396. keyframe.scale = { reader.nextFloat (), reader.nextFloat (), reader.nextFloat () };
  397. // the loader turns the euler angles into a quaternion right away, same order as the matrices
  398. keyframe.orientation = glm::angleAxis (keyframe.rotation.z, glm::vec3 (0.0f, 0.0f, 1.0f))
  399. * glm::angleAxis (keyframe.rotation.y, glm::vec3 (0.0f, 1.0f, 0.0f))
  400. * glm::angleAxis (keyframe.rotation.x, glm::vec3 (1.0f, 0.0f, 0.0f));
  401. track.push_back (keyframe);
  402. }
  403. }
  404. if (version >= 2) {
  405. skipFlaggedTracks (rig.extraCount, 9 * sizeof (float));
  406. skipFlaggedTracks (rig.constraintCount, sizeof (float));
  407. }
  408. if (version >= 3 && valid) {
  409. skipFlaggedTracks (reader.nextUInt32 (), sizeof (float));
  410. if (valid && reader.next () != 0) {
  411. skipFlaggedTracks (boneCount, sizeof (float));
  412. }
  413. }
  414. // per mesh morph weight tracks: a u32 whose bit 0 enables them, a u32, a u16 count and per track the target
  415. // and its samples
  416. if (version >= 4 && valid && reader.next () != 0) {
  417. clip.morphTracks.resize (meshCount);
  418. for (uint32_t mesh = 0; mesh < meshCount && valid; mesh++) {
  419. if ((reader.nextUInt32 () & 1) == 0) {
  420. continue;
  421. }
  422. auto& meshTracks = clip.morphTracks[mesh];
  423. meshTracks.enabled = true;
  424. (void)reader.nextUInt32 ();
  425. uint16_t count = 0;
  426. reader.next (reinterpret_cast<char*> (&count), sizeof (count));
  427. for (uint16_t i = 0; i < count && valid; i++) {
  428. PuppetAnimationClip::MorphTrack track;
  429. reader.next (reinterpret_cast<char*> (&track.target), sizeof (track.target));
  430. const uint32_t trackBytes = reader.nextUInt32 ();
  431. if (trackBytes != sampleCount * sizeof (float)) {
  432. valid = false;
  433. break;
  434. }
  435. track.samples.resize (sampleCount);
  436. for (float& sample : track.samples) {
  437. sample = reader.nextFloat ();
  438. }
  439. meshTracks.tracks.push_back (std::move (track));
  440. }
  441. }
  442. }
  443. if (version >= 5 && valid) {
  444. reader.base ().seekg (sizeof (uint32_t) * 6, std::ios::cur);
  445. }
  446. if (version >= 6 && valid && reader.next () != 0) {
  447. skipFlaggedTracks (boneCount, sizeof (float));
  448. }
  449. if ((flags & 1) && valid) {
  450. reader.base ().seekg (sizeof (uint16_t) + sizeof (uint32_t) * 4, std::ios::cur);
  451. }
  452. if (valid) {
  453. const uint32_t eventCount = reader.nextUInt32 ();
  454. for (uint32_t i = 0; i < eventCount && reader.base ().good (); i++) {
  455. (void)reader.nextUInt32 (); // frame
  456. (void)reader.nextNullTerminatedString ();
  457. }
  458. }
  459. if (!valid || !reader.base ().good ()) {
  460. reader.base ().clear ();
  461. sLog.error ("Puppet animation clip ", clip.name, " doesn't match the MDLA layout, stopping here");
  462. if (!valid) {
  463. break;
  464. }
  465. }
  466. clips.push_back (std::move (clip));
  467. }
  468. if (clips.size () == clipCount && static_cast<size_t> (reader.base ().tellg ()) != sectionEnd) {
  469. sLog.error (
  470. "Puppet MDLA clips end at ", static_cast<size_t> (reader.base ().tellg ()), " but the section ends at ",
  471. sectionEnd
  472. );
  473. }
  474. return clips;
  475. }
  476. glm::vec3 lerp (const glm::vec3& a, const glm::vec3& b, float alpha) { return a + (b - a) * alpha; }
  477. } // namespace
  478. void PuppetRig::clear () {
  479. *this = PuppetRig ();
  480. }
  481. void PuppetRig::load (const std::vector<char>& data, size_t mdlsOffset, uint32_t meshCount, const std::string& name) {
  482. this->clear ();
  483. auto buffer = std::make_unique<char[]> (data.size ());
  484. std::copy (data.begin (), data.end (), buffer.get ());
  485. const BinaryReader reader (std::make_shared<MemoryStream> (std::move (buffer), data.size ()));
  486. auto boneSet = parsePuppetBones (reader, mdlsOffset);
  487. std::vector<int> bindParents (boneSet.bones.size ());
  488. std::vector<glm::mat4> bindLocals (boneSet.bones.size ());
  489. for (size_t i = 0; i < boneSet.bones.size (); i++) {
  490. bindParents[i] = boneSet.bones[i].parent;
  491. bindLocals[i] = boneSet.bones[i].bindLocal;
  492. }
  493. const std::vector<glm::mat4> worldBind = composeBoneWorldTransforms (bindParents, bindLocals);
  494. for (size_t i = 0; i < boneSet.bones.size (); i++) {
  495. boneSet.bones[i].inverseBindWorld = glm::inverse (worldBind[i]);
  496. }
  497. this->bones = std::move (boneSet.bones);
  498. this->boneModel = worldBind;
  499. this->physicsState.assign (this->bones.size (), {});
  500. this->hasPhysics
  501. = std::ranges::any_of (this->bones, [] (const PuppetBone& bone) { return bone.physics.simulated (); });
  502. // sub_140261880 walks the sections after MDLS in whatever order they come: every one is "TAGnnnn\0" and the absolute
  503. // offset of the next one, an empty tag or the end of the file ends it. MDAT holds attachment points, MDMP morph
  504. // targets (read by the model), MDLA the clips
  505. size_t offset = boneSet.nextSectionOffset;
  506. std::set<size_t> visited;
  507. while (offset + 13 <= data.size () && data[offset] != 0 && visited.insert (offset).second) {
  508. const std::string tag (data.data () + offset, 4);
  509. uint32_t next = 0;
  510. std::memcpy (&next, data.data () + offset + 9, sizeof (next));
  511. if (tag == "MDAT") {
  512. auto attachmentSet = parsePuppetAttachmentPoints (reader, offset, static_cast<uint32_t> (this->bones.size ()));
  513. this->attachmentPoints = std::move (attachmentSet.points);
  514. } else if (tag == "MDMP") {
  515. this->morphSection = offset;
  516. } else if (tag == "MDLA") {
  517. this->clips
  518. = parsePuppetAnimationClips (reader, offset, static_cast<uint32_t> (this->bones.size ()), boneSet, meshCount);
  519. }
  520. if (next <= offset) {
  521. sLog.error ("Section ", tag, " of ", name, " doesn't point past itself, the sections after it are skipped");
  522. break;
  523. }
  524. offset = next;
  525. }
  526. if (!this->attachmentPoints.empty ()) {
  527. std::string names;
  528. for (const auto& point : this->attachmentPoints) {
  529. names += (names.empty () ? "" : ", ") + point.name;
  530. }
  531. sLog.out ("Found ", this->attachmentPoints.size (), " attachment point(s) on ", name, ": ", names);
  532. }
  533. }
  534. void PuppetRig::addSceneLayers (const std::vector<ImageAnimationLayerUniquePtr>& sceneLayers) {
  535. // a layer plays the clip whose id is its "animation" value, layers without a match are dropped (2.8.42
  536. // sub_1401FCC20); layer and clip names don't have to agree (3521337568's "j" plays "动画 1")
  537. for (size_t index = 0; index < sceneLayers.size (); index++) {
  538. this->addLayer (*sceneLayers[index], nullptr, index, false);
  539. }
  540. this->nextLayerSerial = sceneLayers.size ();
  541. for (const auto& active : this->layers) {
  542. sLog.out (
  543. "Playing animation ", active.clip.name, " (", active.clip.mode, ", ", active.clip.fps, " fps, ",
  544. active.clip.frameCount, " frames)"
  545. );
  546. }
  547. }
  548. std::vector<glm::mat4> PuppetRig::skinMatrices () const {
  549. std::vector<glm::mat4> skin (this->bones.size ());
  550. for (size_t i = 0; i < this->bones.size (); i++) {
  551. skin[i] = (i < this->boneModel.size () ? this->boneModel[i] : glm::mat4 (1.0f)) * this->bones[i].inverseBindWorld;
  552. }
  553. return skin;
  554. }
  555. PuppetActiveAnimation* PuppetRig::findLayer (size_t serial) {
  556. const auto it = std::ranges::find (this->layers, serial, &PuppetActiveAnimation::serial);
  557. return it == this->layers.end () ? nullptr : &*it;
  558. }
  559. // sub_1401FCC20: the layer plays the clip whose id is its "animation", without one it isn't created. autosort puts it
  560. // after the last non-additive layer, "index" at that position (never past the last one), otherwise it goes last
  561. bool PuppetRig::addLayer (
  562. const ImageAnimationLayer& layer, ImageAnimationLayerUniquePtr owned, size_t serial, bool autoRemove
  563. ) {
  564. if (!layer.animation) {
  565. return false;
  566. }
  567. const auto id = static_cast<uint64_t> (layer.animation->value->getInt ());
  568. const auto match = std::ranges::find (this->clips, id, &PuppetAnimationClip::id);
  569. if (match == this->clips.end ()) {
  570. return false;
  571. }
  572. // sub_1401A8C10: "mirror" sets flag 1, "single" flag 2, anything else loops; starts at 0, playing
  573. uint32_t flags = 0;
  574. if (strcasecmp (match->mode.c_str (), "mirror") == 0) {
  575. flags |= PuppetClockMirror;
  576. } else if (strcasecmp (match->mode.c_str (), "single") == 0) {
  577. flags |= PuppetClockSingle;
  578. }
  579. PuppetActiveAnimation entry {
  580. .clip = *match,
  581. .layer = &layer,
  582. .ownedLayer = std::move (owned),
  583. .serial = serial,
  584. .blendIn = layer.blendIn,
  585. // only a clip that stops on its end fades out
  586. .blendOut = layer.blendOut && (flags & PuppetClockSingle) != 0,
  587. .autoRemove = autoRemove,
  588. .flags = flags,
  589. };
  590. auto& list = this->layers;
  591. auto position = list.end ();
  592. if (layer.autosort) {
  593. position = std::find_if (list.rbegin (), list.rend (), [] (const PuppetActiveAnimation& other) {
  594. return !other.layer->additive;
  595. }).base ();
  596. } else if (layer.index.has_value () && !list.empty ()) {
  597. const auto index = std::clamp<int64_t> (*layer.index, 0, static_cast<int64_t> (list.size ()) - 1);
  598. position = list.begin () + index;
  599. }
  600. list.insert (position, std::move (entry));
  601. return true;
  602. }
  603. size_t PuppetRig::getLayerCount () const { return this->layers.size (); }
  604. std::optional<size_t> PuppetRig::getLayerAt (int64_t index) const {
  605. if (index < 0 || index >= static_cast<int64_t> (this->layers.size ())) {
  606. return std::nullopt;
  607. }
  608. return this->layers[static_cast<size_t> (index)].serial;
  609. }
  610. std::optional<size_t> PuppetRig::findLayerByName (const std::string& name) const {
  611. // sub_14020E910 keeps the last layer with that name
  612. std::optional<size_t> result = std::nullopt;
  613. if (name.empty ()) {
  614. return result;
  615. }
  616. for (const auto& layer : this->layers) {
  617. if (layer.layer->name == name) {
  618. result = layer.serial;
  619. }
  620. }
  621. return result;
  622. }
  623. // sub_14020EA30: a config without blendin/blendout fades both ways. A clip name looks the clip up by name and puts its
  624. // id into the config, an object is the layer JSON itself with the config's keys written over it
  625. std::optional<size_t> PuppetRig::createLayer (
  626. const Data::JSON::JSON& animation, const Data::JSON::JSON& config, bool autoRemove, const Project& project
  627. ) {
  628. if (this->clips.empty ()) {
  629. return std::nullopt;
  630. }
  631. auto settings = config.is_object () ? config : Data::JSON::JSON::object ();
  632. if (!settings.contains ("blendin")) {
  633. settings["blendin"] = true;
  634. }
  635. if (!settings.contains ("blendout")) {
  636. settings["blendout"] = true;
  637. }
  638. Data::JSON::JSON layerJson;
  639. if (animation.is_string ()) {
  640. const auto name = animation.get<std::string> ();
  641. const auto clip = std::ranges::find (this->clips, name, &PuppetAnimationClip::name);
  642. if (name.empty () || clip == this->clips.end () || clip->id == 0) {
  643. return std::nullopt;
  644. }
  645. layerJson = std::move (settings);
  646. layerJson["animation"] = clip->id;
  647. } else if (animation.is_object ()) {
  648. layerJson = animation;
  649. for (const auto& [key, value] : settings.items ()) {
  650. layerJson[key] = value;
  651. }
  652. } else {
  653. return std::nullopt;
  654. }
  655. if (!layerJson.contains ("animation") || !layerJson["animation"].is_number ()) {
  656. return std::nullopt;
  657. }
  658. const size_t serial = this->nextLayerSerial++;
  659. // sub_1401A38F0 hands out a fresh id when the config has none
  660. if (!layerJson.contains ("id") || !layerJson["id"].is_number ()) {
  661. layerJson["id"] = static_cast<int> (serial);
  662. }
  663. ImageAnimationLayerUniquePtr owned;
  664. try {
  665. owned = ObjectParser::parseAnimationLayer (layerJson, project);
  666. } catch (const std::exception& ex) {
  667. sLog.error ("createAnimationLayer: invalid layer config: ", ex.what ());
  668. return std::nullopt;
  669. }
  670. const auto& layer = *owned;
  671. if (!this->addLayer (layer, std::move (owned), serial, autoRemove)) {
  672. return std::nullopt;
  673. }
  674. return serial;
  675. }
  676. bool PuppetRig::destroyLayersByName (const std::string& name) {
  677. if (name.empty ()) {
  678. return false;
  679. }
  680. return std::erase_if (this->layers, [&name] (const PuppetActiveAnimation& layer) {
  681. return layer.layer->name == name;
  682. })
  683. > 0;
  684. }
  685. bool PuppetRig::destroyLayer (size_t serial) {
  686. return std::erase_if (this->layers, [serial] (const PuppetActiveAnimation& layer) {
  687. return layer.serial == serial;
  688. })
  689. > 0;
  690. }
  691. // sub_1401FDF90, after the pose: a layer that ended runs its ended callbacks, a playSingleAnimation() one is removed
  692. void PuppetRig::finishEndedLayers (const std::function<void (size_t)>& dispatch) {
  693. std::vector<size_t> ended;
  694. for (const auto& layer : this->layers) {
  695. if (layer.ended) {
  696. ended.push_back (layer.serial);
  697. }
  698. }
  699. // callbacks may create or destroy layers, so layers are looked up again by serial
  700. for (const size_t serial : ended) {
  701. dispatch (serial);
  702. }
  703. std::erase_if (this->layers, [&ended] (const PuppetActiveAnimation& layer) {
  704. return layer.autoRemove && std::ranges::find (ended, layer.serial) != ended.end ();
  705. });
  706. }
  707. void PuppetRig::updateMorphWeights (const std::vector<PuppetLayerSample>& samples) {
  708. // sub_14021C480: every mesh's weights start at zero each frame, then the layers apply theirs in order. A layer at
  709. // full weight sets them (a weight of about 0 switches the target off), additive ones add theirs kept between
  710. // the two values, the others blend towards theirs and clamp to 0..1. Layers at zero weight are skipped
  711. for (auto& mesh : this->morphWeights) {
  712. mesh.active = 0;
  713. std::ranges::fill (mesh.weights, 0.0f);
  714. }
  715. constexpr float epsilon = 1.1920929e-7f;
  716. for (const auto& sample : samples) {
  717. if (sample.weight == 0.0f) {
  718. continue;
  719. }
  720. const bool direct = sample.weight == 1.0f && !sample.additive;
  721. const auto& meshes = sample.clip->morphTracks;
  722. if (this->morphWeights.size () < meshes.size ()) {
  723. this->morphWeights.resize (meshes.size ());
  724. }
  725. for (size_t mesh = 0; mesh < meshes.size (); mesh++) {
  726. if (!meshes[mesh].enabled) {
  727. continue;
  728. }
  729. auto& state = this->morphWeights[mesh];
  730. for (const auto& track : meshes[mesh].tracks) {
  731. if (track.target >= 64 || track.samples.size () <= sample.frame1) {
  732. continue;
  733. }
  734. if (state.weights.size () <= track.target) {
  735. state.weights.resize (track.target + 1, 0.0f);
  736. }
  737. const float value = (1.0f - sample.alpha) * track.samples[sample.frame0] + sample.alpha * track.samples[sample.frame1];
  738. const uint64_t bit = uint64_t (1) << track.target;
  739. float& weight = state.weights[track.target];
  740. if (direct) {
  741. if (std::abs (value) < epsilon) {
  742. state.active &= ~bit;
  743. } else {
  744. state.active |= bit;
  745. weight = value;
  746. }
  747. } else if (sample.additive) {
  748. if (std::abs (value) >= epsilon) {
  749. const float added = value * sample.weight;
  750. state.active |= bit;
  751. weight = std::clamp (weight + added, std::min (weight, added), std::max (weight, added));
  752. }
  753. } else {
  754. if (std::abs (value) >= epsilon) {
  755. state.active |= bit;
  756. }
  757. weight = std::clamp ((1.0f - sample.weight) * weight + sample.weight * value, 0.0f, 1.0f);
  758. }
  759. }
  760. }
  761. }
  762. }
  763. void PuppetRig::updatePose (const glm::mat4& objectWorld) {
  764. if (this->bones.empty ()) {
  765. return;
  766. }
  767. // WE's layer blend (2.8.42 sub_1401FDF90): each bone starts from its rest pose (the MDLS bind matrix as
  768. // position, rotation and scale) and every visible layer in order blends towards its clip's sample
  769. // (sub_1401F9020) or, when additive, adds the sample's difference from the rest pose (sub_1401F9820).
  770. // Bones whose track is flagged off in a clip keep what they have.
  771. // every layer runs its own clock, stepped by dt * rate while the layer is visible (sub_1401FDF90)
  772. const float dt = this->clockTime < 0.0f ? 0.0f : std::max (g_Time - this->clockTime, 0.0f);
  773. this->clockTime = g_Time;
  774. std::vector<PuppetLayerSample> samples;
  775. for (auto& candidate : this->layers) {
  776. candidate.ended = false;
  777. if (candidate.layer == nullptr || !candidate.layer->visible->value->getBool ()) {
  778. continue;
  779. }
  780. const auto& clip = candidate.clip;
  781. if (clip.fps <= 0.0f || clip.frameCount == 0) {
  782. continue;
  783. }
  784. const float frameTime = 1.0f / clip.fps;
  785. const float duration = static_cast<float> (clip.frameCount) * frameTime;
  786. const uint32_t previousFlags = candidate.flags;
  787. const float previousTime = candidate.time;
  788. stepPuppetClock (candidate, duration, dt * candidate.layer->rate->value->getFloat ());
  789. // a layer ends when a single clip stops, a mirror turns around or a loop wraps, unless it was paused, stopped
  790. // or moved by setFrame() since the last step
  791. if ((previousFlags & (PuppetClockFrameSet | PuppetClockPaused | PuppetClockStopped)) == 0) {
  792. if ((candidate.flags & PuppetClockSingle) != 0) {
  793. candidate.ended = (candidate.flags & PuppetClockStopped) != 0;
  794. } else if ((candidate.flags & PuppetClockMirror) != 0) {
  795. candidate.ended = (previousFlags & PuppetClockBackwards) != (candidate.flags & PuppetClockBackwards);
  796. } else {
  797. candidate.ended = previousTime > candidate.time;
  798. }
  799. }
  800. candidate.flags &= ~PuppetClockFrameSet;
  801. const float time = candidate.time;
  802. // sub_140170580
  803. const int lastFrame = static_cast<int> (clip.frameCount) - 1;
  804. const int frame0 = std::clamp (static_cast<int> (time / frameTime), 0, lastFrame);
  805. samples.push_back (
  806. PuppetLayerSample { .clip = &clip,
  807. .frame0 = static_cast<uint32_t> (frame0),
  808. .frame1 = std::min (static_cast<uint32_t> (frame0 + 1), clip.frameCount),
  809. .alpha = std::fmod (time, frameTime) / frameTime,
  810. .weight = puppetLayerWeight (candidate, duration),
  811. .additive = candidate.layer->additive }
  812. );
  813. }
  814. this->poseAnimated = !samples.empty () || this->hasPhysics || this->poseScripted;
  815. // q and -q are the same rotation, blends take the one on the same side
  816. const auto nlerp = [] (const glm::quat& a, glm::quat b, float t) {
  817. if (glm::dot (a, b) < 0.0f) {
  818. b = -b;
  819. }
  820. return glm::normalize (a * (1.0f - t) + b * t);
  821. };
  822. std::vector<int> animatedParents (this->bones.size ());
  823. std::vector<glm::mat4> animatedLocals (this->bones.size ());
  824. for (size_t i = 0; i < this->bones.size (); i++) {
  825. const auto& bone = this->bones[i];
  826. animatedParents[i] = bone.parent;
  827. // no animation layer playing, physics runs on the bind pose like WE
  828. if (samples.empty ()) {
  829. animatedLocals[i] = bone.bindLocal;
  830. continue;
  831. }
  832. const glm::vec3 restPosition (bone.bindLocal[3]);
  833. const glm::vec3 restScale (
  834. glm::length (glm::vec3 (bone.bindLocal[0])), glm::length (glm::vec3 (bone.bindLocal[1])),
  835. glm::length (glm::vec3 (bone.bindLocal[2]))
  836. );
  837. const glm::quat restOrientation = glm::normalize (glm::quat_cast (glm::mat3 (
  838. glm::vec3 (bone.bindLocal[0]) / restScale.x, glm::vec3 (bone.bindLocal[1]) / restScale.y,
  839. glm::vec3 (bone.bindLocal[2]) / restScale.z
  840. )));
  841. glm::vec3 position = restPosition;
  842. glm::vec3 scale = restScale;
  843. glm::quat orientation = restOrientation;
  844. for (const auto& sample : samples) {
  845. const auto& clip = *sample.clip;
  846. if (i >= clip.boneTracks.size () || clip.boneTracks[i].size () <= sample.frame1
  847. || (i < clip.boneAnimated.size () && !clip.boneAnimated[i])) {
  848. continue;
  849. }
  850. const auto& from = clip.boneTracks[i][sample.frame0];
  851. const auto& to = clip.boneTracks[i][sample.frame1];
  852. const glm::vec3 samplePosition = lerp (from.position, to.position, sample.alpha);
  853. const glm::vec3 sampleScale = lerp (from.scale, to.scale, sample.alpha);
  854. const glm::quat sampleOrientation = nlerp (from.orientation, to.orientation, sample.alpha);
  855. const float weight = sample.weight;
  856. if (sample.additive) {
  857. position += (samplePosition - restPosition) * weight;
  858. scale += (sampleScale - restScale) * weight;
  859. const glm::quat delta = glm::conjugate (restOrientation) * sampleOrientation;
  860. orientation = orientation * nlerp (glm::quat (1.0f, 0.0f, 0.0f, 0.0f), delta, weight);
  861. } else {
  862. position = position * (1.0f - weight) + samplePosition * weight;
  863. scale = scale * (1.0f - weight) + sampleScale * weight;
  864. orientation = nlerp (orientation, sampleOrientation, weight);
  865. }
  866. }
  867. animatedLocals[i] = glm::translate (glm::mat4 (1.0f), position) * glm::mat4_cast (orientation)
  868. * glm::scale (glm::mat4 (1.0f), scale);
  869. }
  870. this->composePose (animatedParents, animatedLocals, objectWorld);
  871. this->updateMorphWeights (samples);
  872. }
  873. void PuppetRig::composePose (
  874. const std::vector<int>& parents, const std::vector<glm::mat4>& locals, const glm::mat4& objectWorld
  875. ) {
  876. const size_t count = parents.size ();
  877. const float dt = std::max (g_Time - g_TimeLast, 0.0f);
  878. // sub_1401FDF90 swaps the current and previous scene matrices first, so whatever a script wrote into the current
  879. // ones last frame is what the physics compares against
  880. const bool hasPrevious = this->boneScene.size () == count;
  881. if (hasPrevious) {
  882. this->physicsPreviousScene = this->boneScene;
  883. }
  884. // WE runs the physics on the bones' scene transforms (object world * bone)
  885. const glm::mat4& object = objectWorld;
  886. const float objectScale
  887. = (glm::length (glm::vec3 (object[0])) + glm::length (glm::vec3 (object[1])) + glm::length (glm::vec3 (object[2])))
  888. / 3.0f;
  889. std::vector<glm::mat4> model (count);
  890. std::vector<glm::mat4> scene (count);
  891. std::vector<uint8_t> resolved (count, 0);
  892. // parents first, a simulated parent moves its children
  893. const auto resolve = [&] (const auto& self, size_t index) -> void {
  894. if (resolved[index] != 0) {
  895. return;
  896. }
  897. resolved[index] = 1;
  898. const int parent = parents[index];
  899. if (parent >= 0 && static_cast<size_t> (parent) < count && resolved[parent] != 1) {
  900. self (self, static_cast<size_t> (parent));
  901. model[index] = model[parent] * locals[index];
  902. } else {
  903. model[index] = locals[index];
  904. }
  905. scene[index] = object * model[index];
  906. const auto& physics = this->bones[index].physics;
  907. // the first frame has nothing to compare against and only records where the bones are
  908. if (physics.simulated () && hasPrevious) {
  909. model[index] = model[index]
  910. * stepPuppetBonePhysics (
  911. physics, this->physicsState[index], scene[index],
  912. this->physicsPreviousScene[index], dt, objectScale
  913. );
  914. scene[index] = object * model[index];
  915. }
  916. resolved[index] = 2;
  917. };
  918. for (size_t i = 0; i < count; i++) {
  919. resolve (resolve, i);
  920. }
  921. this->boneLocal = locals;
  922. this->boneModel = std::move (model);
  923. this->boneScene = std::move (scene);
  924. }
  925. bool PuppetRig::hasPose () const {
  926. return !this->bones.empty () && this->boneScene.size () == this->bones.size ();
  927. }
  928. int PuppetRig::findBone (const std::string& name) const {
  929. for (size_t i = 0; i < this->bones.size (); i++) {
  930. if (this->bones[i].name == name) {
  931. return static_cast<int> (i);
  932. }
  933. }
  934. return -1;
  935. }
  936. const glm::mat4& PuppetRig::getBoneTransform (int bone) const { return this->boneScene[bone]; }
  937. void PuppetRig::setBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld) {
  938. // sub_14020F350: only this bone, its children keep their matrices until the next update
  939. this->boneScene[bone] = transform;
  940. this->boneModel[bone] = glm::inverse (objectWorld) * transform;
  941. this->poseScripted = true;
  942. this->poseAnimated = true;
  943. }
  944. const glm::mat4& PuppetRig::getLocalBoneTransform (int bone) const { return this->boneLocal[bone]; }
  945. void PuppetRig::setLocalBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld) {
  946. this->boneLocal[bone] = transform;
  947. // sub_14020DB40: the bone and every later bone whose parent was touched, in index order
  948. const glm::mat4& object = objectWorld;
  949. std::set<int> touched;
  950. const int count = static_cast<int> (this->bones.size ());
  951. for (int index = bone; index < count; index++) {
  952. const int parent = this->bones[index].parent;
  953. if (index != bone && !touched.contains (parent)) {
  954. continue;
  955. }
  956. touched.insert (index);
  957. this->boneModel[index] = parent < 0 || parent >= count
  958. ? this->boneLocal[index]
  959. : this->boneModel[parent] * this->boneLocal[index];
  960. this->boneScene[index] = object * this->boneModel[index];
  961. }
  962. this->poseScripted = true;
  963. this->poseAnimated = true;
  964. }
  965. void PuppetRig::applyBonePhysicsImpulse (int bone, const glm::vec3& directional, const glm::vec3& angularDegrees) {
  966. if (bone >= 0 && static_cast<size_t> (bone) < this->physicsState.size ()) {
  967. applyPuppetBoneImpulse (this->physicsState[bone], directional, angularDegrees);
  968. }
  969. }
  970. void PuppetRig::resetBonePhysics (int bone) {
  971. // sub_140210E10
  972. if (bone >= 0 && static_cast<size_t> (bone) < this->physicsState.size ()) {
  973. this->physicsState[bone] = {};
  974. }
  975. }