PuppetRig.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. /** MDLA v5 clip box */
  89. glm::vec3 boundsMin = glm::vec3 (0.0f);
  90. glm::vec3 boundsMax = glm::vec3 (0.0f);
  91. /** a morph target's weight over the clip, one sample per frame like the bone tracks */
  92. struct MorphTrack {
  93. uint16_t target = 0;
  94. std::vector<float> samples;
  95. };
  96. /** MDLA v4+, per mesh of the model: whether the clip drives its morph weights and the tracks doing it */
  97. struct MeshMorphTracks {
  98. bool enabled = false;
  99. std::vector<MorphTrack> tracks;
  100. };
  101. std::vector<MeshMorphTracks> morphTracks;
  102. /** the clip's flags: 1 has the record below, 0x400 the record refers to this clip itself, 0x800/0x1000/0x2000
  103. * root motion along x/y/z, 0x8000 root rotation (0x1F800 any root motion) */
  104. uint32_t flags = 0;
  105. /** flags & 1 (MDLA, sub_140261880): models play another clip's frames from frameStart on (sub_14021C480), and
  106. * root motion measures the root bone against two of its frames */
  107. struct RootMotion {
  108. uint16_t clip = 0;
  109. uint32_t frameStart = 0;
  110. uint32_t frameEnd = 0;
  111. uint32_t startOffset = 0;
  112. int bone = -1;
  113. /** with flags & 0x1F800 */
  114. PuppetRootMotionFrames frames;
  115. };
  116. std::optional<RootMotion> rootMotion;
  117. };
  118. /** One mesh's morph target weights this frame (WE model state +96: a bit per active target and the weights) */
  119. struct PuppetMorphWeights {
  120. uint64_t active = 0;
  121. std::vector<float> weights;
  122. };
  123. /** A named point on a puppet's rig that other objects can follow via scene.json's "attachment" field */
  124. struct PuppetAttachmentPoint {
  125. std::string name;
  126. int boneIndex = -1;
  127. /** Transform of the point relative to its bone, in the same convention as PuppetBone::bindLocal */
  128. glm::mat4 localTransform { 1.0f };
  129. };
  130. /** One of an object's animationlayers[] entries, paired with the baked clip it plays and its own clock (WE's layer
  131. * timeline, sub_1401A8C10 / sub_1401A9F60) */
  132. struct PuppetActiveAnimation {
  133. PuppetAnimationClip clip;
  134. const WallpaperEngine::Data::Model::ImageAnimationLayer* layer = nullptr;
  135. /** layers made by createAnimationLayer()/playSingleAnimation() own their settings */
  136. WallpaperEngine::Data::Model::ImageAnimationLayerUniquePtr ownedLayer = nullptr;
  137. /** stable handle for scripts: the index in the object's animationlayers[] for scene layers, counted on from
  138. * there for created ones */
  139. size_t serial = 0;
  140. /** fade flags (+208 bits 4 and 8), blendin drops once a non-single clip has faded in */
  141. bool blendIn = false;
  142. bool blendOut = false;
  143. /** playSingleAnimation(): removed once it ends (0x8000000) */
  144. bool autoRemove = false;
  145. /** seconds into the clip */
  146. float time = 0.0f;
  147. /** 1 mirror, 2 single, 0x2000000 frame set by a script, 0x20000000 paused, 0x40000000 stopped, sign bit mirror
  148. * playing backwards */
  149. uint32_t flags = 0;
  150. /** reached its end in this frame's update, for IAnimationLayer.addEndedCallback() */
  151. bool ended = false;
  152. PuppetRootMotionState rootMotion;
  153. };
  154. /** What root motion moves: a model object (sub_140225900 writes its origin +296 and angles +320) */
  155. class PuppetRootMotionHost {
  156. public:
  157. virtual ~PuppetRootMotionHost () = default;
  158. /** "rootmotion" (model +784) */
  159. [[nodiscard]] virtual bool rootMotionEnabled () const = 0;
  160. /** the object's current world matrix (vtable slot 16), after any move of this frame */
  161. [[nodiscard]] virtual glm::mat4 rootMotionWorld () const = 0;
  162. virtual void rootMotionMove (const glm::vec3& origin) = 0;
  163. [[nodiscard]] virtual glm::vec3 rootMotionAngles () const = 0;
  164. virtual void rootMotionTurn (const glm::vec3& angles) = 0;
  165. };
  166. /** A visible layer's place in its clip this frame: the two frames around it and how far between them */
  167. struct PuppetLayerSample {
  168. const PuppetAnimationClip* clip;
  169. uint32_t frame0;
  170. uint32_t frame1;
  171. float alpha;
  172. float weight;
  173. bool additive;
  174. };
  175. /** A bone in model space at a point of a clip, how WE's clip sampling builds it (sub_140267F00) */
  176. [[nodiscard]] glm::mat4 samplePuppetBoneChain (
  177. const std::vector<PuppetBone>& bones, const PuppetAnimationClip& clip, int bone, uint32_t frame0, uint32_t frame1,
  178. float alpha
  179. );
  180. // skeleton, animation layers and bone physics of a puppet or 3D model, the same pose update in 2.8.42 (images
  181. // sub_1401FDF90, models sub_14021C480): rest pose, layer blends, physics on scene transforms
  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. /** Created layers removed since the last call, alive until their property scripts are dropped */
  205. std::vector<PuppetActiveAnimation> takeRemovedLayers ();
  206. /** Clip events fired this frame, in layer order */
  207. [[nodiscard]] std::vector<std::string> takeFiredEvents ();
  208. /** After the pose: every layer that ended runs dispatch (its ended callbacks), playSingleAnimation() ones go */
  209. void finishEndedLayers (const std::function<void (size_t)>& dispatch);
  210. // steps the layer clocks and builds the pose; models pass themselves as host for cross-clip frames and root motion
  211. void updatePose (const glm::mat4& objectWorld, PuppetRootMotionHost* host = nullptr);
  212. void updateMorphWeights (const std::vector<PuppetLayerSample>& samples);
  213. /** sub_1401FDF90 for meshes with flag 8: every bone's draw order from MDLS, moved by the layers' v6 tracks */
  214. void updateDrawOrder (const std::vector<PuppetLayerSample>& samples);
  215. /** sub_1401FDF90, mesh flag 4 */
  216. void updateBoneAlpha (const std::vector<PuppetLayerSample>& samples);
  217. /** sub_1401FDF90, mesh flag 2 */
  218. void updateBlendMap (const std::vector<PuppetLayerSample>& samples);
  219. /** sub_1401FDF90 */
  220. void updateConstraintWeights (const std::vector<PuppetLayerSample>& samples);
  221. /** sub_140225900 for one model layer after its blend, rest is what the layers above leave of it */
  222. void applyRootMotion (
  223. PuppetActiveAnimation& layer, const PuppetLayerSample& sample, std::vector<glm::vec3>& positions,
  224. std::vector<glm::quat>& orientations, float rest, PuppetRootMotionHost& host
  225. );
  226. void
  227. composePose (const std::vector<int>& parents, const std::vector<glm::mat4>& locals, const glm::mat4& objectWorld);
  228. [[nodiscard]] bool hasPose () const;
  229. [[nodiscard]] int findBone (const std::string& name) const;
  230. /** First attachment point of that name, -1 without one (image/model vtable slot 14, sub_1401FD510/sub_1402248C0) */
  231. [[nodiscard]] int findAttachment (const std::string& name) const;
  232. /** An attachment point in model space, its bone's model matrix times the point (slot 15, sub_1401FD5C0/
  233. * sub_140224970); nothing for an index out of range or before the bones exist */
  234. [[nodiscard]] std::optional<glm::mat4> attachmentMatrix (int index) const;
  235. [[nodiscard]] const glm::mat4& getBoneTransform (int bone) const;
  236. /** sub_1401FD690: first bone box in reverse hit order, name or index */
  237. [[nodiscard]] std::optional<std::string> imageHitBox (const glm::vec3& origin, const glm::vec3& direction) const;
  238. /** sub_140223810: the box the line enters first, local gets the entry point in its space */
  239. [[nodiscard]] std::optional<std::string> modelHitBox (
  240. const glm::vec3& origin, const glm::vec3& direction, const glm::mat4& objectWorld, glm::vec3& local
  241. ) const;
  242. [[nodiscard]] std::string hitBoxName (int bone) const;
  243. void setBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld);
  244. [[nodiscard]] const glm::mat4& getLocalBoneTransform (int bone) const;
  245. void setLocalBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld);
  246. void applyBonePhysicsImpulse (int bone, const glm::vec3& directional, const glm::vec3& angularDegrees);
  247. void resetBonePhysics (int bone);
  248. /** model space bone matrices times the inverse bind ones, what the vertices are skinned with */
  249. [[nodiscard]] std::vector<glm::mat4> skinMatrices () const;
  250. /** sub_140226A10: union of the visible layers' MDLA v5 boxes, false when none has one */
  251. [[nodiscard]] bool clipBounds (glm::vec3& min, glm::vec3& max) const;
  252. /** Where the file's MDMP section (morph targets) starts, 0 without one */
  253. [[nodiscard]] size_t getMorphSection () const { return this->morphSection; }
  254. std::vector<PuppetBone> bones = {};
  255. std::vector<PuppetAnimationClip> clips = {};
  256. std::vector<PuppetAttachmentPoint> attachmentPoints = {};
  257. std::vector<PuppetActiveAnimation> layers = {};
  258. /** per mesh, rebuilt by every updatePose () (sub_14021C480) */
  259. std::vector<PuppetMorphWeights> morphWeights = {};
  260. /** models clamp blended layer weights to 0..1, images don't */
  261. bool morphBlendClamped = true;
  262. /** mesh flag 4, instance +616 */
  263. bool boneAlphaEnabled = false;
  264. std::vector<float> boneAlpha = {};
  265. /** instance +848, four g_BlendMap rows */
  266. std::array<float, 16> blendMap = {};
  267. size_t morphSection = 0;
  268. /** MDLS v3+ per bone order (instance +496), added to the order of every part of that bone */
  269. std::vector<int> boneDrawOrder = {};
  270. /** walked from the end */
  271. std::vector<int> boneHitOrder = {};
  272. /** set by the image for a mesh with flag 8: the pose update then keeps drawOrder (instance +640) */
  273. bool drawOrderEnabled = false;
  274. std::vector<float> drawOrder = {};
  275. /** a layer wrote drawOrder this frame, the parts get sorted again */
  276. bool drawOrderTouched = false;
  277. std::vector<PuppetExtra> extras = {};
  278. PuppetIKRig ik = {};
  279. /** bind pose in model space (P+808) */
  280. std::vector<glm::mat4> bindModel = {};
  281. /** MDLE0002 local bind matrices */
  282. std::vector<glm::mat4> layerImageBindLocal = {};
  283. /** sub_1401D6D30: MDLE0002 locals if any, else MDLS's */
  284. [[nodiscard]] std::vector<glm::mat4> layerImageBindModel () const;
  285. /** P+736 */
  286. std::vector<glm::mat4> extraModel = {};
  287. bool hasIK = false;
  288. /** the bones in model space (WE images P+712), starts at the bind pose */
  289. std::vector<glm::mat4> boneModel = {};
  290. /** this frame's local matrices (P+784) and scene matrices (P+832), empty until the first update */
  291. std::vector<glm::mat4> boneLocal = {};
  292. std::vector<glm::mat4> boneScene = {};
  293. /** Bone physics state and last frame's scene transforms, empty until the first frame */
  294. std::vector<PuppetBonePhysicsState> physicsState = {};
  295. std::vector<glm::mat4> physicsPreviousScene = {};
  296. /** P+952 */
  297. std::vector<PuppetRopeJoint> ropeJoints = {};
  298. /** puppet +592 */
  299. std::vector<float> constraintWeights = {};
  300. PuppetRopeEnvironment ropeEnvironment = {};
  301. bool hasPhysics = false;
  302. /** The rest pose isn't the bind pose, the mesh needs skinning even when nothing moves */
  303. bool hasRestPose = false;
  304. size_t nextLayerSerial = 0;
  305. size_t removeLayers (const std::function<bool (const PuppetActiveAnimation&)>& predicate);
  306. std::vector<PuppetActiveAnimation> removedLayers = {};
  307. std::vector<std::string> firedEvents = {};
  308. /** g_Time of the last clock step, so a scene drawn on several outputs steps once per frame */
  309. float clockTime = -1.0f;
  310. /** a script wrote bone matrices, the mesh has to be skinned from then on */
  311. bool poseScripted = false;
  312. /** the pose differs from the bind pose (animation, physics or scripts) */
  313. bool poseAnimated = false;
  314. };
  315. } // namespace WallpaperEngine::Render::Objects