PuppetRig.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. #pragma once
  2. #include "PuppetIK.h"
  3. #include "PuppetPhysics.h"
  4. #include "PuppetRootMotion.h"
  5. #include "WallpaperEngine/Data/JSON.h"
  6. #include "WallpaperEngine/Data/Model/Object.h"
  7. #include <array>
  8. #include <functional>
  9. #include <optional>
  10. #include <string>
  11. #include <vector>
  12. #include <glm/glm.hpp>
  13. #include <glm/gtc/quaternion.hpp>
  14. namespace WallpaperEngine::Data::Model {
  15. struct Project;
  16. }
  17. namespace WallpaperEngine::Render::Objects {
  18. /** A skeleton bone, parsed from the MDLS section of a .mdl */
  19. struct PuppetBone {
  20. std::string name;
  21. int parent = -1;
  22. /** Local bind-pose transform, relative to the parent bone (identity for a root bone's "world" reference) */
  23. glm::mat4 bindLocal { 1.0f };
  24. /** Local rest pose, where animation and physics start from: MDLS's optional second matrix array, else bindLocal */
  25. glm::mat4 restLocal { 1.0f };
  26. /** Inverse of the bone's bind-pose world transform, derived by walking the parent chain */
  27. glm::mat4 inverseBindWorld { 1.0f };
  28. PuppetBonePhysics physics {};
  29. /** MDLS type, bit 2: posed by the IK solver */
  30. uint32_t type = 0;
  31. PuppetBoneIK ik {};
  32. /** blend rules (bone +216) */
  33. std::vector<PuppetConstraintRule> rules;
  34. /** IK chain this bone starts (bone +212) */
  35. int chain = -1;
  36. /** The bone's collision capsule (MDLS, what collisionmodel particles hit): extents, and its frame in bone space */
  37. bool hasCapsule = false;
  38. glm::vec3 capsuleExtents { 0.0f };
  39. glm::mat4 capsule { 1.0f };
  40. };
  41. /** MDLS v2+ extra: type 0 IK target, 1 pole */
  42. struct PuppetExtra {
  43. uint32_t bone = 0;
  44. uint32_t type = 0;
  45. glm::mat4 restLocal { 1.0f };
  46. };
  47. /** A single sampled TRS pose for one bone at one point in time, from the MDLA section */
  48. struct PuppetKeyframe {
  49. glm::vec3 position {};
  50. glm::vec3 rotation {};
  51. glm::vec3 scale { 1.0f };
  52. /** rotation as WE blends it, Rz * Ry * Rx */
  53. glm::quat orientation { 1.0f, 0.0f, 0.0f, 0.0f };
  54. };
  55. /** MDLA clip event, time in seconds (sub_1401A9F60) */
  56. struct PuppetClipEvent {
  57. float time = 0.0f;
  58. std::string payload;
  59. };
  60. /** A baked animation clip: one keyframe track per bone, sampled at a fixed rate */
  61. struct PuppetAnimationClip {
  62. /** what animationlayers[].animation refers to */
  63. uint64_t id = 0;
  64. std::string name;
  65. std::string mode;
  66. float fps = 30.0f;
  67. uint32_t frameCount = 0;
  68. /** [boneIndex][sampleIndex], each track has frameCount+1 samples */
  69. std::vector<std::vector<PuppetKeyframe>> boneTracks;
  70. /** per bone, false when its track flags have bit 0 set: the clip leaves that bone alone */
  71. std::vector<bool> boneAnimated;
  72. /** per bone, the raw track flags; the float tracks below skip a bone when (flags & 3) == 1 */
  73. std::vector<uint32_t> boneFlags;
  74. /** MDLA v2, [extra][sample] */
  75. std::vector<std::vector<PuppetKeyframe>> extraTracks;
  76. std::vector<bool> extraAnimated;
  77. /** MDLA v6, [bone][sample]: what gets added to the parts' draw order of that bone (mesh flag 8) */
  78. std::vector<std::vector<float>> drawOrderTracks;
  79. /** MDLA v3, [bone][sample]: g_BonesAlpha */
  80. std::vector<std::vector<float>> boneAlphaTracks;
  81. /** MDLA v2, [constraint][sample]: blend rule weights, flags bit 0 skips */
  82. std::vector<std::vector<float>> constraintTracks;
  83. std::vector<uint32_t> constraintFlags;
  84. /** MDLA v3, [track][sample]: g_BlendMap */
  85. std::vector<std::vector<float>> blendTracks;
  86. /** clip +288 */
  87. std::vector<PuppetClipEvent> events;
  88. /** a morph target's weight over the clip, one sample per frame like the bone tracks */
  89. struct MorphTrack {
  90. uint16_t target = 0;
  91. std::vector<float> samples;
  92. };
  93. /** MDLA v4+, per mesh of the model: whether the clip drives its morph weights and the tracks doing it */
  94. struct MeshMorphTracks {
  95. bool enabled = false;
  96. std::vector<MorphTrack> tracks;
  97. };
  98. std::vector<MeshMorphTracks> morphTracks;
  99. /** the clip's flags: 1 has the record below, 0x400 the record refers to this clip itself, 0x800/0x1000/0x2000
  100. * root motion along x/y/z, 0x8000 root rotation (0x1F800 any root motion) */
  101. uint32_t flags = 0;
  102. /** flags & 1 (MDLA, sub_140261880): models play another clip's frames from frameStart on (sub_14021C480), and
  103. * root motion measures the root bone against two of its frames */
  104. struct RootMotion {
  105. uint16_t clip = 0;
  106. uint32_t frameStart = 0;
  107. uint32_t frameEnd = 0;
  108. uint32_t startOffset = 0;
  109. int bone = -1;
  110. /** with flags & 0x1F800 */
  111. PuppetRootMotionFrames frames;
  112. };
  113. std::optional<RootMotion> rootMotion;
  114. };
  115. /** One mesh's morph target weights this frame (WE model state +96: a bit per active target and the weights) */
  116. struct PuppetMorphWeights {
  117. uint64_t active = 0;
  118. std::vector<float> weights;
  119. };
  120. /** A named point on a puppet's rig that other objects can follow via scene.json's "attachment" field */
  121. struct PuppetAttachmentPoint {
  122. std::string name;
  123. int boneIndex = -1;
  124. /** Transform of the point relative to its bone, in the same convention as PuppetBone::bindLocal */
  125. glm::mat4 localTransform { 1.0f };
  126. };
  127. /** One of an object's animationlayers[] entries, paired with the baked clip it plays and its own clock (WE's layer
  128. * timeline, sub_1401A8C10 / sub_1401A9F60) */
  129. struct PuppetActiveAnimation {
  130. PuppetAnimationClip clip;
  131. const WallpaperEngine::Data::Model::ImageAnimationLayer* layer = nullptr;
  132. /** layers made by createAnimationLayer()/playSingleAnimation() own their settings */
  133. WallpaperEngine::Data::Model::ImageAnimationLayerUniquePtr ownedLayer = nullptr;
  134. /** stable handle for scripts: the index in the object's animationlayers[] for scene layers, counted on from
  135. * there for created ones */
  136. size_t serial = 0;
  137. /** fade flags (+208 bits 4 and 8), blendin drops once a non-single clip has faded in */
  138. bool blendIn = false;
  139. bool blendOut = false;
  140. /** playSingleAnimation(): removed once it ends (0x8000000) */
  141. bool autoRemove = false;
  142. /** seconds into the clip */
  143. float time = 0.0f;
  144. /** 1 mirror, 2 single, 0x2000000 frame set by a script, 0x20000000 paused, 0x40000000 stopped, sign bit mirror
  145. * playing backwards */
  146. uint32_t flags = 0;
  147. /** reached its end in this frame's update, for IAnimationLayer.addEndedCallback() */
  148. bool ended = false;
  149. PuppetRootMotionState rootMotion;
  150. };
  151. /** What root motion moves: a model object (sub_140225900 writes its origin +296 and angles +320) */
  152. class PuppetRootMotionHost {
  153. public:
  154. virtual ~PuppetRootMotionHost () = default;
  155. /** "rootmotion" (model +784) */
  156. [[nodiscard]] virtual bool rootMotionEnabled () const = 0;
  157. /** the object's current world matrix (vtable slot 16), after any move of this frame */
  158. [[nodiscard]] virtual glm::mat4 rootMotionWorld () const = 0;
  159. virtual void rootMotionMove (const glm::vec3& origin) = 0;
  160. [[nodiscard]] virtual glm::vec3 rootMotionAngles () const = 0;
  161. virtual void rootMotionTurn (const glm::vec3& angles) = 0;
  162. };
  163. /** A visible layer's place in its clip this frame: the two frames around it and how far between them */
  164. struct PuppetLayerSample {
  165. const PuppetAnimationClip* clip;
  166. uint32_t frame0;
  167. uint32_t frame1;
  168. float alpha;
  169. float weight;
  170. bool additive;
  171. };
  172. /** A bone in model space at a point of a clip, how WE's clip sampling builds it (sub_140267F00) */
  173. [[nodiscard]] glm::mat4 samplePuppetBoneChain (
  174. const std::vector<PuppetBone>& bones, const PuppetAnimationClip& clip, int bone, uint32_t frame0, uint32_t frame1,
  175. float alpha
  176. );
  177. /**
  178. * The skeleton, animation layers and bone physics of a puppet image or a 3D model. Both run the same pose update in
  179. * wallpaper64.exe 2.8.42 (images sub_1401FDF90, models sub_14021C480): every bone starts at its rest pose, visible
  180. * layers blend their clips in, physics runs on the bones' scene transforms
  181. */
  182. class PuppetRig {
  183. public:
  184. /** Reads MDLS at mdlsOffset and the MDAT/MDLA sections it leads to (sub_140261880). Throws on a broken file */
  185. void load (const std::vector<char>& data, size_t mdlsOffset, uint32_t meshCount, const std::string& name);
  186. void clear ();
  187. [[nodiscard]] PuppetActiveAnimation* findLayer (size_t serial);
  188. /** sub_1401FCC20: plays the clip whose id is the layer's "animation", false without one */
  189. bool addLayer (
  190. const Data::Model::ImageAnimationLayer& layer, Data::Model::ImageAnimationLayerUniquePtr owned, size_t serial,
  191. bool autoRemove
  192. );
  193. /** The object's animationlayers[], serials are their indices */
  194. void addSceneLayers (const std::vector<Data::Model::ImageAnimationLayerUniquePtr>& layers);
  195. [[nodiscard]] size_t getLayerCount () const;
  196. [[nodiscard]] std::optional<size_t> getLayerAt (int64_t index) const;
  197. [[nodiscard]] std::optional<size_t> findLayerByName (const std::string& name) const;
  198. std::optional<size_t> createLayer (
  199. const Data::JSON::JSON& animation, const Data::JSON::JSON& config, bool autoRemove,
  200. const Data::Model::Project& project
  201. );
  202. bool destroyLayersByName (const std::string& name);
  203. bool destroyLayer (size_t serial);
  204. /** Clip events fired this frame, in layer order */
  205. [[nodiscard]] std::vector<std::string> takeFiredEvents ();
  206. /** After the pose: every layer that ended runs dispatch (its ended callbacks), playSingleAnimation() ones go */
  207. void finishEndedLayers (const std::function<void (size_t)>& dispatch);
  208. /**
  209. * Steps the layer clocks and builds this frame's pose, objectWorld is the object's world matrix. Models pass
  210. * themselves as host: their clips can play another clip's frames and move the object by root motion
  211. */
  212. void updatePose (const glm::mat4& objectWorld, PuppetRootMotionHost* host = nullptr);
  213. void updateMorphWeights (const std::vector<PuppetLayerSample>& samples);
  214. /** sub_1401FDF90 for meshes with flag 8: every bone's draw order from MDLS, moved by the layers' v6 tracks */
  215. void updateDrawOrder (const std::vector<PuppetLayerSample>& samples);
  216. /** sub_1401FDF90, mesh flag 4 */
  217. void updateBoneAlpha (const std::vector<PuppetLayerSample>& samples);
  218. /** sub_1401FDF90, mesh flag 2 */
  219. void updateBlendMap (const std::vector<PuppetLayerSample>& samples);
  220. /** sub_1401FDF90 */
  221. void updateConstraintWeights (const std::vector<PuppetLayerSample>& samples);
  222. /** sub_140225900 for one model layer after its blend, rest is what the layers above leave of it */
  223. void applyRootMotion (
  224. PuppetActiveAnimation& layer, const PuppetLayerSample& sample, std::vector<glm::vec3>& positions,
  225. std::vector<glm::quat>& orientations, float rest, PuppetRootMotionHost& host
  226. );
  227. void
  228. composePose (const std::vector<int>& parents, const std::vector<glm::mat4>& locals, const glm::mat4& objectWorld);
  229. [[nodiscard]] bool hasPose () const;
  230. [[nodiscard]] int findBone (const std::string& name) const;
  231. /** First attachment point of that name, -1 without one (image/model vtable slot 14, sub_1401FD510/sub_1402248C0) */
  232. [[nodiscard]] int findAttachment (const std::string& name) const;
  233. /** An attachment point in model space, its bone's model matrix times the point (slot 15, sub_1401FD5C0/
  234. * sub_140224970); nothing for an index out of range or before the bones exist */
  235. [[nodiscard]] std::optional<glm::mat4> attachmentMatrix (int index) const;
  236. [[nodiscard]] const glm::mat4& getBoneTransform (int bone) const;
  237. void setBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld);
  238. [[nodiscard]] const glm::mat4& getLocalBoneTransform (int bone) const;
  239. void setLocalBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld);
  240. void applyBonePhysicsImpulse (int bone, const glm::vec3& directional, const glm::vec3& angularDegrees);
  241. void resetBonePhysics (int bone);
  242. /** model space bone matrices times the inverse bind ones, what the vertices are skinned with */
  243. [[nodiscard]] std::vector<glm::mat4> skinMatrices () const;
  244. /** Where the file's MDMP section (morph targets) starts, 0 without one */
  245. [[nodiscard]] size_t getMorphSection () const { return this->morphSection; }
  246. std::vector<PuppetBone> bones = {};
  247. std::vector<PuppetAnimationClip> clips = {};
  248. std::vector<PuppetAttachmentPoint> attachmentPoints = {};
  249. std::vector<PuppetActiveAnimation> layers = {};
  250. /** per mesh, rebuilt by every updatePose () (sub_14021C480) */
  251. std::vector<PuppetMorphWeights> morphWeights = {};
  252. /** models clamp blended layer weights to 0..1, images don't */
  253. bool morphBlendClamped = true;
  254. /** mesh flag 4, instance +616 */
  255. bool boneAlphaEnabled = false;
  256. std::vector<float> boneAlpha = {};
  257. /** instance +848, four g_BlendMap rows */
  258. std::array<float, 16> blendMap = {};
  259. size_t morphSection = 0;
  260. /** MDLS v3+ per bone order (instance +496), added to the order of every part of that bone */
  261. std::vector<int> boneDrawOrder = {};
  262. /** set by the image for a mesh with flag 8: the pose update then keeps drawOrder (instance +640) */
  263. bool drawOrderEnabled = false;
  264. std::vector<float> drawOrder = {};
  265. /** a layer wrote drawOrder this frame, the parts get sorted again */
  266. bool drawOrderTouched = false;
  267. std::vector<PuppetExtra> extras = {};
  268. PuppetIKRig ik = {};
  269. /** bind pose in model space (P+808) */
  270. std::vector<glm::mat4> bindModel = {};
  271. /** P+736 */
  272. std::vector<glm::mat4> extraModel = {};
  273. bool hasIK = false;
  274. /** the bones in model space (WE images P+712), starts at the bind pose */
  275. std::vector<glm::mat4> boneModel = {};
  276. /** this frame's local matrices (P+784) and scene matrices (P+832), empty until the first update */
  277. std::vector<glm::mat4> boneLocal = {};
  278. std::vector<glm::mat4> boneScene = {};
  279. /** Bone physics state and last frame's scene transforms, empty until the first frame */
  280. std::vector<PuppetBonePhysicsState> physicsState = {};
  281. std::vector<glm::mat4> physicsPreviousScene = {};
  282. /** P+952 */
  283. std::vector<PuppetRopeJoint> ropeJoints = {};
  284. /** puppet +592 */
  285. std::vector<float> constraintWeights = {};
  286. PuppetRopeEnvironment ropeEnvironment = {};
  287. bool hasPhysics = false;
  288. /** The rest pose isn't the bind pose, the mesh needs skinning even when nothing moves */
  289. bool hasRestPose = false;
  290. size_t nextLayerSerial = 0;
  291. std::vector<std::string> firedEvents = {};
  292. /** g_Time of the last clock step, so a scene drawn on several outputs steps once per frame */
  293. float clockTime = -1.0f;
  294. /** a script wrote bone matrices, the mesh has to be skinned from then on */
  295. bool poseScripted = false;
  296. /** the pose differs from the bind pose (animation, physics or scripts) */
  297. bool poseAnimated = false;
  298. };
  299. } // namespace WallpaperEngine::Render::Objects